diff --git a/.bumpversion.toml b/.bumpversion.toml index af2f32902..bbf036dc8 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.17" +current_version = "0.42.0-beta.9" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. @@ -70,6 +70,11 @@ filename = "rust/lancedb/Cargo.toml" replace = "\nversion = \"{new_version}\"" search = "\nversion = \"{current_version}\"" +[[tool.bumpversion.files]] +filename = "rust/lancedb/cli/Cargo.toml" +replace = "\nversion = \"{new_version}\"" +search = "\nversion = \"{current_version}\"" + [[tool.bumpversion.files]] filename = "nodejs/Cargo.toml" replace = "\nversion = \"{new_version}\"" diff --git a/.github/actions/setup-protoc/action.yml b/.github/actions/setup-protoc/action.yml index a99cf3320..d61af5632 100644 --- a/.github/actions/setup-protoc/action.yml +++ b/.github/actions/setup-protoc/action.yml @@ -52,7 +52,8 @@ runs: Linux/X64) platform="linux-x86_64"; sha256="$LINUX_X86_64_SHA256" ;; Linux/ARM64) platform="linux-aarch_64"; sha256="$LINUX_AARCH_64_SHA256" ;; macOS/*) platform="osx-universal_binary"; sha256="$OSX_SHA256" ;; - Windows/X64) platform="win64"; sha256="$WIN64_SHA256" ;; + # Windows 11 Arm runners can execute the upstream x64 protoc binary. + Windows/X64|Windows/ARM64) platform="win64"; sha256="$WIN64_SHA256" ;; *) echo "Unsupported runner: $RUNNER_OS_NAME/$RUNNER_ARCH_NAME" >&2; exit 1 ;; esac zip="$RUNNER_TEMP/protoc.zip" diff --git a/.github/vale/README.md b/.github/vale/README.md index 2cfbd1633..94a11bfd8 100644 --- a/.github/vale/README.md +++ b/.github/vale/README.md @@ -4,10 +4,11 @@ come from the `LanceDB.zip` asset of `lancedb/docs` release `vale-lancedb-v0.1.0`, whose archive SHA-256 is `0730a43e919774121068811d5687c61dfc7a0421cff78e1393f5e565b622cb0f`. -`ProductNames` no longer swaps in "LanceDB OSS". +`ProductNames` no longer swaps in "LanceDB OSS" and now recommends +"LanceDB Enterprise" for the retired "LanceDB Distributed" name. The product-terminology rules were added here: `EmbeddedName`, -`RemoteExecution`, `OSSProduct`, `DistributedEnterprise`, `InternalNames` +`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 `.github/vale` with `vale test --coverage styles`. diff --git a/.github/vale/styles/LanceDB/DistributedEnterprise.yml b/.github/vale/styles/LanceDB/DistributedEnterprise.yml deleted file mode 100644 index 813d10375..000000000 --- a/.github/vale/styles/LanceDB/DistributedEnterprise.yml +++ /dev/null @@ -1,19 +0,0 @@ -extends: existence -message: "'%s' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#names -level: warning -ignorecase: false -tokens: - - 'Distributed(?:\s+(?:and|or)\s+|\s*/\s*)(?:LanceDB\s+)?Enterprise' - - 'Enterprise(?:\s+(?:and|or)\s+|\s*/\s*)(?:LanceDB\s+)?Distributed' -tests: - - name: flags Distributed and Enterprise side by side - input: Choose Distributed or Enterprise. LanceDB Enterprise and LanceDB Distributed differ, and so does Distributed/Enterprise. - want: | - 1:8:LanceDB.DistributedEnterprise:'Distributed or Enterprise' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both. - 1:43:LanceDB.DistributedEnterprise:'Enterprise and LanceDB Distributed' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both. - 1:98:LanceDB.DistributedEnterprise:'Distributed/Enterprise' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both. - - name: leaves the defining sentence and the Embedded pair alone - input: | - LanceDB Enterprise runs LanceDB Distributed. Compare Embedded and Distributed execution. Distributed search and enterprise teams are fine. - want: '' diff --git a/.github/vale/styles/LanceDB/LegacyCloud.yml b/.github/vale/styles/LanceDB/LegacyCloud.yml index 668f66011..932b7a7db 100644 --- a/.github/vale/styles/LanceDB/LegacyCloud.yml +++ b/.github/vale/styles/LanceDB/LegacyCloud.yml @@ -1,5 +1,5 @@ extends: existence -message: "'%s' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise' or 'LanceDB Distributed'." +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 level: suggestion ignorecase: false @@ -13,8 +13,8 @@ tests: - name: suggests checking each LanceDB Cloud mention input: Connect to LanceDB Cloud with an API key. Cloud/Enterprise users get the cache. want: | - 1:12:LanceDB.LegacyCloud:'LanceDB Cloud' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise' or 'LanceDB Distributed'. - 1:43:LanceDB.LegacyCloud:'Cloud/Enterprise' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise' or 'LanceDB Distributed'. + 1:12:LanceDB.LegacyCloud:'LanceDB Cloud' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise'. + 1:43:LanceDB.LegacyCloud:'Cloud/Enterprise' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise'. - name: leaves other clouds and code alone input: | Deploy into your own cloud account on Google Cloud. Pass `LanceDB Cloud` as a literal. diff --git a/.github/vale/styles/LanceDB/ProductNames.yml b/.github/vale/styles/LanceDB/ProductNames.yml index 2122679ef..42cde9869 100644 --- a/.github/vale/styles/LanceDB/ProductNames.yml +++ b/.github/vale/styles/LanceDB/ProductNames.yml @@ -9,7 +9,8 @@ swap: '(?:Lancedb|LanceDb|lanceDB|LANCEDB|Lance DB)': LanceDB 'LanceDB (?:cloud|CLOUD)': LanceDB Cloud 'LanceDB (?:enterprise|ENTERPRISE)': LanceDB Enterprise - '(?:HuggingFace|Huggingface|Hugging face)': Hugging Face + 'LanceDB\s+Distributed': LanceDB Enterprise + '(?:Hugging Face|Hugging face|Huggingface)': HuggingFace Langchain: LangChain Typescript: TypeScript VoyageAI: Voyage AI @@ -21,13 +22,21 @@ tests: 1:32:LanceDB.ProductNames:Use 'LanceDB Cloud' instead of 'LanceDB cloud'. 1:49:LanceDB.ProductNames:Use 'LanceDB Enterprise' instead of 'LanceDB enterprise'. - name: corrects names seen misspelled in the current pages - input: Load a HuggingFace model, build a Langchain retriever in Typescript and call VoyageAI. + input: Load a Hugging Face model, build a Langchain retriever in Typescript and call VoyageAI. want: | - 1:8:LanceDB.ProductNames:Use 'Hugging Face' instead of 'HuggingFace'. - 1:35:LanceDB.ProductNames:Use 'LangChain' instead of 'Langchain'. - 1:58:LanceDB.ProductNames:Use 'TypeScript' instead of 'Typescript'. - 1:78:LanceDB.ProductNames:Use 'Voyage AI' instead of 'VoyageAI'. + 1:8:LanceDB.ProductNames:Use 'HuggingFace' instead of 'Hugging Face'. + 1:37:LanceDB.ProductNames:Use 'LangChain' instead of 'Langchain'. + 1:60:LanceDB.ProductNames:Use 'TypeScript' instead of 'Typescript'. + 1:80:LanceDB.ProductNames:Use 'Voyage AI' instead of 'VoyageAI'. - name: leaves package names, identifiers and code alone input: | The lancedb package exposes `HuggingFaceEmbeddings` and LanceDBConnection; see `Typescript` in code. want: '' + - name: uses Enterprise for the product and its execution model + input: Connect to LanceDB Distributed. + want: | + 1:12:LanceDB.ProductNames:Use 'LanceDB Enterprise' instead of 'LanceDB Distributed'. + - name: keeps technical descriptions and API identifiers + input: | + LanceDB Enterprise supports distributed search. Compare Embedded and Enterprise. Distributed training uses workers. `LanceDB Distributed` and `RemoteTable` are literal code. + want: '' diff --git a/.github/vale/styles/LanceDB/RemoteExecution.yml b/.github/vale/styles/LanceDB/RemoteExecution.yml index dc450993b..ccff9e926 100644 --- a/.github/vale/styles/LanceDB/RemoteExecution.yml +++ b/.github/vale/styles/LanceDB/RemoteExecution.yml @@ -1,5 +1,5 @@ extends: existence -message: "Avoid '%s'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product." +message: "Avoid '%s'. Write 'LanceDB Enterprise' and describe where the operation runs directly." link: https://github.com/lancedb/docs/blob/main/STYLE.md#names level: warning ignorecase: false @@ -11,18 +11,18 @@ tests: - name: flags remote as the execution model input: In remote mode, a remote table is opened through a remote connection. want: | - 1:4:LanceDB.RemoteExecution:Avoid 'remote mode'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. - 1:19:LanceDB.RemoteExecution:Avoid 'remote table'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. - 1:52:LanceDB.RemoteExecution:Avoid 'remote connection'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. + 1:4:LanceDB.RemoteExecution:Avoid 'remote mode'. Write 'LanceDB Enterprise' and describe where the operation runs directly. + 1:19:LanceDB.RemoteExecution:Avoid 'remote table'. Write 'LanceDB Enterprise' and describe where the operation runs directly. + 1:52:LanceDB.RemoteExecution:Avoid 'remote connection'. Write 'LanceDB Enterprise' and describe where the operation runs directly. - name: flags plurals and a heading input: | ## Remote tables Remote databases hold remote tables. want: | - 1:4:LanceDB.RemoteExecution:Avoid 'Remote tables'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. - 3:1:LanceDB.RemoteExecution:Avoid 'Remote databases'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. - 3:23:LanceDB.RemoteExecution:Avoid 'remote tables'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. + 1:4:LanceDB.RemoteExecution:Avoid 'Remote tables'. Write 'LanceDB Enterprise' and describe where the operation runs directly. + 3:1:LanceDB.RemoteExecution:Avoid 'Remote databases'. Write 'LanceDB Enterprise' and describe where the operation runs directly. + 3:23:LanceDB.RemoteExecution:Avoid 'remote tables'. Write 'LanceDB Enterprise' and describe where the operation runs directly. - name: leaves other remotes and code alone input: | Push to the git remote, read remote storage and fetch a remote URL. `open_table` returns a `RemoteTable`; see `remote table` in the API. diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml index d45289c2d..c8c4d0998 100644 --- a/.github/workflows/ci-scripts.yml +++ b/.github/workflows/ci-scripts.yml @@ -9,6 +9,11 @@ on: - python/pyproject.toml - ci/check_cargo_lock.py - ci/check_sdist.py + - ci/extract_sdk_doc_links.py + - ci/build_cli_linux.sh + - ci/package_cli.py + - .bumpversion.toml + - rust/lancedb/cli/Cargo.toml - ci/set_lance_version.py - ci/tests/** - .github/workflows/ci-scripts.yml @@ -18,6 +23,11 @@ on: - python/pyproject.toml - ci/check_cargo_lock.py - ci/check_sdist.py + - ci/extract_sdk_doc_links.py + - ci/build_cli_linux.sh + - ci/package_cli.py + - .bumpversion.toml + - rust/lancedb/cli/Cargo.toml - ci/set_lance_version.py - ci/tests/** - .github/workflows/ci-scripts.yml diff --git a/.github/workflows/cli-release.yml b/.github/workflows/cli-release.yml new file mode 100644 index 000000000..2ec74e5f3 --- /dev/null +++ b/.github/workflows/cli-release.yml @@ -0,0 +1,167 @@ +name: CLI release packages + +on: + workflow_call: + workflow_dispatch: + pull_request: + paths: + - 'rust/lancedb/**' + - 'Cargo.toml' + - 'Cargo.lock' + - 'rust-toolchain.toml' + - '.cargo/config.toml' + - '.bumpversion.toml' + - 'LICENSE' + - 'RUST_THIRD_PARTY_LICENSES.html' + - 'ci/build_cli_linux.sh' + - 'ci/package_cli.py' + - 'ci/tests/test_package_cli.py' + - '.github/actions/setup-protoc/**' + - '.github/workflows/cli-release.yml' + - '.github/workflows/gh-release.yml' + +permissions: + contents: read + +concurrency: + group: cli-packages-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + version: + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-python@v6 + with: + python-version: '3.13' + - name: Validate release version before building + id: version + run: | + version=$(python ci/package_cli.py version) + echo "version=$version" >> "$GITHUB_OUTPUT" + + build: + needs: version + timeout-minutes: 180 + strategy: + fail-fast: false + matrix: + include: + - target: x86_64-unknown-linux-gnu + runner: ubuntu-2404-8x-x64 + image: quay.io/pypa/manylinux_2_28_x86_64 + protoc: linux-x86_64 + - target: aarch64-unknown-linux-gnu + runner: ubuntu-2404-8x-arm64 + image: quay.io/pypa/manylinux_2_28_aarch64 + protoc: linux-aarch_64 + - target: aarch64-apple-darwin + runner: warp-macos-14-arm64-6x + runs-on: ${{ matrix.runner }} + env: + CLI_TARGET: ${{ matrix.target }} + CLI_VERSION: ${{ needs.version.outputs.version }} + MACOSX_DEPLOYMENT_TARGET: '14.0' + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-python@v6 + with: + python-version: '3.13' + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1 + with: + # Leave .cargo/config.toml's CPU/feature flags in effect. + rustflags: '' + cache: false + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + with: + key: cli-release-${{ matrix.target }} + save-if: ${{ github.event_name == 'pull_request' || github.ref == 'refs/heads/main' }} + - uses: ./.github/actions/setup-protoc + id: protoc + with: + install: ${{ runner.os == 'macOS' }} + - name: Add swap for Arm fat LTO + if: matrix.target == 'aarch64-unknown-linux-gnu' + run: | + swap_file="$RUNNER_TEMP/lancedb-cli-swap" + sudo fallocate --length 16G "$swap_file" + sudo chmod 600 "$swap_file" + sudo mkswap "$swap_file" + sudo swapon "$swap_file" + - name: Build Linux CLI against glibc 2.28 + if: runner.os == 'Linux' + env: + MANYLINUX_IMAGE: ${{ matrix.image }} + PROTOC_PLATFORM: ${{ matrix.protoc }} + PROTOC_VERSION: ${{ steps.protoc.outputs.version }} + PROTOC_SHA256: ${{ matrix.protoc == 'linux-x86_64' && steps.protoc.outputs.linux-x86_64-sha256 || steps.protoc.outputs.linux-aarch_64-sha256 }} + run: | + docker run --rm \ + --volume "$PWD:/workspace" --workdir /workspace \ + --volume "$HOME/.cargo:/cargo" --env CARGO_HOME=/cargo \ + --volume "$HOME/.rustup:/rustup" --env RUSTUP_HOME=/rustup \ + --env CLI_TARGET --env PROTOC_PLATFORM --env PROTOC_VERSION --env PROTOC_SHA256 \ + "$MANYLINUX_IMAGE" bash ci/build_cli_linux.sh + - name: Build macOS CLI + if: runner.os == 'macOS' + run: | + cargo build --locked --release -p lancedb-cli --bin lancedb --target "$CLI_TARGET" + strip -S "target/$CLI_TARGET/release/lancedb" + # Stripping can invalidate the linker's ad-hoc signature on Apple Silicon. + codesign --force --sign - "target/$CLI_TARGET/release/lancedb" + - name: Package, inspect runtime dependencies, and smoke-test archive + run: | + python ci/package_cli.py package \ + --binary "target/$CLI_TARGET/release/lancedb" --target "$CLI_TARGET" --output dist + - name: Smoke-test Linux archive on a clean glibc 2.28 system + if: runner.os == 'Linux' + run: | + docker run --rm --volume "$PWD/dist:/artifacts:ro" \ + --env CLI_TARGET --env CLI_VERSION almalinux:8 bash -euo pipefail -c ' + dnf install -y libstdc++ + mkdir -p /tmp/check /tmp/cli-home + export HOME=/tmp/cli-home XDG_CONFIG_HOME=/tmp/cli-home/.config + stem="lancedb-v${CLI_VERSION}-${CLI_TARGET}" + tar -xzf "/artifacts/${stem}.tar.gz" -C /tmp/check + cli="/tmp/check/${stem}/lancedb" + "$cli" --help + test "$("$cli" --version)" = "lancedb ${CLI_VERSION}" + "$cli" profile list + ' + - uses: actions/upload-artifact@v7 + with: + name: cli-archive-${{ matrix.target }} + path: dist/*.tar.gz + if-no-files-found: error + + assemble: + needs: [version, build] + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-python@v6 + with: + python-version: '3.13' + - uses: actions/download-artifact@v8 + with: + pattern: cli-archive-* + merge-multiple: true + path: dist + - name: Require all three archives and generate checksums + run: | + python ci/package_cli.py checksums --output dist + python ci/package_cli.py verify --output dist + - uses: actions/upload-artifact@v7 + with: + name: cli-release + path: dist/* + if-no-files-found: error diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml index eb57a3804..8d8763e1d 100644 --- a/.github/workflows/cli.yml +++ b/.github/workflows/cli.yml @@ -14,7 +14,7 @@ jobs: test: strategy: matrix: - os: [ubuntu-24.04, macos-14] + os: [ubuntu-24.04, macos-15] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v6 @@ -24,6 +24,11 @@ jobs: with: components: clippy - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + with: + # Restoring compiled targets can exhaust the hosted runner disk. + prefix-key: v1-cli-downloads + cache-targets: false + save-if: ${{ github.ref == 'refs/heads/main' }} - name: Install Linux prerequisites if: runner.os == 'Linux' run: sudo apt-get update && sudo apt-get install -y protobuf-compiler libssl-dev clang diff --git a/.github/workflows/codex-fix-ci.yml b/.github/workflows/codex-fix-ci.yml deleted file mode 100644 index 8172acfac..000000000 --- a/.github/workflows/codex-fix-ci.yml +++ /dev/null @@ -1,179 +0,0 @@ -name: Codex Fix CI - -on: - workflow_dispatch: - inputs: - workflow_run_url: - description: "Failing CI workflow run URL (e.g., https://github.com/lancedb/lancedb/actions/runs/12345678)" - required: true - type: string - branch: - description: "Branch to fix (e.g., main, release/v2.0, or feature-branch)" - required: true - type: string - guidelines: - description: "Additional guidelines for the fix (optional)" - required: false - type: string - -permissions: - contents: write - pull-requests: write - actions: read - -jobs: - fix-ci: - runs-on: warp-ubuntu-latest-x64-4x - timeout-minutes: 60 - env: - CC: clang - CXX: clang++ - steps: - - name: Show inputs - run: | - echo "workflow_run_url = ${{ inputs.workflow_run_url }}" - echo "branch = ${{ inputs.branch }}" - echo "guidelines = ${{ inputs.guidelines }}" - - - name: Checkout Repo - uses: actions/checkout@v6 - with: - ref: ${{ inputs.branch }} - fetch-depth: 0 - persist-credentials: true - - - name: Set up Node.js - uses: actions/setup-node@v6 - with: - # pnpm 11 (used by the nodejs install step below) requires - # Node >= 22.13; use 24 since 22 hits EOL in October. - node-version: 24 - - - name: Install Codex CLI - run: npm install -g @openai/codex - - - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: clippy, rustfmt - - - uses: Swatinem/rust-cache@v2 - - - name: Install system dependencies - run: | - sudo apt-get update - sudo apt-get install -y protobuf-compiler libssl-dev - - - name: Set up Python - uses: actions/setup-python@v5 - with: - python-version: '3.11' - - - name: Install Python dependencies - run: | - pip install maturin ruff pytest pyarrow pandas polars - - - name: Set up Java - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '11' - cache: maven - - - name: Setup pnpm - uses: pnpm/action-setup@v6 - with: - version: 11.1.1 - - name: Install Node.js dependencies for TypeScript bindings - run: | - cd nodejs - pnpm install --frozen-lockfile - - - name: Configure git user - run: | - git config user.name "lancedb automation" - git config user.email "robot@lancedb.com" - - - name: Run Codex to fix CI failure - env: - WORKFLOW_RUN_URL: ${{ inputs.workflow_run_url }} - BRANCH: ${{ inputs.branch }} - GUIDELINES: ${{ inputs.guidelines }} - GITHUB_TOKEN: ${{ secrets.ROBOT_TOKEN }} - GH_TOKEN: ${{ secrets.ROBOT_TOKEN }} - OPENAI_API_KEY: ${{ secrets.CODEX_TOKEN }} - run: | - set -euo pipefail - - cat </tmp/codex-prompt.txt - You are running inside the lancedb repository on a GitHub Actions runner. Your task is to fix a CI failure. - - Input parameters: - - Failing workflow run URL: ${WORKFLOW_RUN_URL} - - Branch to fix: ${BRANCH} - - Additional guidelines: ${GUIDELINES:-"None provided"} - - Follow these steps exactly: - - 1. Extract the run ID from the workflow URL. The URL format is https://github.com/lancedb/lancedb/actions/runs/. - - 2. Use "gh run view --json jobs,conclusion,name" to get information about the failed run. - - 3. Identify which jobs failed. For each failed job, use "gh run view --job --log-failed" to get the failure logs. - - 4. Analyze the failure logs to understand what went wrong. Common failures include: - - Compilation errors - - Test failures - - Clippy warnings treated as errors - - Formatting issues - - Dependency issues - - 5. Based on the analysis, fix the issues in the codebase: - - For compilation errors: Fix the code that doesn't compile - - For test failures: Fix the failing tests or the code they test - - For clippy warnings: Apply the suggested fixes - - For formatting issues: Run "cargo fmt --all" - - For other issues: Apply appropriate fixes - - 6. After making fixes, verify them locally: - - Run "cargo fmt --all" to ensure formatting is correct - - Run "cargo clippy --workspace --tests --all-features -- -D warnings" to check for issues - - Run ONLY the specific failing tests to confirm they pass now: - - For Rust test failures: Run the specific test with "cargo test -p " - - For Python test failures: Build with "cd python && maturin develop" then run "pytest ::" - - For Java test failures: Run "cd java && mvn test -Dtest=#" - - For TypeScript test failures: Run "cd nodejs && pnpm build && pnpm test -- --testNamePattern=''" - - Do NOT run the full test suite - only run the tests that were failing - - 7. If the additional guidelines are provided, follow them as well. - - 8. Inspect "git status --short" and "git diff" to review your changes. - - 9. Create a fix branch: "git checkout -b codex/fix-ci-". - - 10. Stage all changes with "git add -A" and commit with message "fix: resolve CI failures from run ". - - 11. Push the branch: "git push origin codex/fix-ci-". If the remote branch exists, delete it first with "gh api -X DELETE repos/lancedb/lancedb/git/refs/heads/codex/fix-ci-" then push. Do NOT use "git push --force" or "git push -f". - - 12. Create a pull request targeting "${BRANCH}": - - Title: "ci: " (e.g., "ci: fix clippy warnings in lancedb" or "ci: resolve test flakiness in vector search") - - First, write the PR body to /tmp/pr-body.md using a heredoc (cat <<'PREOF' > /tmp/pr-body.md). The body should include: - - Link to the failing workflow run - - Summary of what failed - - Description of the fixes applied - - Then run "gh pr create --base ${BRANCH} --body-file /tmp/pr-body.md". - - 13. Display the new PR URL, "git status --short", and a summary of what was fixed. - - Constraints: - - Use bash commands for all operations. - - Do not merge the PR. - - Do not modify GitHub workflow files unless they are the cause of the failure. - - If any command fails, diagnose and attempt to fix the issue instead of aborting immediately. - - If you cannot fix the issue automatically, create the PR anyway with a clear explanation of what you tried and what remains to be fixed. - - env "GH_TOKEN" is available, use "gh" tools for GitHub-related operations. - EOF - - printenv OPENAI_API_KEY | codex login --with-api-key - codex --config shell_environment_policy.ignore_default_excludes=true exec --dangerously-bypass-approvals-and-sandbox "$(cat /tmp/codex-prompt.txt)" diff --git a/.github/workflows/docs-link-check.yml b/.github/workflows/docs-link-check.yml index afa48a14a..5bcbc0102 100644 --- a/.github/workflows/docs-link-check.yml +++ b/.github/workflows/docs-link-check.yml @@ -50,6 +50,10 @@ jobs: ref: ${{ github.event.repository.default_branch }} persist-credentials: false + - name: Extract SDK documentation links + run: | + python3 ci/extract_sdk_doc_links.py --output ./lychee-inputs/sdk-doc-links.md + - name: Check links id: lychee continue-on-error: true @@ -64,10 +68,12 @@ jobs: args: >- --scheme https --scheme http + --include-fragments --no-progress --max-retries 3 --timeout 20 'docs/src/**/*.md' + './lychee-inputs/sdk-doc-links.md' format: json output: ./lychee/out.json jobSummary: false diff --git a/.github/workflows/gh-release.yml b/.github/workflows/gh-release.yml index 683d55d71..bbaade34c 100644 --- a/.github/workflows/gh-release.yml +++ b/.github/workflows/gh-release.yml @@ -1,8 +1,8 @@ name: GitHub Release # All SDKs share one version, so a single `vX.Y.Z` tag produces a single GitHub -# release covering all of them. The per-package publish workflows (PyPI, NPM, -# Cargo, Maven) trigger off the same tag independently. +# release covering all of them, including CLI binaries. The per-package publish +# workflows (PyPI, NPM, Cargo, Maven) trigger off the same tag independently. on: push: @@ -13,7 +13,11 @@ permissions: contents: read jobs: + cli: + uses: ./.github/workflows/cli-release.yml + gh-release: + needs: cli runs-on: ubuntu-latest permissions: contents: write @@ -22,6 +26,15 @@ jobs: with: fetch-depth: 0 lfs: true + - uses: actions/setup-python@v6 + with: + python-version: '3.13' + - uses: actions/download-artifact@v8 + with: + name: cli-release + path: dist + - name: Verify CLI release assets + run: python ci/package_cli.py verify --output dist - name: Extract version id: extract_version env: @@ -83,3 +96,22 @@ jobs: generate_release_notes: false name: LanceDB v${{ steps.extract_version.outputs.version }} body: ${{ steps.release_notes.outputs.changelog }} + files: | + dist/lancedb-*.tar.gz + dist/SHA256SUMS + fail_on_unmatched_files: true + overwrite_files: true + + report-failure: + runs-on: ubuntu-24.04 + needs: [cli, gh-release] + if: always() && failure() + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@v6 + - uses: ./.github/actions/create-failure-issue + with: + job-results: ${{ toJSON(needs) }} + workflow-name: ${{ github.workflow }} diff --git a/.github/workflows/make-release-commit.yml b/.github/workflows/make-release-commit.yml index 2ab69ee32..a35bff7f1 100644 --- a/.github/workflows/make-release-commit.yml +++ b/.github/workflows/make-release-commit.yml @@ -39,7 +39,9 @@ jobs: contents: write steps: - name: Output Inputs - run: echo "${{ toJSON(github.event.inputs) }}" + env: + INPUTS_JSON: ${{ toJSON(github.event.inputs) }} + run: echo "$INPUTS_JSON" - uses: actions/checkout@v6 with: fetch-depth: 0 @@ -59,10 +61,17 @@ jobs: - name: Bump version env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TYPE: ${{ inputs.type }} + BUMP_MINOR: ${{ inputs.bump-minor }} run: | pip install bump-my-version PyGithub packaging - bash ci/bump_version.sh ${{ inputs.type }} ${{ inputs.bump-minor }} + bash ci/bump_version.sh "$RELEASE_TYPE" "$BUMP_MINOR" + release_tag=$(git describe --tags --exact-match HEAD) bash ci/update_lockfiles.sh --amend + # Keep the unpublished tag on the commit that includes the synced lockfile. + if [ "$(git rev-parse "${release_tag}^{}")" != "$(git rev-parse HEAD)" ]; then + git tag --force --annotate "$release_tag" --message "$(git log -1 --format=%s)" HEAD + fi - name: Push new version tag if: ${{ !inputs.dry_run }} uses: ad-m/github-push-action@881a6320fdb16eb5318c5054f31c218aec2b324c # v1.3.0 diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index d45833def..b2db765d0 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -36,7 +36,8 @@ concurrency: jobs: linux: name: Python ${{ matrix.config.package_name }} ${{ matrix.config.platform }} manylinux${{ matrix.config.manylinux }} - timeout-minutes: 60 + # The ARM64 release build can exceed an hour with fat LTO on a cold runner. + timeout-minutes: ${{ matrix.config.platform == 'aarch64' && 120 || 60 }} strategy: matrix: config: diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index fa6ac4741..2080789d4 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -161,7 +161,16 @@ jobs: - name: Test without pylance or pandas run: | pip uninstall -y pylance pandas - pytest -vv python/tests/test_table.py python/tests/test_namespace_no_pylance.py + # These modules still import optional packages during collection or + # exercise them throughout many tests; the full run above covers them. + pytest -m "not slow and not s3_test" -vv --durations=30 python/tests \ + --ignore=python/tests/docs \ + --ignore=python/tests/test_context.py \ + --ignore=python/tests/test_db.py \ + --ignore=python/tests/test_embeddings.py \ + --ignore=python/tests/test_embeddings_slow.py \ + --ignore=python/tests/test_namespace_integration.py \ + --ignore=python/tests/test_query.py # Make sure wheels are not included in the Rust cache - name: Delete wheels run: rm -rf target/wheels @@ -171,7 +180,7 @@ jobs: matrix: features: ["default", "experimental-functions"] timeout-minutes: 30 - runs-on: macos-14 + runs-on: macos-15 defaults: run: shell: bash diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index f65123f78..9d28ac5e4 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -14,6 +14,12 @@ on: - docs/web-tests/blob-v2/rs/** - nodejs/Cargo.toml - python/Cargo.toml + - python/src/** + - python/python/lancedb/exceptions.py + - python/python/lancedb/remote/errors.py + - ci/build_no_lock.py + - ci/tests/test_build_no_lock.py + - .github/actions/setup-protoc/** - .github/workflows/rust.yml permissions: @@ -134,7 +140,8 @@ jobs: command: check advisories bans licenses sources build-no-lock: - runs-on: ubuntu-24.04 + # Keep the existing Linux runner; its available disk varies by image. + runs-on: ubuntu-2404-4x-x64 timeout-minutes: 30 env: # Need up-to-date compilers for kernels @@ -161,9 +168,22 @@ jobs: run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev + - name: Test build output cleanup + run: python3 -m unittest discover -s ci/tests -p test_build_no_lock.py -v - name: Build all run: | - cargo build --profile ci --benches --all-features --tests + df -h . + # Every target is linked, but this job never executes the test binaries. + python3 ci/build_no_lock.py + - name: Report build disk usage + if: always() + run: | + df -h . + for build_path in target "$HOME/.cargo/registry" "$HOME/.cargo/git"; do + if [ -d "$build_path" ]; then + du -h -d 2 "$build_path" + fi + done linux: timeout-minutes: 60 @@ -179,6 +199,8 @@ jobs: # Need up-to-date compilers for kernels CC: clang-18 CXX: clang++-18 + # Preserve the repository CPU flags and use setup-mold's system linker. + RUSTFLAGS: "-C target-cpu=haswell -C target-feature=+avx2,+fma,+f16c -C linker-features=-lld" steps: - uses: actions/checkout@v6 with: @@ -218,16 +240,20 @@ jobs: sudo mkswap "$swapfile" sudo swapon "$swapfile" - name: Build - run: cargo build --profile ci --all-features --tests --locked --examples + run: cargo build --profile ci -p lancedb --all-features --tests --locked --examples - name: Run feature tests run: CARGO_ARGS="--profile ci" make -C ./lancedb feature-tests - name: Run examples - run: cargo run --profile ci --all-features --example simple --locked + run: cargo run --profile ci -p lancedb --all-features --example simple --locked - name: Run blob v2 docs example # Python and TypeScript blob docs tests install preview packages. # Those builds are not guaranteed to remain available for more than # 6 months, so they stay a manual run. This example uses the workspace crate. - run: cargo run --profile ci --all-features -p lancedb-blob-v2-docs --example multimodal --locked + run: | + # The completed all-features checks leave large lancedb artifacts in target. + # Reclaim that package before building the example with a different feature set. + cargo clean --profile ci -p lancedb + cargo run --profile ci --all-features -p lancedb-blob-v2-docs --example multimodal --locked remote: timeout-minutes: 30 @@ -243,6 +269,8 @@ jobs: env: CC: clang-18 CXX: clang++-18 + # Rust's default rust-lld bypasses setup-mold's /usr/bin/ld replacement. + RUSTFLAGS: "-C target-cpu=haswell -C target-feature=+avx2,+fma,+f16c -C linker-features=-lld" GH_TOKEN: ${{ github.token }} SOPHON_READ_TOKEN: ${{ secrets.SOPHON_READ_TOKEN }} steps: @@ -270,7 +298,7 @@ jobs: timeout-minutes: 60 strategy: matrix: - mac-runner: ["macos-14", "macos-15"] + mac-runner: ["macos-15", "macos-26"] runs-on: "${{ matrix.mac-runner }}" defaults: run: @@ -324,8 +352,8 @@ jobs: # unreadable outside their own branch anyway, since GitHub scopes # caches to the creating ref. save-if: ${{ github.ref == 'refs/heads/main' }} - - name: Install Protoc v21.12 - run: choco install --no-progress protoc + - name: Install protoc + uses: ./.github/actions/setup-protoc - name: Build run: | $env:VCPKG_ROOT = $env:VCPKG_INSTALLATION_ROOT @@ -361,8 +389,8 @@ jobs: # unreadable outside their own branch anyway, since GitHub scopes # caches to the creating ref. save-if: ${{ github.ref == 'refs/heads/main' }} - - name: Install Protoc v21.12 - run: choco install --no-progress protoc + - name: Install protoc + uses: ./.github/actions/setup-protoc - name: Build run: | $env:VCPKG_ROOT = $env:VCPKG_INSTALLATION_ROOT diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c3bf61471..d053fcbb3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,7 +72,7 @@ are wrappers around the Rust library. * `node`: **Deprecated** Typescript package source code * `java`: Java package source code * `docs/src`: SDK reference, built with mkdocs -* `docs/web`: website guides for LanceDB Embedded and the APIs used by both Embedded and Distributed +* `docs/web`: website guides for LanceDB Embedded and the APIs used by both Embedded and Enterprise * `docs/web-tests`: the tests the documentation's code examples are extracted from ## Documentation @@ -84,13 +84,13 @@ it is ready for readers. ### Choose the right place - `docs/web/` holds website guides for LanceDB Embedded and the APIs used by both - Embedded and Distributed. + Embedded and Enterprise. - `docs/src/` holds the SDK reference. See [docs/README.md](docs/README.md) for its build and API-generation instructions. - `docs/web-tests/` and `rust/lancedb/tests/` hold tests used to generate the website's code examples. -Document SDK APIs here, and explain which operations work in Embedded and Distributed. +Document SDK APIs here, and explain which operations work in Embedded and Enterprise. Put Enterprise-specific deployment and operating instructions in the Enterprise documentation. @@ -150,18 +150,15 @@ example. ### Say where a feature works Use `availability` in a page's frontmatter to describe the support covered by -that page. Each product (`oss` for LanceDB Embedded, `enterprise` for LanceDB -Enterprise) is either `available` or `unavailable`; use the summary -and body for setup requirements, SDK differences and unsupported operations. -For example, a page about signing in to Enterprise could declare: +that page. Each product (`embedded` for LanceDB Embedded, `enterprise` for +LanceDB Enterprise) is `available` or `unavailable`. Use the body for setup +requirements, SDK differences and unsupported operations. For example, a page +about signing in to Enterprise could declare: ```yaml availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - These sign-in instructions apply to LanceDB Enterprise. LanceDB - Embedded has no server to sign in to. ``` Check these claims with the feature owner. Don't use `varies`, treat an API diff --git a/Cargo.lock b/Cargo.lock index bf7b12213..893fb21d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -38,6 +38,7 @@ dependencies = [ "const-random", "getrandom 0.3.4", "once_cell", + "serde", "version_check", "zerocopy", ] @@ -625,9 +626,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "aws-config" -version = "1.8.16" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f156acdd2cf55f5aa53ee416c4ac851cf1222694506c0b1f78c85695e9ca9d" +checksum = "939e256cfe0ed68e96d32f194339d88210d5c10685cff0787400158f852c6819" dependencies = [ "aws-credential-types", "aws-runtime", @@ -639,12 +640,13 @@ dependencies = [ "aws-smithy-json", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", "hex", - "http 1.5.0", + "http", "sha1 0.10.6", "time", "tokio", @@ -655,9 +657,9 @@ dependencies = [ [[package]] name = "aws-credential-types" -version = "1.2.14" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f20799b373a1be121fe3005fba0c2090af9411573878f224df44b42727fcaf7" +checksum = "576e8da35751dc85409ec1cd15999f692c277a1fbe9336780fe6f15e49dd637d" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", @@ -691,9 +693,9 @@ dependencies = [ [[package]] name = "aws-runtime" -version = "1.7.3" +version = "1.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dcd93c82209ac7413532388067dce79be5a8780c1786e5fae3df22e4dee2864" +checksum = "9a0cc2144962cc5e358467b16e3d82981b1d424a7c3d34602be0036103814a1a" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -707,10 +709,8 @@ dependencies = [ "bytes", "bytes-utils", "fastrand", - "http 0.2.12", - "http 1.5.0", - "http-body 0.4.6", - "http-body 1.1.0", + "http", + "http-body", "percent-encoding", "pin-project-lite", "tracing", @@ -719,10 +719,11 @@ dependencies = [ [[package]] name = "aws-sdk-bedrockruntime" -version = "1.130.0" +version = "1.153.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2f7bca252e3c5c8f0ed12c5501bf8b0fbadb937cd9fdd71a0ebd9d7526540f" +checksum = "89b8aeb4b1b6d5f9d377264cff21b4e4d773e66ee3c5582b4099a8fbc702bdb3" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-sigv4", @@ -733,12 +734,12 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "http-body-util", "regex-lite", "tracing", @@ -746,10 +747,11 @@ dependencies = [ [[package]] name = "aws-sdk-dynamodb" -version = "1.111.0" +version = "1.137.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc418346e3cb248c7d59e642acbcb06488b7c7cd2ba6ebc79e8003f618c60099" +checksum = "41515f51bd2b5608268336bda372065e8fd5d1ca2f684b63e5c25ae4abb62c53" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -758,22 +760,24 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", + "url", ] [[package]] name = "aws-sdk-kms" -version = "1.106.0" +version = "1.129.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2336350f96efcf9c2552b7fdb4dd07a0c1fef11f22b28fb020a9e33e7925cf9d" +checksum = "5c5cdb29ad25d71c9ee54c408a672c98d90a24a0ea6eb063025483e0e894b411" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -782,22 +786,23 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sdk-s3" -version = "1.132.0" +version = "1.157.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5575840a3a6b11f6011463ebe359320dfe5b67babb5e9b06fed6ddf809a9ab40" +checksum = "6ea9794c741520d8baec9462bcd0ad12164d4f5f78d008a8da9d6a0b7222caa8" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-sigv4", @@ -809,6 +814,7 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-smithy-xml", "aws-types", @@ -816,10 +822,9 @@ dependencies = [ "fastrand", "hex", "hmac 0.13.0", - "http 0.2.12", - "http 1.5.0", - "http-body 1.1.0", - "lru", + "http", + "http-body", + "lru 0.18.5", "percent-encoding", "regex-lite", "sha2 0.11.0", @@ -829,10 +834,11 @@ dependencies = [ [[package]] name = "aws-sdk-sso" -version = "1.98.0" +version = "1.119.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d69c77aafa20460c68b6b3213c84f6423b6e76dbf89accd3e1789a686ffd9489" +checksum = "3c414f25ec4aa9dc18f5cc8f55e18848bb509fcda4ce7c77bee6072e95806bc9" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -841,22 +847,23 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sdk-ssooidc" -version = "1.100.0" +version = "1.121.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c7e7b09346d5ca22a2a08267555843a6a0127fb20d8964cb6ecfb8fdb190225" +checksum = "bc638bb4355e6514334dcc3228cd4622f5ee54d704bd6a9010a5a91d7856d9d9" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -865,22 +872,23 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sdk-sts" -version = "1.103.0" +version = "1.124.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2249b81a2e73a8027c41c378463a81ec39b8510f184f2caab87de912af0f49b" +checksum = "3f8a0dd8fbde04ba58ad722113c7addb11bf94cf549b1ea0eb9ea427fb87198a" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -890,21 +898,21 @@ dependencies = [ "aws-smithy-query", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-smithy-xml", "aws-types", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sigv4" -version = "1.4.3" +version = "1.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68dc0b907359b120170613b5c09ccc61304eac3998ff6274b97d93ee6490115a" +checksum = "f385da9b7757ed4c8214797ad663ff534fb622006143530aa80e21f8e06ff85c" dependencies = [ "aws-credential-types", "aws-smithy-eventstream", @@ -912,15 +920,14 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "bytes", - "crypto-bigint 0.5.5", + "crypto-bigint", + "ecdsa", "form_urlencoded", "hex", "hmac 0.13.0", - "http 0.2.12", - "http 1.5.0", + "http", "p256", "percent-encoding", - "ring", "sha2 0.11.0", "subtle", "time", @@ -930,9 +937,9 @@ dependencies = [ [[package]] name = "aws-smithy-async" -version = "1.2.14" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ffcaf626bdda484571968400c326a244598634dc75fd451325a54ad1a59acfc" +checksum = "de681a9df7ff79823b759ee17061076ec049cd61a8fa28ece4293d89c9f6964e" dependencies = [ "futures-util", "pin-project-lite", @@ -941,17 +948,17 @@ dependencies = [ [[package]] name = "aws-smithy-checksums" -version = "0.64.7" +version = "0.65.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10efbbcec1e044b81600e2fc562a391951d291152d95b482d5b7e7132299d762" +checksum = "b67ecd999972b58e67cab052f5129906c08c25883bd0788ceefc55ef97d61307" dependencies = [ "aws-smithy-http", "aws-smithy-types", "bytes", "crc-fast", "hex", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "md-5", "pin-project-lite", @@ -962,9 +969,9 @@ dependencies = [ [[package]] name = "aws-smithy-eventstream" -version = "0.60.20" +version = "0.61.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faf09d74e5e32f76b8762da505a3cd59303e367a664ca67295387baa8c1d7548" +checksum = "14c8a643d0e114cae39e45415e3225793a6396698b7779a0c9e3ede731d8fc71" dependencies = [ "aws-smithy-types", "bytes", @@ -973,9 +980,9 @@ dependencies = [ [[package]] name = "aws-smithy-http" -version = "0.63.6" +version = "0.64.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba1ab2dc1c2c3749ead27180d333c42f11be8b0e934058fb4b2258ee8dbe5231" +checksum = "19af609dd5edf8b056cd0bb001c706c8b3b1458055328b334ec13d7f46f6aaa8" dependencies = [ "aws-smithy-eventstream", "aws-smithy-runtime-api", @@ -984,26 +991,25 @@ dependencies = [ "bytes-utils", "futures-core", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "percent-encoding", "pin-project-lite", - "pin-utils", "tracing", ] [[package]] name = "aws-smithy-http-client" -version = "1.1.13" +version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c3ef8931ad1c98aa6a55b4256f847f3116090819844e0dd41ea682cac5dd2d3" +checksum = "859a81364f8185349c584fb41cd8765a400cf982f447adada590cf008a9f3b85" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", "aws-smithy-types", "h2", - "http 1.5.0", + "http", "hyper", "hyper-rustls", "hyper-util", @@ -1019,9 +1025,9 @@ dependencies = [ [[package]] name = "aws-smithy-json" -version = "0.62.7" +version = "0.65.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "701a947f4797e52a911e114a898667c746c39feea467bbd1abd7b3721f702ffa" +checksum = "b45f9fc77ffe92c92c341165a01a565bd30c39ecf5aa8c0719b41719009604f9" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-schema", @@ -1030,28 +1036,31 @@ dependencies = [ [[package]] name = "aws-smithy-observability" -version = "0.2.6" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06c2315d173edbf1920da8ba3a7189695827002e4c0fc961973ab1c54abca9c" +checksum = "8e86338c869539a581bf161247762a6e87f92c5c075060057b5ed6d06632ed0c" dependencies = [ "aws-smithy-runtime-api", ] [[package]] name = "aws-smithy-query" -version = "0.60.15" +version = "0.64.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a56d79744fb3edb5d722ef79d86081e121d3b9422cb209eb03aea6aa4f21ebd" +checksum = "165f6265342a313ad6f7a1ac17a0cdba30c522039d3f41d8d6871ce8a2b34ecd" dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", + "aws-smithy-xml", "urlencoding", ] [[package]] name = "aws-smithy-runtime" -version = "1.11.3" +version = "1.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e6f5caf6fea86f8c2206541ab5857cfcda9013426cdbe8fa0098b9e2d32182" +checksum = "4cb80fb19c084da5fca9d797845735e184445e5b958599440d67529bf6ef1b64" dependencies = [ "aws-smithy-async", "aws-smithy-http", @@ -1062,29 +1071,25 @@ dependencies = [ "aws-smithy-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", - "http-body 0.4.6", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "pin-project-lite", - "pin-utils", "tokio", "tracing", ] [[package]] name = "aws-smithy-runtime-api" -version = "1.12.3" +version = "1.19.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9db177daa6ba8afb9ee1aefcf548c907abcf52065e394ee11a92780057fe0e8c" +checksum = "8c4e85cffe9944b10d576b075432bd8f98dbc081e8681cb37d5b2d87dc27bc84" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api-macros", "aws-smithy-types", "bytes", - "http 0.2.12", - "http 1.5.0", + "http", "pin-project-lite", "tokio", "tracing", @@ -1093,9 +1098,9 @@ dependencies = [ [[package]] name = "aws-smithy-runtime-api-macros" -version = "1.0.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d7396fd9500589e62e460e987ecb671bad374934e55ec3b5f498cc7a8a8a7b7" +checksum = "ce237f890a2283c9b328955c3b0918d2d5bf66a1cb6ceccd36a0047246fbc6e6" dependencies = [ "proc-macro2", "quote", @@ -1104,34 +1109,31 @@ dependencies = [ [[package]] name = "aws-smithy-schema" -version = "0.1.0" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7442cb268338f0eb8278140a107c046756aa01093d8ef5e99628d34ae09c94f5" +checksum = "9543fc722ed4865ab29fb66bd7ed0bef7b029d265ba8c587144511e30006d431" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", - "http 1.5.0", + "http", ] [[package]] name = "aws-smithy-types" -version = "1.6.4" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b791f3ac597193fe1d08b82366986eb1f5bc31f2ac6c194c0855276116c76cd" +checksum = "cf183d70774ea2cfcc101ca74a8884e4c76be8b9df65cd303f6a1175c88e8f80" dependencies = [ "base64-simd", "bytes", "bytes-utils", "futures-core", - "http 0.2.12", - "http 1.5.0", - "http-body 0.4.6", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "itoa", "num-integer", "pin-project-lite", - "pin-utils", "ryu", "serde", "time", @@ -1141,22 +1143,26 @@ dependencies = [ [[package]] name = "aws-smithy-xml" -version = "0.60.15" +version = "0.64.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ce02add1aa3677d022f8adf81dcbe3046a95f17a1b1e8979c145cd21d3d22b3" +checksum = "590fdc1a70546b2f7f2061c42eaf173fb6f26d935330d069edc04dbd8f01d924" dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", "xmlparser", ] [[package]] name = "aws-types" -version = "1.3.15" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4bbcaa9304ea40902d3d5f42a0428d1bd895a2b0f6999436fb279ffddc58ac" +checksum = "6ba0d970d3947bb064d2ae1d823efa186c1dbde88f88afa8f6549946e5d8deee" dependencies = [ "aws-credential-types", "aws-smithy-async", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "rustc_version", "tracing", @@ -1172,8 +1178,8 @@ dependencies = [ "axum-core 0.4.5", "bytes", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-util", @@ -1206,8 +1212,8 @@ dependencies = [ "bytes", "form_urlencoded", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-util", @@ -1238,8 +1244,8 @@ dependencies = [ "async-trait", "bytes", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", @@ -1258,8 +1264,8 @@ checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", @@ -1311,9 +1317,9 @@ dependencies = [ [[package]] name = "base16ct" -version = "0.1.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" [[package]] name = "base64" @@ -1577,32 +1583,36 @@ dependencies = [ [[package]] name = "candle-core" -version = "0.9.2" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c15b675b80d994b2eadb20a4bbe434eabeb454eac3ee5e2b4cf6f147ee9be091" +checksum = "d11c8be87cfbaef9ebb62fb3f850d1fc8e00cc1d11d393fdbe55a4d5c2cdb325" dependencies = [ "byteorder", "float8", "gemm", "half", + "libc", "libm", "memmap2 0.9.10", "num-traits", "num_cpus", + "parking_lot", "rand 0.9.5", "rand_distr 0.5.1", "rayon", "safetensors", "thiserror 2.0.18", + "tokenizers 0.23.2", "yoke", + "zerocopy", "zip", ] [[package]] name = "candle-nn" -version = "0.9.2" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3045fa9e7aef8567d209a27d56b692f60b96f4d0569f4c3011f8ca6715c65e03" +checksum = "437fabe77547c2447c7bdf3cc946e19db29a2832440176b419f77c80b0a9a05e" dependencies = [ "candle-core", "half", @@ -1616,14 +1626,14 @@ dependencies = [ [[package]] name = "candle-transformers" -version = "0.9.2" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b538ec4aa807c416a2ddd3621044888f188827862e2a6fcacba4738e89795d01" +checksum = "2b1e1abeac23d7df4f94e8a3852b3dbb661d332e37c3bef479507bac867187b2" dependencies = [ "byteorder", "candle-core", "candle-nn", - "fancy-regex", + "fancy-regex 0.19.2", "num-traits", "rand 0.9.5", "rayon", @@ -1639,6 +1649,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cbc" version = "0.1.2" @@ -1789,9 +1808,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.1" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ "clap_builder", "clap_derive", @@ -1799,9 +1818,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.0" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ "anstream", "anstyle", @@ -1811,14 +1830,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.1" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] @@ -1884,7 +1903,22 @@ checksum = "958c5d6ecf1f214b4c2bbbbf6ab9523a864bd136dcf71a7e8904799acfe1ad47" dependencies = [ "crossterm", "unicode-segmentation", - "unicode-width 0.2.2", + "unicode-width 0.2.3", +] + +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if 1.0.4", + "itoa", + "rustversion", + "ryu", + "serde", + "static_assertions", ] [[package]] @@ -1922,7 +1956,7 @@ dependencies = [ "encode_unicode", "libc", "once_cell", - "unicode-width 0.2.2", + "unicode-width 0.2.3", "windows-sys 0.59.0", ] @@ -2032,6 +2066,12 @@ dependencies = [ "cfg-if 1.0.4", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -2206,26 +2246,20 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "crypto-bigint" -version = "0.4.9" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef" +checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" dependencies = [ - "generic-array", - "rand_core 0.6.4", + "cpubits", + "ctutils", + "getrandom 0.4.2", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", "subtle", "zeroize", ] -[[package]] -name = "crypto-bigint" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" -dependencies = [ - "rand_core 0.6.4", - "subtle", -] - [[package]] name = "crypto-common" version = "0.1.7" @@ -2242,7 +2276,9 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710" dependencies = [ + "getrandom 0.4.2", "hybrid-array", + "rand_core 0.10.1", ] [[package]] @@ -2278,11 +2314,12 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.4" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12218662ccac37d9714f2191252553d67585b97df8c839cbe49e0bde278dc865" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", + "subtle", ] [[package]] @@ -2291,6 +2328,12 @@ version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db756b5eb7d81d31f31f660f4132f8cf5698de52fca144c143d0ae0cbb5f2e06" +[[package]] +name = "daachorse" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5614204febbc33cc07a2806aa6440b904ac012b68eecc37f4493ea4a76455a3d" + [[package]] name = "darling" version = "0.20.11" @@ -2360,6 +2403,15 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "dary_heap" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe" +dependencies = [ + "serde", +] + [[package]] name = "dashmap" version = "6.2.1" @@ -3040,16 +3092,6 @@ dependencies = [ "thiserror 2.0.18", ] -[[package]] -name = "der" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de" -dependencies = [ - "const-oid 0.9.6", - "zeroize", -] - [[package]] name = "der" version = "0.7.10" @@ -3057,7 +3099,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "pem-rfc7468", + "pem-rfc7468 0.7.0", + "zeroize", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid 0.10.2", + "pem-rfc7468 1.0.0", "zeroize", ] @@ -3246,14 +3299,17 @@ dependencies = [ [[package]] name = "ecdsa" -version = "0.14.8" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" dependencies = [ - "der 0.6.1", + "der 0.8.3", + "digest 0.11.3", "elliptic-curve", "rfc6979", - "signature 1.6.4", + "signature 3.0.0", + "spki 0.8.1", + "zeroize", ] [[package]] @@ -3264,19 +3320,20 @@ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "elliptic-curve" -version = "0.12.3" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" dependencies = [ "base16ct", - "crypto-bigint 0.4.9", - "der 0.6.1", - "digest 0.10.7", + "crypto-bigint", + "crypto-common 0.2.1", + "digest 0.11.3", "ff", - "generic-array", "group", - "pkcs8 0.9.0", - "rand_core 0.6.4", + "hybrid-array", + "pem-rfc7468 1.0.0", + "pkcs8 0.11.0", + "rand_core 0.10.1", "sec1", "subtle", "zeroize", @@ -3465,6 +3522,17 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "fancy-regex" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912" +dependencies = [ + "bit-set", + "regex-automata", + "regex-syntax", +] + [[package]] name = "fast-float" version = "0.2.0" @@ -3496,11 +3564,11 @@ dependencies = [ [[package]] name = "ff" -version = "0.12.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" dependencies = [ - "rand_core 0.6.4", + "rand_core 0.10.1", "subtle", ] @@ -3550,9 +3618,9 @@ dependencies = [ [[package]] name = "float8" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719a903cc23e4a89e87962c2a80fdb45cdaad0983a89bd150bb57b4c8571a7d5" +checksum = "c2d1f04709a8ac06e8e8042875a3c466cc4832d3c1a18dbcb9dba3c6e83046bc" dependencies = [ "half", "num-traits", @@ -3697,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4196,7 +4264,7 @@ dependencies = [ "io-uring", "itoa", "libc", - "lru", + "lru 0.16.4", "prost", "rand 0.9.5", "serde", @@ -4212,12 +4280,12 @@ dependencies = [ [[package]] name = "group" -version = "0.12.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" dependencies = [ "ff", - "rand_core 0.6.4", + "rand_core 0.10.1", "subtle", ] @@ -4232,7 +4300,7 @@ dependencies = [ "fnv", "futures-core", "futures-sink", - "http 1.5.0", + "http", "indexmap 2.14.0", "slab", "tokio", @@ -4362,7 +4430,7 @@ checksum = "629d8f3bbeda9d148036d6b0de0a3ab947abd08ce90626327fc3547a49d59d97" dependencies = [ "dirs", "futures", - "http 1.5.0", + "http", "indicatif", "libc", "log", @@ -4386,7 +4454,7 @@ dependencies = [ "anyhow", "async-trait", "bytes", - "http 1.5.0", + "http", "more-asserts", "serde", "serde_json", @@ -4440,17 +4508,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.5.0" @@ -4461,17 +4518,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.1.0" @@ -4479,7 +4525,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", - "http 1.5.0", + "http", ] [[package]] @@ -4490,8 +4536,8 @@ checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", ] @@ -4515,26 +4561,28 @@ checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" [[package]] name = "hybrid-array" -version = "0.4.12" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "subtle", "typenum", + "zeroize", ] [[package]] name = "hyper" -version = "1.9.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", "futures-channel", "futures-core", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "httparse", "httpdate", "itoa", @@ -4550,7 +4598,7 @@ version = "0.27.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ - "http 1.5.0", + "http", "hyper", "hyper-util", "rustls", @@ -4600,8 +4648,8 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "hyper", "ipnet", "libc", @@ -4886,7 +4934,7 @@ dependencies = [ "console", "number_prefix", "portable-atomic", - "unicode-width 0.2.2", + "unicode-width 0.2.3", "web-time", ] @@ -5195,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arc-swap", "arrow", @@ -5237,6 +5285,7 @@ dependencies = [ "lance-datafusion", "lance-encoding", "lance-file", + "lance-geo", "lance-index", "lance-io", "lance-linalg", @@ -5251,7 +5300,6 @@ dependencies = [ "permutation", "pin-project", "prost", - "prost-build", "prost-types", "rand 0.9.5", "rayon", @@ -5271,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-buffer", @@ -5294,7 +5342,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.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-buffer", @@ -5308,7 +5356,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.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-schema", @@ -5317,8 +5365,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrayref", "crunchy", @@ -5328,8 +5376,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-buffer", @@ -5346,6 +5394,7 @@ dependencies = [ "libc", "libm", "log", + "metrics", "moka", "num_cpus", "object_store 0.14.2", @@ -5366,8 +5415,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "arrow-array", @@ -5392,15 +5441,14 @@ dependencies = [ "log", "pin-project", "prost", - "prost-build", "tokio", "tracing", ] [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "arrow-array", @@ -5425,8 +5473,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "arrow-array", @@ -5443,8 +5491,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "proc-macro2", "quote", @@ -5453,8 +5501,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-arith", "arrow-array", @@ -5478,7 +5526,6 @@ dependencies = [ "lz4", "num-traits", "prost", - "prost-build", "serde_json", "tokio", "tracing", @@ -5488,8 +5535,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-arith", "arrow-array", @@ -5512,7 +5559,6 @@ dependencies = [ "num-traits", "object_store 0.14.2", "prost", - "prost-build", "prost-types", "serde", "tokio", @@ -5521,21 +5567,40 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ + "arrow-array", + "arrow-schema", + "arrow-select", + "async-trait", + "datafusion-common", + "datafusion-execution", + "datafusion-expr", + "datafusion-physical-expr", + "datafusion-physical-plan", + "futures", "geo-traits", "geo-types", "geoarrow-array", "geoarrow-schema", + "lance-arrow", "lance-core", + "lance-datafusion-exec", + "lance-index", + "lance-index-core", + "lance-io", + "lance-select", + "prost-types", + "roaring", "serde", + "serde_json", ] [[package]] name = "lance-index" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arc-swap", "arrow", @@ -5562,9 +5627,6 @@ dependencies = [ "dirs", "fst", "futures", - "geo-types", - "geoarrow-array", - "geoarrow-schema", "half", "hashbrown 0.16.1", "hex", @@ -5577,7 +5639,6 @@ dependencies = [ "lance-datafusion-exec", "lance-encoding", "lance-file", - "lance-geo", "lance-index-core", "lance-io", "lance-jsonb", @@ -5592,7 +5653,6 @@ dependencies = [ "num-traits", "object_store 0.14.2", "prost", - "prost-build", "prost-types", "rand 0.9.5", "rand_distr 0.5.1", @@ -5611,8 +5671,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-schema", @@ -5635,8 +5695,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "arrow-array", @@ -5649,7 +5709,7 @@ dependencies = [ "chrono", "futures", "goosefs-sdk", - "http 1.5.0", + "http", "io-uring", "lance-core", "lance-namespace", @@ -5681,8 +5741,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "byteorder", "ethnum", @@ -5699,8 +5759,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5715,8 +5775,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "async-trait", @@ -5730,8 +5790,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arc-swap", "arrow", @@ -5785,8 +5845,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-buffer", @@ -5800,8 +5860,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "arrow-array", @@ -5825,10 +5885,10 @@ dependencies = [ "num-traits", "object_store 0.14.2", "prost", - "prost-build", "prost-types", "rand 0.9.5", "rangemap", + "rayon", "roaring", "semver", "serde", @@ -5842,8 +5902,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-schema", @@ -5856,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "frostem", "icu_segmenter", @@ -5870,7 +5930,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.17" +version = "0.42.0-beta.9" dependencies = [ "ahash", "anyhow", @@ -5912,8 +5972,8 @@ dependencies = [ "futures", "half", "hf-hub", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "lance", "lance-arrow", "lance-core", @@ -5956,7 +6016,7 @@ dependencies = [ "strum_macros 0.28.0", "tempfile", "test-log", - "tokenizers", + "tokenizers 0.19.1", "tokio", "tonic", "tracing", @@ -5981,7 +6041,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.1.0" +version = "0.42.0-beta.9" dependencies = [ "anyhow", "arrow-array", @@ -5998,7 +6058,7 @@ dependencies = [ "directories", "futures", "half", - "http 1.5.0", + "http", "lancedb", "prost", "rcgen", @@ -6017,14 +6077,14 @@ dependencies = [ "toml", "tonic", "tracing", - "unicode-width 0.2.2", + "unicode-width 0.2.3", "url", "which", ] [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.17" +version = "0.42.0-beta.9" dependencies = [ "arrow-array", "arrow-buffer", @@ -6049,7 +6109,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.17" +version = "0.42.0-beta.9" dependencies = [ "arc-swap", "arrow", @@ -6071,6 +6131,7 @@ dependencies = [ "pyo3", "pyo3-async-runtimes", "pyo3-build-config", + "reqwest 0.13.5", "serde", "serde_json", "snafu 0.8.9", @@ -6199,7 +6260,7 @@ dependencies = [ "anyhow", "byteorder", "csv", - "daachorse", + "daachorse 2.1.1", "kanaria", "lindera-dictionary", "log", @@ -6226,7 +6287,7 @@ dependencies = [ "anyhow", "byteorder", "csv", - "daachorse", + "daachorse 2.1.1", "derive_builder", "encoding_rs", "encoding_rs_io", @@ -6317,6 +6378,15 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown 0.17.1", +] + [[package]] name = "lru-slab" version = "0.1.2" @@ -6606,12 +6676,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fafa6961cabd9c63bcd77a45d7e3b7f3b552b70417831fb0f56db717e72407e" -[[package]] -name = "multimap" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" - [[package]] name = "multiversion" version = "0.7.4" @@ -6671,9 +6735,9 @@ dependencies = [ [[package]] name = "napi" -version = "3.15.0" +version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a746ad50efbfb632ade1de4025519a477decbbd798cea1a6ac41d7c44f80083" +checksum = "e4febd3f6e8b57aa986853be5b24f80a1856753535219aec431cce854cd666fc" dependencies = [ "bitflags 2.11.1", "chrono", @@ -6697,9 +6761,9 @@ checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d" [[package]] name = "napi-derive" -version = "3.6.13" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ff48271a0f61abb83f3e2d1989fa71169143db95f6f948c3a8903961f2855dc" +checksum = "d32eb00f92f84cf462fc328f49082b29c2a7d2eebeb1d447d19c1f9fdd9f89ee" dependencies = [ "convert_case", "ctor", @@ -6711,9 +6775,9 @@ dependencies = [ [[package]] name = "napi-derive-backend" -version = "6.1.6" +version = "7.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2639052c5aff9956a21d7b6202fc61d5e89c5f19c72d289b7a0641ea94e8159" +checksum = "d1fe28c64d8fc12e69f9b817d0febdbe7914555760f1e353106281b8ff99cc90" dependencies = [ "convert_case", "proc-macro2", @@ -7015,7 +7079,7 @@ dependencies = [ "base64 0.22.1", "chrono", "getrandom 0.2.17", - "http 1.5.0", + "http", "rand 0.8.6", "serde", "serde_json", @@ -7113,7 +7177,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "http 1.5.0", + "http", "humantime", "itertools 0.14.0", "parking_lot", @@ -7142,7 +7206,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "http 1.5.0", + "http", "http-body-util", "httparse", "humantime", @@ -7238,7 +7302,6 @@ version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fe43e16d96bed57937eb7c4a28559bf4c5fc4a3951656505d1fdd4f856349b4" dependencies = [ - "ctor", "opendal-core", "opendal-http-transport-reqwest", "opendal-layer-concurrent-limit", @@ -7266,7 +7329,7 @@ dependencies = [ "base64 0.23.1", "bytes", "futures", - "http 1.5.0", + "http", "jiff", "log", "md-5", @@ -7289,8 +7352,8 @@ checksum = "f772ce6c137ab43647726116d505a649a88d41928fcd813438eb30b02312bcbb" dependencies = [ "bytes", "futures", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "opendal-core", "reqwest 0.13.5", ] @@ -7303,7 +7366,7 @@ checksum = "3734c648617e5ad724d49175dde8323550624f9614f50e9e81b7aafae30b1734" dependencies = [ "asyncband", "futures", - "http 1.5.0", + "http", "opendal-core", ] @@ -7346,7 +7409,7 @@ checksum = "c6cf31b02e7b44191d97c07254eea109b5da9c17210a29e478c8d0dc26dffb1f" dependencies = [ "base64 0.23.1", "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "opendal-service-azure-common", @@ -7368,7 +7431,7 @@ dependencies = [ "asyncband", "base64 0.23.1", "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "opendal-service-azure-common", @@ -7386,7 +7449,7 @@ version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8107324c3f3cb9970fe20526c2c341b7c5769acbd4699bab73bd525f5fd63d62" dependencies = [ - "http 1.5.0", + "http", "opendal-core", ] @@ -7397,7 +7460,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "feb737e6609b4fd42e4773b7b2d8d05031b63cd0df46c7ba68ddd64bae1dd3f3" dependencies = [ "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "quick-xml 0.41.0", @@ -7415,7 +7478,7 @@ checksum = "3d80eca6f9227bdf65d43e5b8d5fe75dca8cfab1da07571442a0420400847bea" dependencies = [ "async-trait", "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "percent-encoding", @@ -7452,7 +7515,7 @@ dependencies = [ "asyncband", "bytes", "hf-xet", - "http 1.5.0", + "http", "log", "opendal-core", "percent-encoding", @@ -7467,7 +7530,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0ebfa355b1d4edb0e5b2a5b86d8de9f811fae1d7baca6d65246b230b2afc0bd" dependencies = [ "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "quick-xml 0.41.0", @@ -7486,7 +7549,7 @@ dependencies = [ "base64 0.23.1", "bytes", "crc-fast", - "http 1.5.0", + "http", "log", "md-5", "opendal-core", @@ -7592,13 +7655,15 @@ checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" [[package]] name = "p256" -version = "0.11.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" dependencies = [ "ecdsa", "elliptic-curve", - "sha2 0.10.9", + "primefield", + "primeorder", + "sha2 0.11.0", ] [[package]] @@ -7702,6 +7767,15 @@ dependencies = [ "base64ct", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -7847,12 +7921,6 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - [[package]] name = "pkcs1" version = "0.7.5" @@ -7879,16 +7947,6 @@ dependencies = [ "spki 0.7.3", ] -[[package]] -name = "pkcs8" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba" -dependencies = [ - "der 0.6.1", - "spki 0.6.0", -] - [[package]] name = "pkcs8" version = "0.10.2" @@ -7901,6 +7959,16 @@ dependencies = [ "spki 0.7.3", ] +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.3", + "spki 0.8.1", +] + [[package]] name = "pkg-config" version = "0.3.33" @@ -8388,6 +8456,33 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint", + "crypto-common 0.2.1", + "ff", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "once_cell", + "primefield", + "serdect", + "wnaf", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -8416,25 +8511,6 @@ dependencies = [ "prost-derive", ] -[[package]] -name = "prost-build" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" -dependencies = [ - "heck 0.5.0", - "itertools 0.14.0", - "log", - "multimap", - "petgraph", - "prettyplease", - "prost", - "prost-types", - "regex", - "syn 2.0.117", - "tempfile", -] - [[package]] name = "prost-derive" version = "0.14.4" @@ -8932,6 +9008,17 @@ dependencies = [ "rayon", ] +[[package]] +name = "rayon-cond" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f" +dependencies = [ + "either", + "itertools 0.14.0", + "rayon", +] + [[package]] name = "rayon-core" version = "1.13.0" @@ -9098,7 +9185,7 @@ checksum = "a5e6d659fcdbca6fe2d7ef109c2e28499b7be80501f1bb86c10caf5ec8ac1219" dependencies = [ "anyhow", "form_urlencoded", - "http 1.5.0", + "http", "log", "percent-encoding", "reqsign-core", @@ -9116,7 +9203,7 @@ dependencies = [ "bytes", "form_urlencoded", "hex", - "http 1.5.0", + "http", "log", "percent-encoding", "quick-xml 0.41.0", @@ -9135,7 +9222,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff250f0fd0b913fbd565e405acc553da0f13bde30bfb5403178c9d0313cdc15f" dependencies = [ "bytes", - "http 1.5.0", + "http", "log", "quick-xml 0.41.0", "reqsign-aws-core", @@ -9153,7 +9240,7 @@ dependencies = [ "base64 0.23.1", "bytes", "form_urlencoded", - "http 1.5.0", + "http", "log", "pem", "percent-encoding", @@ -9176,7 +9263,7 @@ dependencies = [ "futures", "hex", "hmac 0.13.0", - "http 1.5.0", + "http", "jiff", "log", "mea", @@ -9208,7 +9295,7 @@ checksum = "272a5813571885c1455ffe106f0c768577e6ce69313446d4476e8d41dcf6ac5a" dependencies = [ "bytes", "form_urlencoded", - "http 1.5.0", + "http", "log", "percent-encoding", "reqsign-aws-v4", @@ -9226,7 +9313,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "764629c90f7c3566a6d4e4641ebab9acd604ce02e16eda4d37c7d7e79e16ed90" dependencies = [ "anyhow", - "http 1.5.0", + "http", "log", "percent-encoding", "reqsign-core", @@ -9246,8 +9333,8 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-rustls", @@ -9295,8 +9382,8 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-rustls", @@ -9351,7 +9438,7 @@ checksum = "199dda04a536b532d0cc04d7979e39b1c763ea749bf91507017069c00b96056f" dependencies = [ "anyhow", "async-trait", - "http 1.5.0", + "http", "reqwest 0.13.5", "thiserror 2.0.18", "tower-service", @@ -9359,13 +9446,12 @@ dependencies = [ [[package]] name = "rfc6979" -version = "0.3.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" dependencies = [ - "crypto-bigint 0.4.9", - "hmac 0.12.1", - "zeroize", + "crypto-bigint", + "hmac 0.13.0", ] [[package]] @@ -9429,6 +9515,7 @@ checksum = "18bd8a37d17a58532776dcdf6041ce64929adca78e8489d5cacbafe99229d3e1" dependencies = [ "bytemuck", "byteorder", + "serde", ] [[package]] @@ -9684,13 +9771,15 @@ dependencies = [ [[package]] name = "safetensors" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "675656c1eabb620b921efea4f9199f97fc86e36dd6ffd1fbbe48d0f59a4987f5" +checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846" dependencies = [ "hashbrown 0.16.1", + "libc", "serde", "serde_json", + "tempfile", ] [[package]] @@ -9769,14 +9858,14 @@ dependencies = [ [[package]] name = "sec1" -version = "0.3.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" dependencies = [ "base16ct", - "der 0.6.1", - "generic-array", - "pkcs8 0.9.0", + "ctutils", + "der 0.8.3", + "hybrid-array", "subtle", "zeroize", ] @@ -9979,6 +10068,16 @@ dependencies = [ "unsafe-libyaml", ] +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", +] + [[package]] name = "serial_test" version = "3.5.0" @@ -10098,9 +10197,9 @@ dependencies = [ [[package]] name = "signature" -version = "1.6.4" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest 0.10.7", "rand_core 0.6.4", @@ -10108,12 +10207,12 @@ dependencies = [ [[package]] name = "signature" -version = "2.2.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" dependencies = [ - "digest 0.10.7", - "rand_core 0.6.4", + "digest 0.11.3", + "rand_core 0.10.1", ] [[package]] @@ -10276,16 +10375,6 @@ dependencies = [ "lock_api", ] -[[package]] -name = "spki" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b" -dependencies = [ - "base64ct", - "der 0.6.1", -] - [[package]] name = "spki" version = "0.7.3" @@ -10296,6 +10385,16 @@ dependencies = [ "der 0.7.10", ] +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.3", +] + [[package]] name = "spm_precompiled" version = "0.1.4" @@ -10549,6 +10648,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "sysctl" version = "0.6.0" @@ -10845,7 +10955,7 @@ dependencies = [ "paste", "rand 0.8.6", "rayon", - "rayon-cond", + "rayon-cond 0.3.0", "regex", "regex-syntax", "serde", @@ -10857,6 +10967,39 @@ dependencies = [ "unicode_categories", ] +[[package]] +name = "tokenizers" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc" +dependencies = [ + "ahash", + "compact_str", + "daachorse 3.0.3", + "dary_heap", + "derive_builder", + "esaxx-rs", + "fancy-regex 0.17.0", + "getrandom 0.3.4", + "itertools 0.14.0", + "log", + "macro_rules_attribute", + "monostate", + "paste", + "rand 0.9.5", + "rayon", + "rayon-cond 0.4.0", + "regex", + "regex-syntax", + "serde", + "serde_json", + "spm_precompiled", + "thiserror 2.0.18", + "unicode-normalization-alignments", + "unicode-segmentation", + "unicode_categories", +] + [[package]] name = "tokio" version = "1.54.1" @@ -10918,9 +11061,9 @@ dependencies = [ [[package]] name = "tokio-stream" -version = "0.1.18" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" dependencies = [ "futures-core", "pin-project-lite", @@ -11038,17 +11181,17 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "tonic" -version = "0.14.6" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" +checksum = "e2cdfc673aabd30fe8fee92e65837b644c37c5d47f0f97ae6d5e0f1237d15e1b" dependencies = [ "async-trait", "axum 0.8.9", "base64 0.22.1", "bytes", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-timeout", @@ -11061,6 +11204,7 @@ dependencies = [ "tokio", "tokio-rustls", "tokio-stream", + "tokio-util", "tower", "tower-layer", "tower-service", @@ -11105,8 +11249,8 @@ checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ "bitflags 2.11.1", "bytes", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "pin-project-lite", "tower-layer", @@ -11125,8 +11269,8 @@ dependencies = [ "bytes", "futures-core", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "pin-project-lite", "tokio", @@ -11254,9 +11398,9 @@ dependencies = [ [[package]] name = "typed-path" -version = "0.12.3" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" [[package]] name = "typenum" @@ -11329,9 +11473,9 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "unicode-xid" @@ -11468,9 +11612,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -12275,6 +12419,18 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.3" @@ -12302,7 +12458,7 @@ dependencies = [ "bytes", "crc32fast", "futures", - "http 1.5.0", + "http", "hyper", "more-asserts", "rand 0.10.1", @@ -12370,7 +12526,7 @@ dependencies = [ "bytes", "chrono", "gearhash", - "http 1.5.0", + "http", "itertools 0.14.0", "more-asserts", "rand 0.10.1", @@ -12454,9 +12610,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -12465,14 +12621,14 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", - "synstructure", + "syn 3.0.3", + "synstructure 0.14.0", ] [[package]] @@ -12513,7 +12669,7 @@ dependencies = [ "proc-macro2", "quote", "syn 2.0.117", - "synstructure", + "synstructure 0.13.2", ] [[package]] @@ -12536,9 +12692,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.6" +version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" dependencies = [ "serde", "yoke", @@ -12548,25 +12704,29 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.3" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] name = "zip" -version = "7.4.0" +version = "9.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980" +checksum = "e408c6cc4699dd017d53dc080cd51c2cea2b5354af57a1479bd265ed42911487" dependencies = [ "crc32fast", + "getrandom 0.4.2", "indexmap 2.14.0", + "libc", "memchr", + "nix 0.31.3", "typed-path", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index ce5a5edae..ab8e86f97 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.6", default-features = false, "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.6", default-features = false, "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.6", default-features = false, "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" @@ -49,8 +49,7 @@ arrow-select = "59.2.0" arrow-cast = "59.2.0" arrow-flight = { version = "59.2.0", features = ["flight-sql-experimental"] } async-trait = "0" -# Smithy JSON 0.63 requires the pre-1.7 Document representation; allow the MSRV pin. -aws-smithy-types = ">=1.3.6, <1.7" +aws-smithy-types = "1.9.1" base64 = "0.22" bytes = "1" datafusion = { version = "55.0.0", default-features = false } @@ -82,6 +81,7 @@ url = "2" num-traits = "0.2" oauth2 = { version = "5.0", default-features = false } regex = "1.10" +reqwest = { version = "0.13.0", default-features = false } semver = "1.0.25" serde = "1" serde_json = { version = "1", features = ["preserve_order"] } diff --git a/README.md b/README.md index ea9431298..d330801b0 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ LanceDB is a central location where developers can build, train and analyze thei ### **Ecosystem**: - **Columnar Storage**: Built on the Lance columnar format for efficient storage and analytics. - **Seamless Integration**: Python, Node.js, Rust, and REST APIs for easy integration. Native Python and Javascript/Typescript support. -- **Rich Ecosystem**: Integrations with [**LangChain** 🦜️🔗](https://python.langchain.com/docs/integrations/vectorstores/lancedb/), [**LlamaIndex** 🦙](https://gpt-index.readthedocs.io/en/latest/examples/vector_stores/LanceDBIndexDemo.html), Apache-Arrow, Pandas, Polars, DuckDB and more on the way. +- **Rich Ecosystem**: Integrations with [**LangChain** 🦜️🔗](https://docs.lancedb.com/integrations/ai/langchain), [**LlamaIndex** 🦙](https://docs.lancedb.com/integrations/ai/llamaIndex), Apache-Arrow, Pandas, Polars, DuckDB and more on the way. ## **How to Install**: diff --git a/ci/build_cli_linux.sh b/ci/build_cli_linux.sh new file mode 100644 index 000000000..dac630222 --- /dev/null +++ b/ci/build_cli_linux.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Run inside a native-architecture manylinux_2_28 container. Cargo and rustup +# are mounted from the runner; keep the image's compiler/toolchain PATH intact. +set -euo pipefail + +export PATH="/cargo/bin:$PATH" +# The manylinux images provide GCC, but do not guarantee Clang or LLD. Native +# dependencies use Clang, and the Arm linker wrapper below also requires LLD. +dnf install -y clang lld +export CC=clang CXX=clang++ +"$CC" --version +"$CXX" --version +ld.lld --version + +# Fail before Cargo downloads or compiles dependencies if either compiler or +# the linker cannot produce a runnable binary in this container. +printf 'int main(void) { return 0; }\n' > /tmp/cli-toolchain-probe.c +"$CC" -fuse-ld=lld /tmp/cli-toolchain-probe.c -o /tmp/cli-toolchain-probe +/tmp/cli-toolchain-probe +"$CXX" -fuse-ld=lld -x c++ /tmp/cli-toolchain-probe.c -o /tmp/cli-toolchain-probe +/tmp/cli-toolchain-probe + +git config --global --add safe.directory /workspace + +curl -fsSL "https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOC_VERSION}/protoc-${PROTOC_VERSION}-${PROTOC_PLATFORM}.zip" -o /tmp/protoc.zip +echo "${PROTOC_SHA256} /tmp/protoc.zip" | sha256sum -c - +unzip -q /tmp/protoc.zip -d /tmp/protoc +export PATH="/tmp/protoc/bin:$PATH" + +# GNU ld on Arm has a much higher memory peak for Lance's final link. Use a +# linker wrapper without replacing the repository's CPU and feature rustflags. +if [[ "$CLI_TARGET" == aarch64-unknown-linux-gnu ]]; then + cat > /tmp/cli-linker <<'LINKER' +#!/bin/sh +exec clang -fuse-ld=lld "$@" +LINKER + chmod 755 /tmp/cli-linker + export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=/tmp/cli-linker +fi + +cargo build --locked --release -p lancedb-cli --bin lancedb --target "$CLI_TARGET" +strip "target/$CLI_TARGET/release/lancedb" diff --git a/ci/build_no_lock.py b/ci/build_no_lock.py new file mode 100644 index 000000000..6ec156432 --- /dev/null +++ b/ci/build_no_lock.py @@ -0,0 +1,111 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Link all CI test/bench targets after the workflow removes Cargo.lock. + +This job never runs the test binaries. Discard their completed +executables while retaining normal binaries, libraries and build-script outputs. +""" + +import json +import shutil +import subprocess +import sys +from pathlib import Path + + +def discard_test_executable(message: dict, target_dir: Path) -> bool: + if message.get("reason") != "compiler-artifact": + return False + target = message["target"] + kinds = target["kind"] + # profile.test describes this build; target.test is only a manifest capability. + # Ordinary binaries may still be needed through CARGO_BIN_EXE by later targets. + if "custom-build" in kinds or not ( + message["profile"]["test"] or "test" in kinds or "bench" in kinds + ): + return False + executable = message.get("executable") + if executable is None: + return False + path = Path(executable) + if not path.resolve().is_relative_to(target_dir.resolve()): + raise ValueError(f"executable {path} is outside target directory {target_dir}") + if not path.is_file(): + return False + size = path.stat().st_size + path.unlink() + print( + json.dumps( + { + "removed_test_executable": str(path), + "target": target["name"], + "logical_bytes": size, + "filesystem_free_bytes": shutil.disk_usage(path.parent).free, + } + ), + flush=True, + ) + return True + + +def main() -> int: + metadata = subprocess.run( + ["cargo", "metadata", "--format-version=1", "--no-deps", "--all-features"], + stdout=subprocess.PIPE, + text=True, + ) + if metadata.returncode: + return metadata.returncode + target_dir = Path(json.loads(metadata.stdout)["target_directory"]) + command = [ + "cargo", + "build", + "--profile", + "ci", + "--benches", + "--all-features", + "--tests", + # Bound simultaneous compiler/linker temporary outputs as well as retained files. + "--jobs", + "1", + "--message-format=json,json-diagnostic-rendered-ansi", + ] + cleanup_failed = False + with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as process: + assert process.stdout is not None + for line in process.stdout: + try: + message = json.loads(line) + except json.JSONDecodeError: + print(line, end="", flush=True) + continue + if not isinstance(message, dict): + print(line, end="", flush=True) + continue + if message.get("reason") == "compiler-message": + diagnostic = message["message"] + sys.stderr.write( + diagnostic.get("rendered") or json.dumps(diagnostic) + "\n" + ) + sys.stderr.flush() + elif message.get("reason") == "compiler-artifact": + try: + discard_test_executable(message, target_dir) + except (OSError, ValueError) as error: + print( + f"Cannot discard completed test executable: {error}", + file=sys.stderr, + ) + cleanup_failed = True + elif message.get("reason") not in { + "build-script-executed", + "build-finished", + }: + print(line, end="", flush=True) + result = process.wait() + return result if result else int(cleanup_failed) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ci/extract_sdk_doc_links.py b/ci/extract_sdk_doc_links.py new file mode 100644 index 000000000..70453ff24 --- /dev/null +++ b/ci/extract_sdk_doc_links.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Extract documentation links defined in rust/lancedb/src/docs.rs for link checking.""" + +from __future__ import annotations + +import argparse +from pathlib import Path +import re +import sys + +REPO_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_DOCS_RS = REPO_ROOT / "rust" / "lancedb" / "src" / "docs.rs" + + +def _parse_match_arm_map(match_arms: str) -> dict[str, str | None]: + mapping: dict[str, str | None] = {} + uncommented = "\n".join( + line for line in match_arms.splitlines() if not line.strip().startswith("//") + ) + for raw_arm in uncommented.split(","): + arm = " ".join(raw_arm.split()) + if not arm or "=>" not in arm: + continue + lhs, rhs = [part.strip() for part in arm.split("=>", 1)] + variants = [ + part.strip().removeprefix("Self::") + for part in lhs.split("|") + if part.strip() + ] + if rhs == "None": + value: str | None = None + else: + str_match = re.search(r'"([^"]+)"', rhs) + if not str_match: + raise ValueError(f"unsupported match arm value: {rhs}") + value = str_match.group(1) + for variant in variants: + mapping[variant] = value + return mapping + + +def extract_doc_links(docs_rs_path: Path = DEFAULT_DOCS_RS) -> list[str]: + source = docs_rs_path.read_text(encoding="utf-8") + + base_match = re.search( + r'pub\s+const\s+DOCS_BASE_URL:\s*&str\s*=\s*"([^"]+)";', source + ) + if not base_match: + raise ValueError("DOCS_BASE_URL not found in docs.rs") + base_url = base_match.group(1) + + all_match = re.search( + r"pub\s+const\s+ALL:\s*&'static\s*\[Self\]\s*=\s*&\[(.*?)\];", + source, + re.DOTALL, + ) + if not all_match: + raise ValueError("DocLink::ALL not found in docs.rs") + variants = re.findall(r"Self::([A-Za-z0-9_]+)", all_match.group(1)) + if not variants: + raise ValueError("no variants found in DocLink::ALL") + + path_fn = re.search( + r"pub\s+const\s+fn\s+path\(self\)\s*->\s*&'static\s+str\s*\{\s*match\s+self\s*\{(.*?)\}\s*\}", + source, + re.DOTALL, + ) + anchor_fn = re.search( + r"pub\s+const\s+fn\s+anchor\(self\)\s*->\s*Option<&'static\s+str>\s*\{\s*match\s+self\s*\{(.*?)\}\s*\}", + source, + re.DOTALL, + ) + if not path_fn or not anchor_fn: + raise ValueError("DocLink::path or DocLink::anchor not found in docs.rs") + + paths = _parse_match_arm_map(path_fn.group(1)) + anchors = _parse_match_arm_map(anchor_fn.group(1)) + + urls: list[str] = [] + for variant in variants: + path = paths.get(variant) + if not path: + raise ValueError(f"missing path mapping for DocLink::{variant}") + anchor = anchors.get(variant) + url = f"{base_url}{path}#{anchor}" if anchor else f"{base_url}{path}" + if url not in urls: + urls.append(url) + return urls + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--docs-rs", + type=Path, + default=DEFAULT_DOCS_RS, + help="Path to rust/lancedb/src/docs.rs", + ) + parser.add_argument( + "--output", + type=Path, + required=True, + help="Markdown file to write extracted links to", + ) + args = parser.parse_args(argv) + + urls = extract_doc_links(args.docs_rs) + args.output.parent.mkdir(parents=True, exist_ok=True) + lines = ["# SDK documentation links", ""] + [f"- <{url}>" for url in urls] + [""] + args.output.write_text("\n".join(lines), encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ci/package_cli.py b/ci/package_cli.py new file mode 100644 index 000000000..83f244090 --- /dev/null +++ b/ci/package_cli.py @@ -0,0 +1,230 @@ +"""Package and validate standalone CLI release assets (Python 3.12+). + +Run `version` before building, `package` on each native runner, then `checksums` +after gathering the archives. Run `verify` again immediately before publication. +""" + +import argparse +import hashlib +import os +import re +import subprocess +import tarfile +import tempfile +import tomllib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +TARGETS = ( + "x86_64-unknown-linux-gnu", + "aarch64-unknown-linux-gnu", + "aarch64-apple-darwin", +) +NOTICES = ("LICENSE", "RUST_THIRD_PARTY_LICENSES.html") + + +def release_version(root: Path, ref: str) -> str: + config = tomllib.loads((root / ".bumpversion.toml").read_text())["tool"][ + "bumpversion" + ] + version = config["current_version"] + if not re.fullmatch(r"\d+\.\d+\.\d+(?:-beta\.\d+)?", version): + raise ValueError(f"Unsupported release version: {version}") + for manifest in ("rust/lancedb/Cargo.toml", "rust/lancedb/cli/Cargo.toml"): + package = tomllib.loads((root / manifest).read_text())["package"] + if package["version"] != version: + raise ValueError(f"{manifest} version does not match {version}") + if ref.startswith("refs/tags/") and ref != f"refs/tags/v{version}": + raise ValueError(f"Tag {ref} does not match v{version}") + return version + + +def archive_stem(version: str, target: str) -> str: + return f"lancedb-v{version}-{target}" + + +def command(*args: str) -> str: + return subprocess.check_output(args, text=True) + + +def check_linux_metadata(header: str, dynamic: str, symbols: str, target: str): + machine = ( + "AArch64" if target.startswith("aarch64") else "Advanced Micro Devices X86-64" + ) + if not re.search(rf"Machine:\s+{re.escape(machine)}\s*$", header, re.MULTILINE): + raise ValueError(f"ELF architecture does not match {target}") + allowed = { + "libc.so.6", + "libdl.so.2", + "libm.so.6", + "libpthread.so.0", + "librt.so.1", + "libgcc_s.so.1", + "libstdc++.so.6", + "ld-linux-x86-64.so.2", + "ld-linux-aarch64.so.1", + } + needed = set(re.findall(r"\(NEEDED\).*\[([^\]]+)\]", dynamic)) + if not needed or needed - allowed: + raise ValueError(f"Unexpected runtime libraries: {sorted(needed - allowed)}") + if re.search(r"\((?:RPATH|RUNPATH)\)", dynamic): + raise ValueError("CLI must not depend on a build-container runtime path") + # AlmaLinux 8 provides glibc 2.28, GCC 8's libstdc++, and libgcc. + limits = { + "GLIBC": (2, 28), + "GLIBCXX": (3, 4, 25), + "CXXABI": (1, 3, 11), + "GCC": (7, 0, 0), + } + for namespace, limit in limits.items(): + for value in re.findall(rf"\b{namespace}_([\d.]+)\b", symbols): + if tuple(map(int, value.split("."))) > limit: + raise ValueError( + f"Runtime symbol {namespace}_{value} exceeds Linux baseline" + ) + if "GLIBC_PRIVATE" in symbols: + raise ValueError("CLI must not require private glibc symbols") + + +def check_macos_metadata(arches: str, libraries: str, build: str): + if arches.strip() != "arm64": + raise ValueError("CLI must contain exactly the arm64 architecture") + for library in re.findall(r"^\s+(\S+) \(", libraries, re.MULTILINE): + if not library.startswith(("/usr/lib/", "/System/Library/")): + raise ValueError(f"Non-system macOS runtime library: {library}") + minimum = re.findall(r"^\s*minos ([\d.]+)\s*$", build, re.MULTILINE) + if len(minimum) != 1 or tuple(map(int, minimum[0].split("."))) != (14, 0): + raise ValueError("CLI must target macOS 14.0") + + +def check_runtime(binary: Path, target: str): + path = str(binary.resolve()) + if target.endswith("linux-gnu"): + check_linux_metadata( + command("readelf", "-h", path), + command("readelf", "-d", path), + command("readelf", "--version-info", path), + target, + ) + else: + command("codesign", "--verify", "--strict", path) + check_macos_metadata( + command("lipo", "-archs", path), + command("otool", "-L", path), + command("vtool", "-show-build", path), + ) + + +def verify_archive(archive: Path, version: str, target: str): + stem = archive_stem(version, target) + expected = {f"{stem}/{name}" for name in ("lancedb", *NOTICES)} + with tarfile.open(archive, "r:gz") as tar: + members = tar.getmembers() + if len(members) != len(expected) or {m.name for m in members} != expected: + raise ValueError(f"Unexpected archive contents: {archive.name}") + for member in members: + mode = 0o755 if member.name.endswith("/lancedb") else 0o644 + if not member.isfile() or member.mode != mode or member.size == 0: + raise ValueError(f"Invalid archive member: {member.name}") + + +def smoke_test(archive: Path, version: str, target: str): + verify_archive(archive, version, target) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + with tarfile.open(archive, "r:gz") as tar: + tar.extractall(directory, filter="data") + binary = directory / archive_stem(version, target) / "lancedb" + home = directory / "home" + home.mkdir() + env = {k: v for k, v in os.environ.items() if not k.startswith("LANCEDB_")} + env.update(HOME=str(home), XDG_CONFIG_HOME=str(home / ".config")) + for args in (("--help",), ("--version",), ("profile", "list")): + output = subprocess.run( + [str(binary), *args], + cwd=home, + env=env, + check=True, + capture_output=True, + text=True, + timeout=30, + ) + if args == ("--version",) and output.stdout.strip() != f"lancedb {version}": + raise ValueError( + f"Packaged CLI reports the wrong version: {output.stdout!r}" + ) + if args == ("--help",) and "Usage:" not in output.stdout: + raise ValueError("Packaged CLI did not print help") + if ( + args == ("profile", "list") + and "Configured profiles:" not in output.stdout + ): + raise ValueError("Packaged CLI did not list profiles") + + +def package(root: Path, binary: Path, target: str, output: Path, version: str) -> Path: + check_runtime(binary, target) + output.mkdir(parents=True, exist_ok=True) + stem = archive_stem(version, target) + archive = output / f"{stem}.tar.gz" + with tarfile.open(archive, "w:gz") as tar: + for name, source in [ + ("lancedb", binary), + *((name, root / name) for name in NOTICES), + ]: + member = tar.gettarinfo(str(source), arcname=f"{stem}/{name}") + member.mode = 0o755 if name == "lancedb" else 0o644 + member.uid = member.gid = 0 + member.uname = member.gname = "" + with source.open("rb") as file: + tar.addfile(member, file) + smoke_test(archive, version, target) + return archive + + +def checksum_lines(output: Path, version: str) -> str: + expected = {f"{archive_stem(version, target)}.tar.gz": target for target in TARGETS} + found = {path.name for path in output.glob("*.tar.gz")} + if found != expected.keys(): + raise ValueError( + f"Expected exactly these CLI archives: {sorted(expected)}; found {sorted(found)}" + ) + lines = [] + for name, target in sorted(expected.items()): + archive = output / name + verify_archive(archive, version, target) + with archive.open("rb") as file: + digest = hashlib.file_digest(file, "sha256").hexdigest() + lines.append(f"{digest} {name}\n") + return "".join(lines) + + +def verify_checksums(output: Path, version: str): + if (output / "SHA256SUMS").read_text() != checksum_lines(output, version): + raise ValueError("SHA256SUMS does not match the CLI release archives") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + commands.add_parser("version") + build = commands.add_parser("package") + build.add_argument("--binary", type=Path, required=True) + build.add_argument("--target", choices=TARGETS, required=True) + build.add_argument("--output", type=Path, required=True) + for name in ("checksums", "verify"): + commands.add_parser(name).add_argument("--output", type=Path, required=True) + args = parser.parse_args() + version = release_version(ROOT, os.environ.get("GITHUB_REF", "")) + if args.command == "version": + print(version) + elif args.command == "package": + print(package(ROOT, args.binary, args.target, args.output, version)) + elif args.command == "checksums": + (args.output / "SHA256SUMS").write_text(checksum_lines(args.output, version)) + else: + verify_checksums(args.output, version) + + +if __name__ == "__main__": + main() diff --git a/ci/set_lance_version.py b/ci/set_lance_version.py index bef97f8ad..406483a86 100644 --- a/ci/set_lance_version.py +++ b/ci/set_lance_version.py @@ -155,6 +155,9 @@ def update_cargo_toml(line_updater): lines = core_manifest.read_text().splitlines(keepends=True) for index, line in enumerate(lines): if line.startswith("lance-arrow ="): + dependency = tomllib.loads(line)["lance-arrow"] + if isinstance(dependency, dict) and dependency.get("workspace"): + continue updated = tomllib.loads(line_updater(line))["lance-arrow"] config = {"version": updated} if isinstance(updated, str) else updated if "path" in config: diff --git a/ci/tests/test_build_cli_linux.py b/ci/tests/test_build_cli_linux.py new file mode 100644 index 000000000..2ac318ad9 --- /dev/null +++ b/ci/tests/test_build_cli_linux.py @@ -0,0 +1,65 @@ +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[1] / "build_cli_linux.sh" + + +class BuildCliLinuxTest(unittest.TestCase): + def test_toolchain_failures_stop_before_downloads_and_cargo(self): + # Start with controlled tools so the host's compilers cannot mask a + # missing container dependency. No command can download or build code. + for failed_tool, exit_code in ( + ("dnf", 42), + ("clang", 127), + ("clang++", 127), + ("ld.lld", 127), + ): + with ( + self.subTest(failed_tool=failed_tool), + tempfile.TemporaryDirectory() as tmp, + ): + workdir = Path(tmp) + bin_dir = workdir / "bin" + bin_dir.mkdir() + log = workdir / "commands.log" + for name in ( + "dnf", + "clang", + "clang++", + "ld.lld", + "git", + "curl", + "cargo", + ): + status = exit_code if name == failed_tool else 0 + if name in ("git", "curl", "cargo"): + status = 99 + command = bin_dir / name + command.write_text( + f'#!/bin/sh\necho "{name}" >> "$CLI_TEST_LOG"\nexit {status}\n' + ) + command.chmod(0o755) + env = dict(os.environ, PATH=str(bin_dir), CLI_TEST_LOG=str(log)) + result = subprocess.run( + ["/bin/bash", str(SCRIPT)], + check=False, + cwd=workdir, + env=env, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, exit_code, result.stderr) + commands = log.read_text().splitlines() + self.assertEqual(commands[0], "dnf") + self.assertEqual(commands[-1], failed_tool) + self.assertNotIn("git", commands) + self.assertNotIn("curl", commands) + self.assertNotIn("cargo", commands) + + +if __name__ == "__main__": + unittest.main() diff --git a/ci/tests/test_build_no_lock.py b/ci/tests/test_build_no_lock.py new file mode 100644 index 000000000..634e8d333 --- /dev/null +++ b/ci/tests/test_build_no_lock.py @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +SCRIPT = Path(__file__).resolve().parents[1] / "build_no_lock.py" +SPEC = importlib.util.spec_from_file_location("build_no_lock", SCRIPT) +BUILD = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(BUILD) + + +class BuildNoLockTest(unittest.TestCase): + def fixture(self, directory): + root = Path(directory) + (root / "src").mkdir() + (root / "tests").mkdir() + (root / "benches").mkdir() + (root / "Cargo.toml").write_text( + '[package]\nname = "artifact_fixture"\nversion = "0.0.0"\nedition = "2024"\n' + "[workspace]\n[features]\nprobe = []\n" + '[[bin]]\nname = "fixture_cli"\npath = "src/main.rs"\n' + '[[bench]]\nname = "fixture_bench"\nharness = false\n' + '[profile.ci]\ninherits = "dev"\ndebug = 0\nincremental = false\n' + ) + (root / "build.rs").write_text( + 'fn main() { let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap());' + ' std::fs::write(out.join("generated.rs"), "pub fn value() -> u32 { 7 }").unwrap(); }' + ) + (root / "src/lib.rs").write_text( + '#[cfg(not(feature = "probe"))] compile_error!("all features must be built");\n' + 'include!(concat!(env!("OUT_DIR"), "/generated.rs"));\n' + "#[test] fn library_test() { assert_eq!(value(), 7); }\n" + ) + (root / "src/main.rs").write_text( + "fn main() { assert_eq!(artifact_fixture::value(), 7); }\n" + ) + (root / "tests/retains_binary.rs").write_text( + "#[test] fn ordinary_binary_is_available() {\n" + ' assert!(std::process::Command::new(env!("CARGO_BIN_EXE_fixture_cli"))\n' + " .status().unwrap().success()); }\n" + ) + (root / "benches/fixture_bench.rs").write_text( + "fn main() { assert_eq!(artifact_fixture::value(), 7); }\n" + ) + return root + + def run_build(self, root): + env = os.environ | {"CARGO_TARGET_DIR": str(root / "target")} + return subprocess.run( + [sys.executable, str(SCRIPT)], + cwd=root, + env=env, + text=True, + capture_output=True, + ) + + def test_links_all_targets_and_retains_compiler_inputs(self): + # Stay below the repository so rustup keeps its configured toolchain. + with tempfile.TemporaryDirectory(prefix=".no-lock-", dir=SCRIPT.parent) as temp: + root = self.fixture(temp) + result = self.run_build(root) + self.assertEqual(result.returncode, 0, result.stderr) + messages = [ + json.loads(line) + for line in result.stdout.splitlines() + if line.startswith("{") + ] + removed = [item for item in messages if "removed_test_executable" in item] + self.assertTrue( + {"artifact_fixture", "fixture_cli", "retains_binary", "fixture_bench"} + <= {item["target"] for item in removed} + ) + self.assertTrue( + all( + not Path(item["removed_test_executable"]).exists() + for item in removed + ) + ) + target = root / "target/ci" + self.assertTrue((target / "fixture_cli").is_file()) + # Cargo guarantees this binary for test execution, not compile-time reads. + subprocess.run([str(target / "fixture_cli")], check=True) + self.assertTrue(list((target / "deps").glob("libartifact_fixture*.rlib"))) + self.assertTrue(list((target / "build").glob("*/build-script-build"))) + self.assertTrue(list((target / "build").glob("*/out/generated.rs"))) + + def test_link_failure_preserves_cargo_status_and_diagnostic(self): + with tempfile.TemporaryDirectory(prefix=".no-lock-", dir=SCRIPT.parent) as temp: + root = self.fixture(temp) + with (root / "src/lib.rs").open("a") as file: + file.write( + '#[cfg(test)] unsafe extern "C" { fn missing_no_lock_probe_symbol(); }\n' + "#[test] fn linker_must_run() { unsafe { missing_no_lock_probe_symbol() } }\n" + ) + result = self.run_build(root) + self.assertEqual(result.returncode, 101, result.stderr) + self.assertIn("missing_no_lock_probe_symbol", result.stderr) + self.assertIn("linking with", result.stderr) + + def test_never_deletes_an_executable_outside_the_target_directory(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + target = root / "target" + target.mkdir() + outside = root / "other-owner-binary" + outside.write_bytes(b"keep") + message = { + "reason": "compiler-artifact", + "target": {"kind": ["test"], "name": "foreign"}, + "profile": {"test": True}, + "executable": str(outside), + } + with self.assertRaisesRegex(ValueError, "outside target directory"): + BUILD.discard_test_executable(message, target) + self.assertEqual(outside.read_bytes(), b"keep") + + +if __name__ == "__main__": + unittest.main() diff --git a/ci/tests/test_extract_sdk_doc_links.py b/ci/tests/test_extract_sdk_doc_links.py new file mode 100644 index 000000000..0e4c5fe97 --- /dev/null +++ b/ci/tests/test_extract_sdk_doc_links.py @@ -0,0 +1,47 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from ci.extract_sdk_doc_links import extract_doc_links, main + + +class TestExtractSdkDocLinks(unittest.TestCase): + def test_extracts_all_links_from_repo_docs_rs(self) -> None: + urls = extract_doc_links() + self.assertIn( + "https://docs.lancedb.com/performance#compaction-and-cleanup", + urls, + ) + self.assertIn( + "https://docs.lancedb.com/indexing/reindexing#incremental-reindexing", + urls, + ) + self.assertIn( + "https://docs.lancedb.com/search/sql", + urls, + ) + self.assertIn( + "https://docs.lancedb.com/basics/embedded-vs-enterprise", + urls, + ) + + def test_cli_writes_markdown(self) -> None: + with TemporaryDirectory() as tmp: + out = Path(tmp) / "sdk-links.md" + rc = main(["--output", str(out)]) + self.assertEqual(rc, 0) + content = out.read_text(encoding="utf-8") + self.assertIn( + "", + content, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/ci/tests/test_package_cli.py b/ci/tests/test_package_cli.py new file mode 100644 index 000000000..b56a3c8dc --- /dev/null +++ b/ci/tests/test_package_cli.py @@ -0,0 +1,228 @@ +import io +import os +import tarfile +import tempfile +import tomllib +import unittest +from pathlib import Path +from unittest.mock import patch + +from ci import package_cli as cli + +VERSION = "1.2.3-beta.4" + + +class PackageCliTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.output = self.root / "dist" + self.write_versions(VERSION) + for name in cli.NOTICES: + (self.root / name).write_text(f"Test {name}\n") + self.binary = self.root / "lancedb" + self.binary.write_text( + "#!/usr/bin/env python3\n" + "import os, sys\n" + "assert not any(k.startswith('LANCEDB_') for k in os.environ)\n" + "assert os.environ['HOME'] != os.environ.get('ORIGINAL_HOME')\n" + "assert not os.listdir(os.environ['HOME'])\n" + f"print({{('--version',): 'lancedb {VERSION}', " + "('--help',): 'Usage: lancedb', " + "('profile', 'list'): 'Configured profiles:'}[tuple(sys.argv[1:])])\n" + ) + # Packaging must restore executable permissions even if the input lacks them. + self.binary.chmod(0o644) + + def write_versions(self, version): + (self.root / ".bumpversion.toml").write_text( + f'[tool.bumpversion]\ncurrent_version = "{version}"\n' + ) + for manifest in ("rust/lancedb/Cargo.toml", "rust/lancedb/cli/Cargo.toml"): + path = self.root / manifest + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f'[package]\nversion = "{version}"\n') + + def make_package(self, target=cli.TARGETS[0]): + with patch.object(cli, "check_runtime"): + return cli.package(self.root, self.binary, target, self.output, VERSION) + + def test_stable_and_beta_versions_and_tags(self): + for version in ("1.2.3", VERSION): + self.write_versions(version) + for ref in ( + f"refs/tags/v{version}", + "refs/heads/main", + "refs/pull/1/merge", + ): + with self.subTest(version=version, ref=ref): + self.assertEqual(cli.release_version(self.root, ref), version) + + def test_mismatched_tag_and_manifests_fail(self): + with self.assertRaisesRegex(ValueError, "Tag"): + cli.release_version(self.root, "refs/tags/v1.2.3") + for manifest in ("rust/lancedb/Cargo.toml", "rust/lancedb/cli/Cargo.toml"): + self.write_versions(VERSION) + (self.root / manifest).write_text('[package]\nversion = "0.1.0"\n') + with ( + self.subTest(manifest=manifest), + self.assertRaisesRegex(ValueError, "version does not match"), + ): + cli.release_version(self.root, "refs/heads/main") + + def test_cli_participates_in_repository_version_bumps(self): + config = tomllib.loads((cli.ROOT / ".bumpversion.toml").read_text())["tool"][ + "bumpversion" + ] + entry = next( + f + for f in config["files"] + if f.get("filename") == "rust/lancedb/cli/Cargo.toml" + ) + manifest = (cli.ROOT / entry["filename"]).read_text() + version = cli.release_version(cli.ROOT, "") + self.assertIn(entry["search"].format(current_version=version), manifest) + lock = tomllib.loads((cli.ROOT / "Cargo.lock").read_text()) + package = next(p for p in lock["package"] if p["name"] == "lancedb-cli") + self.assertEqual(package["version"], version) + + def test_archive_layout_permissions_and_isolated_smoke_test(self): + with patch.dict( + os.environ, + {"LANCEDB_API_KEY": "unused", "ORIGINAL_HOME": os.environ["HOME"]}, + ): + archive = self.make_package() + self.assertEqual(archive.name, f"lancedb-v{VERSION}-{cli.TARGETS[0]}.tar.gz") + cli.verify_archive(archive, VERSION, cli.TARGETS[0]) + with tarfile.open(archive) as tar: + for member in tar.getmembers(): + self.assertEqual(member.uid, 0) + self.assertEqual(member.gid, 0) + + def test_wrong_binary_version_fails_smoke_test(self): + self.binary.write_text( + self.binary.read_text().replace(f"lancedb {VERSION}", "lancedb 0.1.0") + ) + with self.assertRaisesRegex(ValueError, "wrong version"): + self.make_package() + + def test_bad_archive_members_are_rejected(self): + archive = self.make_package() + stem = cli.archive_stem(VERSION, cli.TARGETS[0]) + for bad in ( + "missing", + "extra", + "duplicate", + "symlink", + "permissions", + "empty", + "traversal", + ): + with self.subTest(bad=bad): + with tarfile.open(archive, "w:gz") as tar: + for name in ("lancedb", *cli.NOTICES): + if bad == "missing" and name == "LICENSE": + continue + member = tarfile.TarInfo(f"{stem}/{name}") + member.mode = 0o755 if name == "lancedb" else 0o644 + member.size = 1 + if name == "lancedb": + if bad == "symlink": + member.type = tarfile.SYMTYPE + member.linkname = "/usr/bin/true" + member.size = 0 + elif bad == "permissions": + member.mode = 0o644 + elif bad == "empty": + member.size = 0 + elif bad == "traversal": + member.name = "../lancedb" + tar.addfile(member, io.BytesIO(b"x")) + if bad in ("extra", "duplicate"): + member = tarfile.TarInfo( + f"{stem}/{'LICENSE' if bad == 'duplicate' else 'extra'}" + ) + tar.addfile(member) + with self.assertRaises(ValueError): + cli.verify_archive(archive, VERSION, cli.TARGETS[0]) + + def test_checksums_require_exact_target_set_and_detect_tampering(self): + self.make_package() + with self.assertRaisesRegex(ValueError, "exactly"): + cli.checksum_lines(self.output, VERSION) + for target in cli.TARGETS[1:]: + self.make_package(target) + manifest = self.output / "SHA256SUMS" + lines = cli.checksum_lines(self.output, VERSION) + manifest.write_text(lines) + self.assertEqual(len(lines.splitlines()), 3) + cli.verify_checksums(self.output, VERSION) + # Still a valid archive, but a different payload from the published digest. + self.binary.write_text(self.binary.read_text() + "# changed\n") + self.make_package() + with self.assertRaisesRegex(ValueError, "SHA256SUMS"): + cli.verify_checksums(self.output, VERSION) + (self.output / "unexpected.tar.gz").write_bytes(b"extra") + with self.assertRaisesRegex(ValueError, "exactly"): + cli.checksum_lines(self.output, VERSION) + + +class RuntimeMetadataTest(unittest.TestCase): + def test_linux_baseline_and_architectures(self): + for target, machine in ( + (cli.TARGETS[0], "Advanced Micro Devices X86-64"), + (cli.TARGETS[1], "AArch64"), + ): + cli.check_linux_metadata( + f" Machine: {machine}\n", + " (NEEDED) Shared library: [libc.so.6]\n (NEEDED) Shared library: [libgcc_s.so.1]", + "GLIBC_2.28 GLIBCXX_3.4.25 CXXABI_1.3.11 GCC_7.0.0", + target, + ) + + def test_linux_rejects_wrong_arch_new_symbols_and_non_system_libraries(self): + header = " Machine: Advanced Micro Devices X86-64\n" + dynamic = " (NEEDED) Shared library: [libc.so.6]" + cases = [(" Machine: AArch64\n", dynamic, "GLIBC_2.28")] + for symbol in ( + "GLIBC_2.29", + "GLIBCXX_3.4.26", + "CXXABI_1.3.12", + "GCC_12.0.0", + "GLIBC_PRIVATE", + ): + cases.append((header, dynamic, symbol)) + for extra in ( + " (NEEDED) Shared library: [libssl.so.3]", + " (RUNPATH) Library runpath: [/opt/build/lib]", + ): + cases.append((header, dynamic + extra, "GLIBC_2.28")) + for args in cases: + with self.subTest(args=args), self.assertRaises(ValueError): + cli.check_linux_metadata(*args, cli.TARGETS[0]) + + def test_macos_baseline_and_system_libraries(self): + cli.check_macos_metadata( + "arm64\n", + "cli:\n\t/usr/lib/libSystem.B.dylib (compatibility version 1.0.0)", + " minos 14.0\n", + ) + + def test_macos_rejects_wrong_arch_version_and_homebrew_dependencies(self): + for args in ( + ("x86_64", "", " minos 14.0\n"), + ("arm64", "", " minos 15.0\n"), + ("arm64", "", ""), + ( + "arm64", + "\t/opt/homebrew/lib/libssl.dylib (compatibility version 3.0.0)", + " minos 14.0\n", + ), + ): + with self.subTest(args=args), self.assertRaises(ValueError): + cli.check_macos_metadata(*args) + + +if __name__ == "__main__": + unittest.main() diff --git a/ci/tests/test_set_lance_version.py b/ci/tests/test_set_lance_version.py index 1173eab84..1cc0a319c 100644 --- a/ci/tests/test_set_lance_version.py +++ b/ci/tests/test_set_lance_version.py @@ -146,6 +146,25 @@ lance_datafusion = {{ "version" = "=8.2.0-beta.4", "features" = ["substrait"], " f"{command!r} not found in {commands!r}", ) + with (workdir / "Cargo.toml").open("a") as manifest: + manifest.write('lance-arrow = "1.0.0"\n') + for inherited in ( + "lance-arrow = { workspace = true }", + "lance-arrow.workspace = true", + ): + inherited_manifest = f"[dependencies]\n{inherited}\n" + core_manifest.write_text(inherited_manifest) + result = subprocess.run( + [sys.executable, str(SCRIPT), version], + cwd=workdir, + env=env, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(core_manifest.read_text(), inherited_manifest) + def _write_fake_executables(self, fake_bin: Path) -> None: cargo = fake_bin / "cargo" cargo.write_text( diff --git a/deny.toml b/deny.toml index 602cc2820..458559936 100644 --- a/deny.toml +++ b/deny.toml @@ -131,6 +131,14 @@ ignore = [ { id = "RUSTSEC-2026-0391", reason = "zstd 0.13 via arrow-ipc 58; affected with_context API is unused" }, { id = "RUSTSEC-2026-0398", reason = "zstd-safe 7 via arrow-ipc 58; affected seekable API is not enabled" }, { id = "RUSTSEC-2026-0403", reason = "zstd-safe 7 via arrow-ipc 58; affected streaming decoder API is unused" }, + + # pin-utils: unmaintained; reviewed 2026-11-05. 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. + # 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" }, ] diff --git a/docs/src/embeddings/available_embedding_models/text_embedding_functions/oci_genai_embedding.md b/docs/src/embeddings/available_embedding_models/text_embedding_functions/oci_genai_embedding.md new file mode 100644 index 000000000..b2716a2fe --- /dev/null +++ b/docs/src/embeddings/available_embedding_models/text_embedding_functions/oci_genai_embedding.md @@ -0,0 +1,78 @@ +# OCI Generative AI Embeddings + +[Oracle Cloud Infrastructure (OCI) Generative AI](https://docs.oracle.com/en-us/iaas/Content/generative-ai/home.htm) hosts Cohere embedding models behind an OCI-native, IAM-authenticated API. + +Using the `oci-genai` embedding function requires the OCI Python SDK, which can be installed using `pip install oci`. No API key is stored in LanceDB: requests are signed by the SDK with one of the standard OCI authentication methods, so a compartment OCID and an identity that is allowed to `use generative-ai-family` in that compartment are all that is needed. + +Supported models are: + +- `cohere.embed-v4.0` (1536 dims by default; `output_dimensions` can request 256, 512, 1024 or 1536) +- `cohere.embed-english-v3.0`, `cohere.embed-multilingual-v3.0` (1024 dims) +- `cohere.embed-english-light-v3.0`, `cohere.embed-multilingual-light-v3.0` (384 dims) +- Any dedicated AI cluster endpoint OCID (`ocid1.generativeaiendpoint...`) hosting an embedding model + +Cohere embedding models are asymmetric: rows of the source column are embedded with `input_type="SEARCH_DOCUMENT"` and search queries with `input_type="SEARCH_QUERY"`. Inputs are sent in batches of at most 96 texts (the service limit), and the vector size is discovered with a single probe request unless `output_dimensions` is set. + +Supported parameters (to be passed in `create` method) are: + +| Parameter | Type | Default Value | Description | +|---|---|--------|---------| +| `name` | `str` | `"cohere.embed-v4.0"` | Model ID of an on-demand embedding model, or a dedicated AI cluster endpoint OCID. | +| `compartment_id` | `str` | `None` | OCID of the compartment the requests are authorized in and billed to. Required by the service; falls back to the `OCI_COMPARTMENT_ID` environment variable. | +| `region` | `str` | `"us-chicago-1"` | Region used to derive the inference endpoint `https://inference.generativeai..oci.oraclecloud.com`. | +| `service_endpoint` | `str` | `None` | Full inference endpoint. Overrides `region`; use it for realms with a different endpoint template. | +| `auth_type` | `str` | `"API_KEY"` | `API_KEY`, `SECURITY_TOKEN`, `INSTANCE_PRINCIPAL` or `RESOURCE_PRINCIPAL` (see below). | +| `auth_profile` | `str` | `"DEFAULT"` | Profile name in the OCI config file (`API_KEY` and `SECURITY_TOKEN` only). | +| `auth_file_location` | `str` | `"~/.oci/config"` | Path of the OCI config file (`API_KEY` and `SECURITY_TOKEN` only). | +| `truncate` | `str` | `"END"` | What to do with inputs longer than the model context: `NONE` (fail), `START` or `END` (drop tokens from that side). | +| `source_input_type` | `str` | `"SEARCH_DOCUMENT"` | `input_type` used when embedding the source column. | +| `query_input_type` | `str` | `"SEARCH_QUERY"` | `input_type` used when embedding queries. | +| `output_dimensions` | `int` | `None` | Embedding size for models that support it (`cohere.embed-v4.0`: 256, 512, 1024, 1536). | + +When a table is opened in a new process, an explicit `service_endpoint` or a non-default `region` restored from table metadata requires approval with `get_registry().allow_endpoint(...)`. The default `us-chicago-1` endpoint does not need approval. + +Authentication options: + +| `auth_type` | Identity used | +|---|---| +| `API_KEY` | User API key from profile `auth_profile` in `auth_file_location` (the setup produced by `oci setup config`). | +| `SECURITY_TOKEN` | Short-lived session token from the same profile, as written by `oci session authenticate`. | +| `INSTANCE_PRINCIPAL` | The Compute instance the code runs on; needs a dynamic group policy. | +| `RESOURCE_PRINCIPAL` | The OCI resource the code runs in (OKE workload identity, Functions, Data Science, ...). | + +Usage Example: + +```python + import lancedb + from lancedb.pydantic import LanceModel, Vector + from lancedb.embeddings import get_registry + + oci_genai = get_registry().get("oci-genai").create( + name="cohere.embed-v4.0", + compartment_id="ocid1.compartment.oc1..", + auth_type="API_KEY", + auth_profile="DEFAULT", + region="us-chicago-1", + ) + + class TextModel(LanceModel): + text: str = oci_genai.SourceField() + vector: Vector(oci_genai.ndims()) = oci_genai.VectorField() + + data = [{"text": "hello world"}, + {"text": "goodbye world"}] + + db = lancedb.connect("~/.lancedb") + tbl = db.create_table("test", schema=TextModel, mode="overwrite") + + tbl.add(data) + rs = tbl.search("hello").limit(1).to_pandas() +``` + +The compartment OCID can also be supplied at runtime instead of being stored in the table metadata, either through the `OCI_COMPARTMENT_ID` environment variable or with a registry variable: + +```python + registry = get_registry() + registry.set_var("oci_compartment", "ocid1.compartment.oc1..") + oci_genai = registry.get("oci-genai").create(compartment_id="$var:oci_compartment") +``` diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 4bac3f752..6b0ac9492 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -3,7 +3,7 @@ The LanceDB Java SDK provides a convenient way to interact with LanceDB Enterprise deployments using the Lance REST Namespace API. !!! note - The Java SDK currently only works with LanceDB Distributed, connecting to LanceDB Enterprise or LanceDB Cloud (legacy). + The Java SDK currently only connects to LanceDB Enterprise or LanceDB Cloud (legacy). LanceDB Embedded support is a work in progress. Check [LANCEDB-2848](https://github.com/lancedb/lancedb/issues/2848) for the latest progress. ## Installation @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.41.0-beta.17 + 0.42.0-beta.9 ``` diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index 14f283cc9..4876e3a52 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -182,7 +182,7 @@ Define a materialized view named `name` over the table `source`. LanceDB Embedded creation and refresh require a source build with the `experimental-functions` Cargo feature, disabled in published packages. -LanceDB Distributed operations do not require this feature. +LanceDB Enterprise operations do not require this feature. The view is populated before creation returns. Set `withNoData` to create only its definition and empty backing table. The view is a normal table: @@ -558,10 +558,11 @@ on the returned job to know when cleanup has finished. abstract dropView(name, namespacePath?): Promise ``` -Drop the view named `name` and wait for its definition to be deleted. +Drop the view named `name` and wait for catalog removal. The tables it reads are untouched: a view holds no rows of its own. Use -[dropViewAsync](Connection.md#dropviewasync) to retain the cleanup job instead of waiting on it. +[dropViewAsync](Connection.md#dropviewasync) to retain its SQL query job. Completion confirms +catalog removal; physical cleanup continues in the background. #### Parameters @@ -581,11 +582,9 @@ The tables it reads are untouched: a view holds no rows of its own. Use abstract dropViewAsync(name, namespacePath?): Promise ``` -Start dropping the view named `name` and return the job deleting its -definition, without waiting for completion. - -The name is free before this resolves. When nothing was bound to it, the -returned job is already finished and has no id. +Drop a view and return its SQL query job. +The job has type `query` and its ID is the SQL query UUID. Waiting confirms +catalog removal; physical cleanup continues in the background. #### Parameters @@ -827,9 +826,10 @@ abstract renameTable( Rename a table. -Currently only supported in LanceDB Distributed. LanceDB Embedded connections and -namespace-backed connections (via [connectNamespace](../functions/connectNamespace.md)) reject with -a "not supported" error. +Supported in LanceDB Enterprise and by namespace backends that implement +renaming. Directory namespaces support renaming tables resolved through their +manifest, including tables within or across child namespaces. LanceDB Embedded +connections and directory-listing root tables reject with a "not supported" error. #### Parameters diff --git a/docs/src/js/classes/Index.md b/docs/src/js/classes/Index.md index 7b5033160..e613882e4 100644 --- a/docs/src/js/classes/Index.md +++ b/docs/src/js/classes/Index.md @@ -252,7 +252,7 @@ static labelList(): Index Create a label list index. LabelList index is a scalar index that can be used on `List` columns to -support queries with `array_contains_all` and `array_contains_any` +support queries with `array_has_all` and `array_has_any` using an underlying bitmap index. #### Returns diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md index 74e1c00e2..8fd59c964 100644 --- a/docs/src/js/classes/Job.md +++ b/docs/src/js/classes/Job.md @@ -171,6 +171,24 @@ per fragment. `filter` is a SQL-like expression over the `state`, *** +### progress() + +```ts +progress(): Promise +``` + +Fetch a structured progress snapshot. + +Registry jobs include lifecycle and queue metadata even when their job +type does not report counters. The returned object is forward-compatible +with newer servers and job types. In-process operations return null. + +#### Returns + +`Promise`<`null` \| [`JobProgress`](../interfaces/JobProgress.md)> + +*** + ### refresh() ```ts @@ -223,11 +241,22 @@ printing it. ### wait() ```ts -wait(): Promise +wait(progressCallback?): Promise ``` Wait until the operation reaches a terminal state. +The optional callback observes the same snapshots fetched by the backend +poller that drives completion; it does not start another poller. Without a +callback, this preserves the original wait behavior. The callback is a +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`. + +#### Parameters + +* **progressCallback?**: [`JobProgressCallback`](../type-aliases/JobProgressCallback.md) + #### Returns `Promise`<`void`> diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 4398ee3ad..1fad723fe 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -71,7 +71,7 @@ Add new columns with defined values. LanceDB Embedded computed-column declaration and refresh require a source build with the `experimental-functions` Cargo feature. Published packages -disable it; LanceDB Distributed operations remain available. +disable it; LanceDB Enterprise operations remain available. The `{ computed }` form stores the expression rather than evaluating it now: the column is committed with no values, and rows get them from @@ -83,7 +83,7 @@ computed, so a mutated input is reflected by the next refresh. While a declaration reads a column, that column cannot be renamed, retyped or dropped. -In LanceDB Distributed the expression is planned by the +In LanceDB Enterprise the expression is planned by the server, and the refresh runs as a server job -- see [Table#refreshColumnAsync](Table.md#refreshcolumnasync). @@ -126,6 +126,9 @@ abstract alterColumns(columnAlterations): Promise Alter the name or nullability of columns. +Local tables reject renaming source or vector columns referenced by +`embedding_functions` schema metadata, preserving the embedding binding. + #### Parameters * **columnAlterations**: [`ColumnAlteration`](../interfaces/ColumnAlteration.md)[] @@ -354,6 +357,24 @@ vector and non-vector searches) We currently don't support custom named indexes. The index name will always be `${column}_idx`. +On LanceDB Embedded tables the index is built before the returned promise +resolves. On LanceDB Enterprise tables it resolves once the build is +scheduled. Until the build finishes, a vector index may be missing from +[Table.listIndices](Table.md#listindices), a scalar or FTS index may be listed with 0 +indexed rows, and queries won't use the index. To wait until the index is +ready, set [IndexOptions.waitTimeoutSeconds](../interfaces/IndexOptions.md#waittimeoutseconds), call +[Table.waitForIndex](Table.md#waitforindex), or use [Table.createIndexAsync](Table.md#createindexasync) and wait +on its job when the server returned a job ID. + +`waitTimeoutSeconds` waits for the submitted build when the server returns +a job ID. On older servers that don't return one, it falls back to polling +the index by name. [Table.waitForIndex](Table.md#waitforindex) always waits by name. When +replacing an existing index, those name-based waits may return before the +new build finishes because the old index can still match. +`createIndexAsync` can track a specific build only when the server returned +a job ID; otherwise it returns an already-complete job and callers must +use [Table.waitForIndex](Table.md#waitforindex) for that build. + #### Parameters * **column**: `string` @@ -410,6 +431,11 @@ Create an index, returning a handle to the indexing job. The job may already be complete when returned; callers must not assume the index exists until [Job.wait](Job.md#wait) resolves. +In LanceDB Enterprise, the returned job tracks this submission only if the +server returns a job ID. If it does not, the job is already complete and +does not wait for the background build; use [Table.waitForIndex](Table.md#waitforindex) and +account for the replacement caveat described in [Table.createIndex](Table.md#createindex). + #### Parameters * **column**: `string` @@ -504,6 +530,9 @@ underlying storage. In order to remove the data, you must subsequently call ``compact_files`` to rewrite the data without the removed columns and then call ``cleanup_files`` to remove the old files. +Local tables reject dropping source or vector columns referenced by +`embedding_functions` schema metadata, preserving the embedding binding. + #### Parameters * **columnNames**: `string`[] @@ -686,7 +715,7 @@ 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 Distributed only; reading errors needs read +capped. LanceDB Enterprise only; reading errors needs read access to the table, since a message carries the value that failed. #### Parameters @@ -843,6 +872,11 @@ abstract listIndices(): Promise List all indices that have been created with [Table.createIndex](Table.md#createindex) +On LanceDB Enterprise tables, an index whose build hasn't finished may be +missing (vector indices) or listed with 0 indexed rows (scalar and FTS +indices), and `numUnindexedRows` may be undefined. Use +[Table.waitForIndex](Table.md#waitforindex) to wait until an index is ready. + #### Returns `Promise`<[`IndexConfig`](../interfaces/IndexConfig.md)[]> @@ -909,6 +943,15 @@ Modeled after ``VACUUM`` in PostgreSQL. you have added or modified 100,000 or more records or run more than 20 data modification operations. +On a LanceDB Enterprise (remote) table, only compaction is currently +supported. Pruning old versions and index optimization are silently +skipped there instead of being attempted, so this call resolves +successfully, with zeroed pruning statistics, once the compaction job +has been submitted; it does not wait for that job to finish. +`compactionOptions` can tune the four per-job settings documented in +[CompactionOptions](../interfaces/CompactionOptions.md). Older-server errors are propagated without +retrying with the settings removed. + #### Parameters * **options?**: `Partial`<[`OptimizeOptions`](../interfaces/OptimizeOptions.md)> @@ -939,7 +982,7 @@ Prewarm one or more columns of data in the table. 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 Distributed. + This feature is currently only supported in LanceDB Enterprise. #### Returns @@ -1042,7 +1085,7 @@ for await (const batch of table.query()) { ### refreshColumn() ```ts -abstract refreshColumn(column): Promise +abstract refreshColumn(column, options?): Promise ``` Fill the rows of a computed column that hold no value yet. @@ -1051,13 +1094,17 @@ Local refresh requires a source build with `experimental-functions`. Rows appended since the last refresh are filled by the next one, and rows whose inputs changed since they were computed are recomputed; everything else is left as it is. LanceDB Embedded only: in LanceDB -Distributed a refresh runs as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync). +Enterprise a refresh runs as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync). #### Parameters * **column**: `string` The name of the computed column to fill. +* **options?**: [`RefreshColumnOptions`](../interfaces/RefreshColumnOptions.md) + Refresh options, all LanceDB + Enterprise only; see [Table#refreshColumnAsync](Table.md#refreshcolumnasync). + #### Returns `Promise`<[`RefreshColumnResult`](../interfaces/RefreshColumnResult.md)> @@ -1070,26 +1117,36 @@ number of rows filled and the new version number of the table. ### refreshColumnAsync() ```ts -abstract refreshColumnAsync(column): Promise +abstract refreshColumnAsync(column, options?): Promise ``` Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh job instead of blocking until it completes. LanceDB Embedded refresh requires a source build with -`experimental-functions`. LanceDB Distributed jobs do not require this +`experimental-functions`. LanceDB Enterprise jobs do not require this feature. The job may already be complete when returned; callers must not assume the column is filled until [Job.wait](Job.md#wait) resolves. Invalid input -- an unknown column, or one that is not computed -- rejects here rather than failing the job. In LanceDB Embedded the job runs in-process; in -LanceDB Distributed it is the server's backfill job. +LanceDB Enterprise it is the server's backfill job. #### Parameters * **column**: `string` The name of the computed column to fill. +* **options?**: [`RefreshColumnOptions`](../interfaces/RefreshColumnOptions.md) + Refresh options, mirroring the SQL + `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, + `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` + and `initTimeoutSeconds` govern failing rows, and `batchSize`, + `gpuClass`, `gpuCount`, `numWorkers` and `maxExecutorProcessesPerWorker` + size the workers. All are LanceDB Enterprise only; a LanceDB Embedded + refresh rejects every option other than `batchSize`, `gpuClass` and + `gpuCount`. + #### Returns `Promise`<[`Job`](Job.md)> @@ -1097,7 +1154,12 @@ LanceDB Distributed it is the server's backfill job. #### Example ```ts -const job = await table.refreshColumnAsync("doubled"); +const job = await table.refreshColumnAsync("embedding", { + where: "published_at > '2026-01-01'", + errorPolicy: "skip", + maxFailedFraction: 0.01, + rowTimeoutSeconds: 30, +}); await job.wait(); console.log(await job.status()); // "finished" ``` @@ -1312,7 +1374,7 @@ Tokenize a full-text search query using the tokenizer configured on an FTS index Specify exactly one of `column` or `indexName`. Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in -the client process from index metadata. In LanceDB Distributed, this means the +the client process from index metadata. In LanceDB Enterprise, this means the same tokenizer model files must also exist locally (under `LANCE_LANGUAGE_MODEL_HOME`) and must match the files the server uses. A mismatch cannot be detected: the returned tokens may differ from what the diff --git a/docs/src/js/classes/VectorQuery.md b/docs/src/js/classes/VectorQuery.md index d98f05893..2eef209bf 100644 --- a/docs/src/js/classes/VectorQuery.md +++ b/docs/src/js/classes/VectorQuery.md @@ -101,6 +101,38 @@ AnalyzeExec verbose=true, metrics=[] *** +### approxMode() + +```ts +approxMode(approxMode): VectorQuery +``` + +Set the speed / accuracy tradeoff to use for approximate search + +This currently affects RQ-quantized indexes, such as IVF_RQ, and +prefiltered search on HNSW indexes, where "fast" enables the ACORN +traversal. Other index types ignore this setting. + +"fast" favors lower latency and may reduce recall, "normal" (the default) +uses the index's default balance, and "accurate" favors higher recall and +may increase latency. + +#### Parameters + +* **approxMode**: `"fast"` \| `"normal"` \| `"accurate"` + +#### Returns + +[`VectorQuery`](VectorQuery.md) + +#### Example + +```ts +table.vectorSearch([0.1, 0.2]).approxMode("fast").limit(10); +``` + +*** + ### bypassVectorIndex() ```ts @@ -654,6 +686,11 @@ searchEffort(searchEffort): VectorQuery Set the initial IVF search effort to a finite value in [0, 1]. +Efforts 0.1 and 0.25 target empirical mean partition-routing recall of +80% and 90% for L2, cosine and dot through k=100000. The probe budget +adapts to the metric and k. Hamming and larger k remain uncalibrated; +100000 is not an API limit. Remote queries also require server support. + The default, null, uses Auto (internally 0.5). Zero starts at the caller minimum; one searches all partitions within the caller maximum. Later probing may continue when too few candidates are found. diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 25a32b29c..dab1c61bc 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -74,6 +74,7 @@ - [ClientConfig](interfaces/ClientConfig.md) - [ColumnAlteration](interfaces/ColumnAlteration.md) - [ColumnOrdering](interfaces/ColumnOrdering.md) +- [CompactionOptions](interfaces/CompactionOptions.md) - [CompactionStats](interfaces/CompactionStats.md) - [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md) - [ConnectionOptions](interfaces/ConnectionOptions.md) @@ -109,6 +110,7 @@ - [JobEventsOptions](interfaces/JobEventsOptions.md) - [JobFailureInfo](interfaces/JobFailureInfo.md) - [JobInfo](interfaces/JobInfo.md) +- [JobProgress](interfaces/JobProgress.md) - [ListingOptions](interfaces/ListingOptions.md) - [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md) - [MemtableStats](interfaces/MemtableStats.md) @@ -121,6 +123,7 @@ - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md) - [RTEStats](interfaces/RTEStats.md) - [RTEWriteSpec](interfaces/RTEWriteSpec.md) +- [RefreshColumnOptions](interfaces/RefreshColumnOptions.md) - [RefreshColumnResult](interfaces/RefreshColumnResult.md) - [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md) - [RemovalStats](interfaces/RemovalStats.md) @@ -170,6 +173,7 @@ - [FieldLike](type-aliases/FieldLike.md) - [IntoSql](type-aliases/IntoSql.md) - [IntoVector](type-aliases/IntoVector.md) +- [JobProgressCallback](type-aliases/JobProgressCallback.md) - [MaterializedViewSelect](type-aliases/MaterializedViewSelect.md) - [MultiVector](type-aliases/MultiVector.md) - [RecordBatchLike](type-aliases/RecordBatchLike.md) diff --git a/docs/src/js/interfaces/AddDataOptions.md b/docs/src/js/interfaces/AddDataOptions.md index 26c5ccef8..f1f57b98b 100644 --- a/docs/src/js/interfaces/AddDataOptions.md +++ b/docs/src/js/interfaces/AddDataOptions.md @@ -19,7 +19,7 @@ optional allowExternalBlobOutsideBases: boolean; Whether blob URIs outside registered external bases may be written. Defaults to `false`. This option is supported only in LanceDB Embedded; -LanceDB Distributed returns an error when it is enabled. An enabled write +LanceDB Enterprise returns an error when it is enabled. An enabled write stores the absolute URI reference without registering a base or copying the external object into the database. The object must remain accessible when the blob is read later. diff --git a/docs/src/js/interfaces/CompactionOptions.md b/docs/src/js/interfaces/CompactionOptions.md new file mode 100644 index 000000000..135266567 --- /dev/null +++ b/docs/src/js/interfaces/CompactionOptions.md @@ -0,0 +1,49 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / CompactionOptions + +# Interface: CompactionOptions + +Per-invocation compaction settings. Values must be safe integers. + +## Properties + +### batchSize? + +```ts +optional batchSize: number; +``` + +Positive scanner batch size in rows. + +*** + +### ioBufferSize? + +```ts +optional ioBufferSize: number; +``` + +Scanner I/O read-ahead budget in bytes; zero disables byte-based I/O backpressure. + +*** + +### maxSourceRows? + +```ts +optional maxSourceRows: number; +``` + +Positive live-source-row budget across whole tasks; an oversized first task can produce no work. + +*** + +### targetRowsPerFragment? + +```ts +optional targetRowsPerFragment: number; +``` + +Positive target rows per output fragment; also affects candidate selection. diff --git a/docs/src/js/interfaces/FunctionErrorRecord.md b/docs/src/js/interfaces/FunctionErrorRecord.md index 3a26534a0..16198e70e 100644 --- a/docs/src/js/interfaces/FunctionErrorRecord.md +++ b/docs/src/js/interfaces/FunctionErrorRecord.md @@ -90,3 +90,13 @@ detail was capped. ```ts tableVersion: number; ``` + +*** + +### traceback? + +```ts +optional traceback: string; +``` + +User-code traceback, possibly truncated by the server. diff --git a/docs/src/js/interfaces/IndexConfig.md b/docs/src/js/interfaces/IndexConfig.md index df3b81c52..6866cc7db 100644 --- a/docs/src/js/interfaces/IndexConfig.md +++ b/docs/src/js/interfaces/IndexConfig.md @@ -31,7 +31,7 @@ optional createdAt: Date; When the index was created. -`undefined` in LanceDB Distributed or indices created before timestamps were tracked. +`undefined` in LanceDB Enterprise or indices created before timestamps were tracked. *** @@ -44,7 +44,7 @@ optional indexDetails: any; Index-type-specific details parsed as a JavaScript object. Falls back to a raw string if JSON parsing fails. `undefined` in -LanceDB Distributed or when details are unavailable. +LanceDB Enterprise or when details are unavailable. *** @@ -66,7 +66,7 @@ optional indexUuid: string; The UUID of the first segment of the index. -`undefined` in LanceDB Distributed, which does not yet surface this. +`undefined` in LanceDB Enterprise, which does not yet surface this. *** @@ -78,7 +78,7 @@ optional indexVersion: number; The on-disk index format version. -`undefined` in LanceDB Distributed. +`undefined` in LanceDB Enterprise. *** @@ -100,7 +100,7 @@ optional numIndexedRows: number; The number of rows indexed, across all segments. -May be `undefined` in LanceDB Distributed if the server does not report it. +May be `undefined` in LanceDB Enterprise if the server does not report it. *** @@ -112,7 +112,7 @@ optional numSegments: number; The number of segments that make up the index. -`undefined` in LanceDB Distributed. +`undefined` in LanceDB Enterprise. *** @@ -124,7 +124,7 @@ optional numUnindexedRows: number; The number of rows not yet covered by this index. -May be `undefined` in LanceDB Distributed if the server does not report it. +May be `undefined` in LanceDB Enterprise if the server does not report it. *** @@ -136,7 +136,7 @@ optional sizeBytes: number; The total size in bytes of all index files across all segments. -`undefined` in LanceDB Distributed or indices without size tracking. +`undefined` in LanceDB Enterprise or indices without size tracking. *** @@ -148,4 +148,4 @@ optional typeUrl: string; The protobuf type URL, a precise type identifier for the index. -`undefined` in LanceDB Distributed. +`undefined` in LanceDB Enterprise. diff --git a/docs/src/js/interfaces/IndexOptions.md b/docs/src/js/interfaces/IndexOptions.md index eb1a10c8f..e0990fc8d 100644 --- a/docs/src/js/interfaces/IndexOptions.md +++ b/docs/src/js/interfaces/IndexOptions.md @@ -77,4 +77,7 @@ optional waitTimeoutSeconds: number; Timeout in seconds to wait for index creation to complete. -If not specified, the method will return immediately after starting the index creation. +Only applies to LanceDB Enterprise tables, which build the index in the +background. +If not specified, `createIndex` returns once the build is scheduled. +LanceDB Embedded tables always build the index before `createIndex` returns. diff --git a/docs/src/js/interfaces/JobFailureInfo.md b/docs/src/js/interfaces/JobFailureInfo.md index 5683ee5f0..fe9ce04e3 100644 --- a/docs/src/js/interfaces/JobFailureInfo.md +++ b/docs/src/js/interfaces/JobFailureInfo.md @@ -31,3 +31,13 @@ optional phase: string; ```ts optional retryable: boolean; ``` + +*** + +### traceback? + +```ts +optional traceback: string; +``` + +User-code traceback, possibly truncated by the server. diff --git a/docs/src/js/interfaces/JobInfo.md b/docs/src/js/interfaces/JobInfo.md index 01a7ceefc..5de1d5e55 100644 --- a/docs/src/js/interfaces/JobInfo.md +++ b/docs/src/js/interfaces/JobInfo.md @@ -39,6 +39,26 @@ jobType: string; *** +### paused + +```ts +paused: boolean; +``` + +Whether an operator has parked this job. + +*** + +### progress + +```ts +progress: Record; +``` + +Structured lifecycle, queue, pause, and job-type-specific progress. + +*** + ### state ```ts diff --git a/docs/src/js/interfaces/JobProgress.md b/docs/src/js/interfaces/JobProgress.md new file mode 100644 index 000000000..dde202794 --- /dev/null +++ b/docs/src/js/interfaces/JobProgress.md @@ -0,0 +1,117 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / JobProgress + +# Interface: JobProgress + +A forward-compatible structured progress snapshot for a server-side job. + +Fields are optional because older servers and different job types report +different counters. A missing counter is unknown; it is not zero. + +## Indexable + + \[`field`: `string`\]: `unknown` + +## Properties + +### estimated\_remaining\_time\_millis? + +```ts +optional estimated_remaining_time_millis: number; +``` + +Best-effort remaining milliseconds, present only for a reliable sample. + +*** + +### execution\_epoch? + +```ts +optional execution_epoch: null | number; +``` + +Execution identity and sample time used for client-side ETA derivation. + +*** + +### paused? + +```ts +optional paused: boolean; +``` + +Whether an operator has parked the job. + +*** + +### phase? + +```ts +optional phase: null | string; +``` + +Coarse server-derived phase, including phases from newer servers. + +*** + +### rows\_computed? + +```ts +optional rows_computed: null | number; +``` + +*** + +### rows\_failed? + +```ts +optional rows_failed: null | number; +``` + +*** + +### rows\_planned? + +```ts +optional rows_planned: null | number; +``` + +Planned, computed, skipped, remaining, and failed row counters, when the +server reports them. + +*** + +### rows\_remaining? + +```ts +optional rows_remaining: null | number; +``` + +*** + +### rows\_skipped? + +```ts +optional rows_skipped: null | number; +``` + +*** + +### sample\_at\_millis? + +```ts +optional sample_at_millis: null | number; +``` + +*** + +### state? + +```ts +optional state: string; +``` + +Lifecycle state, including states from newer servers. diff --git a/docs/src/js/interfaces/OptimizeOptions.md b/docs/src/js/interfaces/OptimizeOptions.md index 110eb3813..faf1d2724 100644 --- a/docs/src/js/interfaces/OptimizeOptions.md +++ b/docs/src/js/interfaces/OptimizeOptions.md @@ -33,6 +33,28 @@ tbl.optimize({cleanupOlderThan: new Date()}); *** +### compactionOptions? + +```ts +optional compactionOptions: CompactionOptions; +``` + +Compaction settings for this invocation. Omitted remote values inherit table +tuning, then deployment/built-in defaults. +Remote tables require a server supporting these SQL options; settings do +not change table policy. This is not a runtime or total-memory limit. + +#### Example + +```ts +await tbl.optimize({ compactionOptions: { + targetRowsPerFragment: 1000, maxSourceRows: 5000, + ioBufferSize: 64 * 1024 * 1024, batchSize: 128, +} }); +``` + +*** + ### deleteUnverified ```ts diff --git a/docs/src/js/interfaces/QueryExecutionOptions.md b/docs/src/js/interfaces/QueryExecutionOptions.md index f18ada7aa..fb9bada29 100644 --- a/docs/src/js/interfaces/QueryExecutionOptions.md +++ b/docs/src/js/interfaces/QueryExecutionOptions.md @@ -64,3 +64,6 @@ optional timeoutMs: number; ``` Timeout for query execution in milliseconds + +The timeout also covers reading the results, so consuming them slowly can +exceed it. diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md new file mode 100644 index 000000000..840012040 --- /dev/null +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -0,0 +1,124 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / RefreshColumnOptions + +# Interface: RefreshColumnOptions + +Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every +option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores +`batchSize`, `gpuClass` and `gpuCount` and rejects the rest. + +## Properties + +### batchSize? + +```ts +optional batchSize: number; +``` + +Maximum rows per Function call; must be greater than zero. + +*** + +### errorPolicy? + +```ts +optional errorPolicy: string; +``` + +`"fail"` (default) stops on a row error; `"skip"` writes null and +records the error, subject to the failure limits. + +*** + +### gpuClass? + +```ts +optional gpuClass: string; +``` + +GPU class for Function workers. + +*** + +### gpuCount? + +```ts +optional gpuCount: number; +``` + +Positive aggregate GPU budget for Function workers. + +*** + +### initTimeoutSeconds? + +```ts +optional initTimeoutSeconds: number; +``` + +Deadline for Function initialization, in seconds. + +*** + +### maxExecutorProcessesPerWorker? + +```ts +optional maxExecutorProcessesPerWorker: number; +``` + +Cap on executor processes per Function worker. + +*** + +### maxFailedFraction? + +```ts +optional maxFailedFraction: number; +``` + +Under a skip policy, fail the job once more than this share of rows +(0 to 1) has failed. + +*** + +### maxFailedRows? + +```ts +optional maxFailedRows: number; +``` + +Under a skip policy, fail the job once more than this many rows have +failed. + +*** + +### numWorkers? + +```ts +optional numWorkers: number; +``` + +Worker count for an expression column; Function columns reject it. + +*** + +### rowTimeoutSeconds? + +```ts +optional rowTimeoutSeconds: number; +``` + +Deadline for one Function call, in seconds. + +*** + +### where? + +```ts +optional where: string; +``` + +Only refresh the rows matching this SQL filter. diff --git a/docs/src/js/interfaces/RefreshMaterializedViewResult.md b/docs/src/js/interfaces/RefreshMaterializedViewResult.md index e1ec3eb65..87e519a18 100644 --- a/docs/src/js/interfaces/RefreshMaterializedViewResult.md +++ b/docs/src/js/interfaces/RefreshMaterializedViewResult.md @@ -14,7 +14,7 @@ optional mode: string; ``` -How the view was brought up to date: "rebuild", or absent for LanceDB Distributed SQL refreshes. +How the view was brought up to date: "rebuild", or absent for LanceDB Enterprise SQL refreshes. *** @@ -24,7 +24,7 @@ How the view was brought up to date: "rebuild", or absent for LanceDB Distribute optional rowsWritten: number; ``` -Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes. +Rows written by this refresh, or absent for LanceDB Enterprise SQL refreshes. *** @@ -34,7 +34,7 @@ Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes. optional sourceVersion: number; ``` -Source version refreshed to, or absent for LanceDB Distributed SQL refreshes. +Source version refreshed to, or absent for LanceDB Enterprise SQL refreshes. *** diff --git a/docs/src/js/type-aliases/BlobReadOptions.md b/docs/src/js/type-aliases/BlobReadOptions.md index 53184aa48..9d3ed04d6 100644 --- a/docs/src/js/type-aliases/BlobReadOptions.md +++ b/docs/src/js/type-aliases/BlobReadOptions.md @@ -21,4 +21,4 @@ optional signal: AbortSignal; ``` Cancels the read. The call rejects with `signal.reason`, and the native -read stops, including in-flight requests to a LanceDB Distributed table. +read stops, including in-flight requests to a LanceDB Enterprise table. diff --git a/docs/src/js/type-aliases/JobProgressCallback.md b/docs/src/js/type-aliases/JobProgressCallback.md new file mode 100644 index 000000000..41c4dc216 --- /dev/null +++ b/docs/src/js/type-aliases/JobProgressCallback.md @@ -0,0 +1,21 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / JobProgressCallback + +# Type Alias: JobProgressCallback() + +```ts +type JobProgressCallback: (progress) => void; +``` + +Callback for progress snapshots observed while waiting for a job. + +## Parameters + +* **progress**: [`JobProgress`](../interfaces/JobProgress.md) + +## Returns + +`void` diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b3c0c4672..7f28d8804 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -27,7 +27,7 @@ connect, per-table storage and write options on create, and `index_cache_size`, Omit these options to use server-managed storage and caching. Connection-level `storage_options` supported by an Enterprise deployment remain available. -The synchronous LanceDB Distributed `create_table` uses the same positional order as the +The synchronous LanceDB Enterprise `create_table` uses the same positional order as the LanceDB Embedded API: `name, data, schema, mode, exist_ok, on_bad_vectors, fill_value, embedding_functions`. Prefer keyword arguments for optional parameters. @@ -42,6 +42,12 @@ table names. `db.list_tables().tables` is a list of the first page; `limit` controls its page size and `page_token` resumes at a saved token. The same patterns apply to `list_namespaces()`. Other resource listings use `page_limit`. +Resource listings (`list_storage_integrations`, `list_secrets`, `list_views`, `list_jobs`, `list_functions`, and +`list_materialized_views`) return lazy iterators. Use `list(db.list_views())` to +collect synchronous results, or `[name async for name in db.list_views()]` with +an asynchronous connection. `page_limit` controls each request, and `page_token` +resumes a listing. Drain the iterator's cached results before saving its token. + ::: lancedb.listing.Listing ::: lancedb.listing.TableListing @@ -162,6 +168,11 @@ registered functions, for example, namespace. These objects identify resources for ACL operations; a secret object contains the credential's name, not its value. +Storage integration objects identify database-owned storage configuration, for +example `Object.storage_integration(database="default", name="raw")`. Pass +`namespace_path` for nested namespaces. Their keyspace is separate from Secrets, +Functions, and relations; the wire name is `storage_integration:default:public$raw`. + More object types may be added in the future. ### Access control lists @@ -205,6 +216,27 @@ for privilege in [Privilege.CREATE_SECRET, Privilege.CREATE_FUNCTION]: Both privileges also accept their string names in synchronous and asynchronous ACL methods. +Storage integration creation requires `CREATE_STORAGE_INTEGRATION` on its containing +namespace, together with database and namespace `USAGE`: + +```python +catalog.authz.add_acl( + object=Object.namespace(database="default"), + subject=Subject.role("developer"), + privilege=Privilege.CREATE_STORAGE_INTEGRATION, +) +catalog.authz.add_acl( + object=Object.storage_integration(database="default", name="raw"), + subject=Subject.role("reader"), + privilege=Privilege.USAGE, +) +``` + +Creation grants ownership to the creator. Describing an integration requires +`USAGE` on that integration; dropping it requires `OWNERSHIP`. Listing integrations +requires `USAGE` on the selected database and namespace. Describing and dropping +also require parent `USAGE` grants. Manage these grants through `catalog.authz`. + By default, the `list_acls` function lists all the access control entries in the system. By adding a function parameter, the output is filtered to just ACLs matching that parameter. For example, this code lists all the ACLs for the @@ -227,7 +259,7 @@ async for entry in catalog.authz.list_acls(subject=Subject.role("reader")): ## Remote SQL -Submit SQL against a LanceDB Distributed database through the connection. +Submit SQL against a LanceDB Enterprise database through the connection. The connected database and `default_namespace_path=["public"]` are used for unqualified tables. Fully qualified references can still query other databases and namespaces available to the same deployment. `execute_query` returns a @@ -308,24 +340,47 @@ listing a storage directory. ## Tables (Synchronous) -LanceDB Embedded and LanceDB Distributed tables use the same arguments for index creation, deletion, +LanceDB Embedded and LanceDB Enterprise tables use the same arguments for index creation, deletion, index statistics, and search. For example, `table.delete(where="id = 1")`, `table.create_index("cosine", 2)` (the deprecated vector API), and `table.search([1.0, 1.0], fast_search=True)` work with either backend. `fast_search=True` excludes rows that have not been indexed. `create_scalar_index` defaults to `replace=True` on both backends. Both scalar -and full-text index creation accept `wait_timeout`. LanceDB Distributed maintenance methods -accept the LanceDB Embedded options: cleanup and compaction warn that they are no-ops, -while `optimize` reports an unsupported operation. Removed Tantivy options -produce the same explanatory errors on both backends. +and full-text index creation accept `wait_timeout`. LanceDB Enterprise maintenance methods +accept the LanceDB Embedded options: cleanup and compaction warn that they are no-ops. +`optimize` submits a durable compaction job and returns once that submission is +accepted, not once compaction itself finishes. Pruning and index optimization +are not yet supported remotely, so it silently skips them and returns with +zeroed pruning statistics. Remote `compaction_options` support per-job +`target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and `batch_size` +on compatible servers. Other non-default settings raise `NotImplementedError` +before submission; older-server errors are returned without dropping options. +The source-row budget selects whole tasks and can produce no work if the first +task exceeds it. An I/O buffer size of zero disables byte-based I/O backpressure. +Use a positive size to limit I/O read-ahead; this is not a total-memory limit. +Each field resolves as invocation option → table tuning → deployment/built-in +default. These options apply only to the submitted job and leave table policy +unchanged. Table `enabled` controls automatic scheduling; explicit manual runs +remain allowed. -The old LanceDB Distributed keyword names `predicate` for `delete`, `index_name` for +```python +table.optimize(compaction_options={ + "target_rows_per_fragment": 100_000, + "max_source_rows": 1_000_000, + "io_buffer_size": 64 * 1024 * 1024, + "batch_size": 1024, +}) +``` + +Removed Tantivy options produce the same explanatory errors on both backends. + +The old LanceDB Enterprise keyword names `predicate` for `delete`, `index_name` for `drop_index`, `index_uuid` for `index_stats`, and `column` for `create_fts_index` remain available with deprecation warnings. Use `where`, `name`, `index_name`, and `field_names`, respectively. For positional calls, use the argument order documented by `Table` below; specify index options by keyword when migrating -code that used the former LanceDB Distributed-only argument order. +code that used the former LanceDB Enterprise-only argument order. ::: lancedb.table.Table @@ -345,11 +400,64 @@ code that used the former LanceDB Distributed-only argument order. ## Functions and Jobs +A `@function` definition is also a local callable. Call a decorated function +directly with row inputs, or call a decorated class with its initialization fields +and then call the returned instance; call `close()` if the class defines it. This +path uses the current Python environment and does not create a registered +`FunctionVersion`, build the declared remote runtime, resolve Secrets, or execute +the remote Arrow adapter. A registered `FunctionVersion` call instead binds +`col(...)` inputs and returns a remote `FunctionApplication`. + +```python +from lancedb import function + + +@function +def normalize(text: str) -> str: + return text.strip().lower() + + +@function +class Scale: + def __init__(self, factor: float): + self.factor = factor + + def __call__(self, value: float) -> float: + return value * self.factor + + def close(self) -> None: + self.factor = 0.0 + + +assert normalize(" Hello ") == "hello" +scaler = Scale(factor=2.0) +assert scaler(3.0) == 6.0 +scaler.close() +``` + Annotate a blob input with `lancedb.BlobReader` for lazy, seekable access, or with `bytes` to materialize its contents before the Function runs. Reader inputs infer the Blob V2 type without an explicit input schema. Readers are scoped to each invocation and support `read`, `readinto`, `seek`, `tell`, -`size`, and cursor-independent `read_range`. +`size`, and cursor-independent `read_range`. For a local test or another +engine, construct `BlobReader(read_range, size)` with a callback over an +in-memory bytes fixture or the engine's byte-range reader; `read_range` does +not advance the cursor. + +```python +from lancedb import BlobReader + +payload = b"0123456789" + + +def read_range(offset: int, length: int) -> bytes: + return payload[offset : offset + length] + + +with BlobReader(read_range, len(payload)) as reader: + assert reader.read_range(6, 4) == b"6789" + assert reader.tell() == 0 +``` ::: lancedb.BlobReader @@ -365,9 +473,9 @@ scoped to each invocation and support `read`, `readinto`, `seek`, `tell`, ::: lancedb.functions.PythonEnvironmentSpec -::: lancedb.functions.udf +::: lancedb.functions.function -::: lancedb.functions.UdfDefinition +::: lancedb.functions.FunctionDefinition ::: lancedb.secrets.EnvVarSecret @@ -375,6 +483,8 @@ scoped to each invocation and support `read`, `readinto`, `seek`, `tell`, ::: lancedb.functions.FunctionRegistrationRequest +::: lancedb.functions.FunctionRetryPolicy + ::: lancedb.functions.FunctionArtifactRequest ::: lancedb.functions.FunctionArtifactContent @@ -385,8 +495,12 @@ scoped to each invocation and support `read`, `readinto`, `seek`, `tell`, ::: lancedb.functions.FunctionVersion +::: lancedb.functions.HuggingFaceModel + ::: lancedb.functions.PythonRuntimeSpec +::: lancedb.GpuClass + ::: lancedb.functions.FunctionVersionRef ::: lancedb.functions.ApplicationInput @@ -432,11 +546,11 @@ scoped to each invocation and support `read`, `readinto`, `seek`, `tell`, In the 0.41 SDK release, LanceDB Embedded materialized-view creation and refresh require a source build with the `experimental-functions` Cargo feature. Published Python packages leave it disabled. Opening, reading, listing and dropping existing views -remain available, as do LanceDB Distributed operations. The same feature +remain available, as do LanceDB Enterprise operations. The same feature requirement applies to LanceDB Embedded SQL computed-column declaration and refresh; ordinary eager `add_columns` transforms remain available. -In LanceDB Distributed, creation accepts `auto_refresh_enabled` and +In LanceDB Enterprise, creation accepts `auto_refresh_enabled` and `auto_refresh_interval_seconds`: ```python @@ -461,6 +575,31 @@ automatic scheduling requests. ::: lancedb.view.ViewDescription +## Property Graphs + +A property graph is defined over tables of its namespace: which tables hold +nodes and which hold edges, each node table's key and label, and the node keys +each edge table's source and destination columns reference -- the shape of +SQL/PGQ's `CREATE PROPERTY GRAPH`. It stores no rows of its own; a query reads +its tables as nodes and edges through SQL `GRAPH_TABLE`. + +Create one with +[create_property_graph][lancedb.db.DBConnection.create_property_graph], and +manage it with +[open_property_graph][lancedb.db.DBConnection.open_property_graph], +[list_property_graphs][lancedb.db.DBConnection.list_property_graphs] and +[drop_property_graph][lancedb.db.DBConnection.drop_property_graph]. + +::: lancedb.graph.NodeTable + +::: lancedb.graph.EdgeTable + +::: lancedb.graph.Endpoint + +::: lancedb.graph.PropertyGraph + +::: lancedb.graph.PropertyGraphDescription + ## Expressions Type-safe expression builder for filters and projections. Use these instead @@ -617,7 +756,7 @@ 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. -LanceDB Distributed SQL returns blob bytes by default. Select `blob_descriptor(video)` to +LanceDB Enterprise SQL returns blob bytes by default. Select `blob_descriptor(video)` to return an openable reference instead, then use [`open_blob_file`][lancedb.table.Table.open_blob_file] or the lazy iterable [`open_blob_files`][lancedb.table.Table.open_blob_files]: @@ -634,7 +773,7 @@ for row in rows.to_pylist(): frame = extract_frame(video, row["timestamp"]) ``` -This example uses a LanceDB Distributed SQL connection that produces source-bearing +This example uses a LanceDB Enterprise SQL connection that produces source-bearing descriptors. The descriptor contains `kind`, `position`, `size`, `blob_id`, `blob_uri`, and a `source` struct with `uri`, `version`, `committed_at_micros`, `branch`, `column`, `row_reference`, and `row_is_address`. The opener verifies @@ -666,7 +805,7 @@ async for video in async_videos.open_blob_files(rows["video"]): ``` Payload bytes load on reads. Opening an external blob with unspecified size -can issue a metadata-only HEAD request. LanceDB Distributed reads use authenticated range +can issue a metadata-only HEAD request. LanceDB Enterprise reads use authenticated range requests that validate the captured URI and commit timestamp. Blobs inside lists can be written and queried as descriptors. They are omitted @@ -691,8 +830,111 @@ so the fetch APIs cannot read their bytes yet. ## Exceptions +Remote HTTP responses with structured resource details raise a subclass of +`HttpError`. Older servers that omit those details generally raise plain +`HttpError`, so `except HttpError` remains a compatible catch-all: + +```python +from lancedb.remote.errors import ( + AlreadyExistsError, + FunctionNotFoundError, + HttpError, + NamespaceNotFoundError, + SecretNotFoundError, +) + +try: + db.describe_namespace(["analytics"]) +except (SecretNotFoundError, FunctionNotFoundError, NamespaceNotFoundError) as error: + print(error.error_code, error.resource_kind, error.resource_name) +except AlreadyExistsError as error: + print("resource already exists:", error.resource_name) +except HttpError as error: + print("request failed:", error.request_id, error.status_code) +``` + +Remote branch deletion sends a single request. If the server rejects it with +HTTP 409, it raises `ConflictError` with the server's reason, including when an +older server omits structured resource details. A structured `already_exists` +response keeps its more specific `AlreadyExistsError` type. Both are subclasses +of `HttpError`. + +A remote query whose streamed response stops partway raises +`ResponseInterruptedError`, also a subclass of `HttpError`. It carries the number +of batches and rows already returned and, when the server reports it, the table +version the response reflected, so the query can be run again against that +version. It is never retried automatically, because the batches already returned +would be returned again. + +SQL response failures raise `SqlError`, retaining the numeric `grpc_code` and +`request_id`. Servers that report a recognized `x-lancedb-error-code` select a +specific input-error subclass. HTTP failures use the corresponding `HttpError` +subclass. Missing metadata stays absent; diagnostic text is never used to guess +the error type. An Internal or Unavailable response remains a server failure, +even if its message or metadata resembles an input error. + +For errors that can arrive over either transport, catch the shared input type: + +```python +from lancedb.exceptions import ColumnNotFoundError, SchemaMismatchError +from lancedb.remote.errors import HttpError, SqlError + +try: + db.execute_query("SELECT missing FROM events").read_all() +except (ColumnNotFoundError, SchemaMismatchError) as error: + print(error.request_id, error.job_id, error.job_request_id) +except (HttpError, SqlError) as error: + print(error.request_id) +``` + +`ReferenceNotFoundError` identifies a missing branch or table reference. Table +errors are `TableNotFoundError` for HTTP and `SqlTableNotFoundError` for SQL; +both remain compatible with `lance_namespace.errors.TableNotFoundError`. + +A background SQL job still raises `JobFailedError`. Its `__cause__` is the typed +`SqlError` when available, and both carry the current `request_id` and original +worker `job_request_id`. The outer job ID can differ from `sql_job_id`. These +fields are `None` when the server does not report them. Older servers produce +generic HTTP/SQL exceptions with their transport status and current request ID. + ::: lancedb.remote.errors.HttpError +::: lancedb.remote.errors.ColumnNotFoundError + +::: lancedb.remote.errors.ReferenceNotFoundError + +::: lancedb.remote.errors.SchemaMismatchError + +::: lancedb.remote.errors.SqlError + +::: lancedb.remote.errors.SqlColumnNotFoundError + +::: lancedb.remote.errors.SqlTableNotFoundError + +::: lancedb.remote.errors.SqlReferenceNotFoundError + +::: lancedb.remote.errors.SqlSchemaMismatchError + +::: lancedb.exceptions.ColumnNotFoundError + +::: lancedb.exceptions.ReferenceNotFoundError + +::: lancedb.exceptions.SchemaMismatchError + +::: lancedb.remote.errors.TableNotFoundError + +::: lancedb.remote.errors.SecretNotFoundError + +::: lancedb.remote.errors.FunctionNotFoundError + +::: lancedb.remote.errors.NamespaceNotFoundError + +::: lancedb.remote.errors.AlreadyExistsError + +::: lancedb.remote.errors.ConflictError + +::: lancedb.remote.errors.ResponseInterruptedError + ::: lancedb.exceptions.MissingValueError ::: lancedb.exceptions.MissingColumnError @@ -721,6 +963,27 @@ so the fetch APIs cannot read their bytes yet. ::: lancedb.streaming.StreamingDataset +When a transform fails for some rows, fill mode replaces each failed row in place: + +```python +dataset = StreamingDataset( + table, + num_splits=8, + transform=transform, + on_transform_error="fill", + fill_value={"id": -1, "vector": [0.0, 0.0]}, +) +for row in dataset: + train(row) +print(dataset.rows_filled) +``` + +The placeholder must have the same structure as a successful transform output. +Pass `repair(exc, row_batch) -> row` instead of `fill_value` to construct a +replacement from the failed one-row Arrow batch. Keep the repair deterministic +when using elastic training or checkpoints. Fill mode preserves split lengths +and sample positions. + ::: lancedb.streaming.StreamingDataLoader ::: lancedb.permutation.permutation_builder @@ -808,6 +1071,14 @@ Table hold your actual data as a collection of records / rows. ::: lancedb.materialized_view.AsyncMaterializedView +## Property Graphs (Asynchronous) + +`AsyncConnection` returns this handle from +[create_property_graph][lancedb.db.AsyncConnection.create_property_graph] and +[open_property_graph][lancedb.db.AsyncConnection.open_property_graph]. + +::: lancedb.graph.AsyncPropertyGraph + ## Indices (Asynchronous) Indices can be created on a table to speed up queries. This section @@ -851,3 +1122,196 @@ rows nearest to a query vector and can be created with the ::: lancedb.query.AsyncTakeQuery options: inherited_members: true + +## Storage integrations + +::: lancedb.storage_integration.StorageIntegrationInfo + +::: lancedb.storage_integration.SecretReference + +Integrations belong to a database and follow the same namespace-path naming rules +as Secrets, with their own keyspace. Use a regular database under the cluster root for storage configuration needed +before opening an external database. `default` is a convention; no database with +that name is required or created automatically. The system database is read-only. +Client methods execute SQL through the existing SQL transport. + +```python +catalog = lancedb.connect_catalog("https://my-server.example", api_key="secret") +db = catalog.connect_database("default") +integration = db.create_storage_integration( + "raw", "s3://customer-bucket/raw/", + aws_role_arn="arn:aws:iam::123456789012:role/lancedb-access", +) +print(integration.configuration_instructions) +integration = db.describe_storage_integration("raw") +for name in db.list_storage_integrations(): + print(name) +db.drop_storage_integration("raw") +``` + +Static credentials use two existing, single-value Secrets instead of a role: + +```python +from lancedb.storage_integration import SecretReference + +integration = db.create_storage_integration( + "raw", "s3://customer-bucket/raw/", + aws_access_key_id_secret=SecretReference("s3-key-id", database="default"), + aws_secret_access_key_secret=SecretReference("s3-secret-key", database="default"), +) +``` + +Pass `namespace_path` on the object APIs and Secret references to select a namespace. +A string Secret reference selects the root namespace of the integration's database. +Cross-database references require `USAGE` on the source database, namespace, and +Secret. Role and static-credential modes are mutually exclusive. Credential values +are never included in integration metadata. + +`configuration_instructions` is one sentence of display guidance whose wording may +change. Use the structured identity and policy fields for programmatic access. +Registration does not verify AWS access. `AsyncConnection` provides the same methods; +await create, describe, and drop, and use `async for` for listing. + + +### Azure storage integrations + +Create three Secrets containing the Azure tenant ID, client ID and client secret in an ordinary database. Reference their names when registering Azure Blob access: + +```python +integration = db.create_storage_integration( + "customer_blobs", + "az://customer-data/raw/", + storage_provider="AZURE", + azure_storage_account="customeraccount", + azure_tenant_id_secret="azure_tenant", + azure_client_id_secret="azure_client", + azure_client_secret_secret="azure_credential", +) +print(integration.configuration_instructions) +``` + +Use `SecretReference` to qualify another database or namespace. Sync and async connections use the same options. Secret values are never part of integration metadata. Azure supports service principal client credentials; managed identity, account key and SAS authentication are not integration modes. + +The equivalent SQL is: + +```sql +CREATE STORAGE INTEGRATION customer_blobs + STORAGE_PROVIDER = 'AZURE' + STORAGE_PREFIX = 'az://customer-data/raw/' + STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount' + STORAGE_AZURE_TENANT_ID_SECRET = public.azure_tenant + STORAGE_AZURE_CLIENT_ID_SECRET = public.azure_client + STORAGE_AZURE_CLIENT_SECRET_SECRET = public.azure_credential; +DESCRIBE STORAGE INTEGRATION customer_blobs; +SHOW STORAGE INTEGRATIONS; +DROP STORAGE INTEGRATION customer_blobs; +``` + +Registration returns setup instructions and leaves `access_verified` false. It stores an account-qualified prefix such as `az://customer-data@customeraccount.blob.core.windows.net/raw/`. + +### GCP storage integrations + +Create one Secret containing the complete GCP application credentials JSON file +content, then reference its name when registering Google Cloud Storage access: + +```python +from pathlib import Path + +db.create_secret("gcp_credentials", Path("credentials.json").read_text()) +integration = db.create_storage_integration( + "customer_gcs", + "gs://customer-data/raw/", + storage_provider="GCP", + gcp_credentials_json_secret="gcp_credentials", +) +print(integration.configuration_instructions) +``` + +The equivalent SQL references the existing Secret: + +```sql +CREATE STORAGE INTEGRATION customer_gcs + STORAGE_PROVIDER = 'GCP' + STORAGE_PREFIX = 'gs://customer-data/raw/' + GCP_CREDENTIALS_JSON_SECRET = public.gcp_credentials; +DESCRIBE STORAGE INTEGRATION customer_gcs; +SHOW STORAGE INTEGRATIONS; +DROP STORAGE INTEGRATION customer_gcs; +``` + +`gcp_credentials_json_secret` names a Secret; pass the file content to +`create_secret`, not to `create_storage_integration`. Use `SecretReference` to +qualify another database or namespace. Sync and async connections accept the same +options. The service interprets the stored JSON when accessing storage; registration +does not validate its credentials format or verify access, and leaves +`access_verified` false. Integration metadata contains the Secret reference, never +its JSON content. GCP options cannot be combined with AWS or Azure options. + + +### Hugging Face storage integrations + +Store a Hugging Face token as one Secret, then register the repository prefix +with the existing integration methods. Only the Secret name is part of the +integration configuration: + +```python +import os + +from lancedb.storage_integration import SecretReference + +db.create_secret("hf_token", os.environ["HF_TOKEN"]) +info = db.create_storage_integration( + "private_hub", + "hf://datasets/acme/private/raw/", + storage_provider="HUGGINGFACE", + huggingface_token_secret=SecretReference("hf_token"), +) +print(info.configuration_instructions) +info = db.describe_storage_integration("private_hub") +names = list(db.list_storage_integrations()) +db.drop_storage_integration("private_hub") +``` + +The equivalent SQL references the existing Secret: + +```sql +CREATE STORAGE INTEGRATION private_hub + STORAGE_PROVIDER = 'HUGGINGFACE' + STORAGE_PREFIX = 'hf://datasets/acme/private/raw/' + HUGGINGFACE_TOKEN_SECRET = public.hf_token; +DESCRIBE STORAGE INTEGRATION private_hub; +SHOW STORAGE INTEGRATIONS; +SELECT * FROM 'hf://datasets/acme/private/raw/*.parquet' LIMIT 10; +DROP STORAGE INTEGRATION private_hub; +``` + +Omit the token Secret for anonymous access at Hugging Face's default anonymous +rate limits. A tokenless integration does not use a cluster's Hugging Face token: + +```python +info = db.create_storage_integration( + "public_hub", "hf://datasets/acme/public/raw/", + storage_provider="HUGGINGFACE", +) +``` + +```sql +CREATE STORAGE INTEGRATION public_hub + STORAGE_PROVIDER = 'HUGGINGFACE' + STORAGE_PREFIX = 'hf://datasets/acme/public/raw/'; +``` + +When provided, the Secret must contain the token itself, with repository read +permission. +Cross-database and namespace references use the same `SecretReference` rules as +other integrations. Sync and async APIs accept the same options. Registration +returns one sentence of instructions and leaves `access_verified` false; it does +not contact Hugging Face. Metadata contains the Secret reference, never its value. +Hugging Face options cannot be combined with AWS, Azure or GCP options. + +Repository prefixes use `hf://datasets//[/]` or +`hf://models//[/]`. An optional `@revision` follows the repository +name; omitting it allows matching reads of any revision. Prefixes must be concrete +paths without wildcards or traversal. This integration does not make Hugging Face +a writable database location for `ATTACH DATABASE`. Dataset SQL sources select a +matching integration automatically, with no integration argument in the query. diff --git a/docs/web-tests/blob-v2/py/requirements.txt b/docs/web-tests/blob-v2/py/requirements.txt index c90c8d622..b0b1739a7 100644 --- a/docs/web-tests/blob-v2/py/requirements.txt +++ b/docs/web-tests/blob-v2/py/requirements.txt @@ -3,6 +3,6 @@ lancedb==0.41.0b10 numpy==2.2.6 pandas==2.3.3 -pillow==12.1.1 +pillow==13.0.0 pytest==8.4.2 pytest-asyncio==1.2.0 diff --git a/docs/web-tests/py/test_build_with_ai_agents.py b/docs/web-tests/py/test_build_with_ai_agents.py deleted file mode 100644 index 1ab7c9cdc..000000000 --- a/docs/web-tests/py/test_build_with_ai_agents.py +++ /dev/null @@ -1,109 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright The LanceDB Authors - -# --8<-- [start:camelot_schema] -from lancedb.pydantic import LanceModel -from pydantic import ConfigDict - - -class Stats(LanceModel): - model_config = ConfigDict(strict=True, extra="forbid") - - strength: int - courage: int - magic: int - wisdom: int - - -class Character(LanceModel): - model_config = ConfigDict(strict=True, extra="forbid") - - id: int - name: str - role: str - description: str - stats: Stats - image_filename: str - image: bytes -# --8<-- [end:camelot_schema] - - -# --8<-- [start:camelot_batches] -import json -from collections.abc import Iterator -from pathlib import Path - - -def validated_batches( - input_path: Path, batch_size: int -) -> Iterator[list[dict]]: - raw_records = json.loads(input_path.read_text()) - asset_root = input_path.parent.parent - batch: list[dict] = [] - - for raw in raw_records: - payload = dict(raw) - image_path = asset_root / payload.pop("img") - payload["image_filename"] = image_path.name - payload["image"] = image_path.read_bytes() - - character = Character.model_validate(payload) - batch.append(character.model_dump(mode="python")) - - if len(batch) == batch_size: - yield batch - batch = [] - - if batch: - yield batch -# --8<-- [end:camelot_batches] - - -# --8<-- [start:camelot_oss_ingestion] -import lancedb - - -def ingest_oss( - input_path: Path, - uri: str = "data/camelot.lancedb", - table_name: str = "camelot_multimodal", - batch_size: int = 64, -): - db = lancedb.connect(uri) - if table_name in db.list_tables(): - raise ValueError( - f"Table {table_name!r} already exists. Choose a fresh table name." - ) - - table = db.create_table(table_name, schema=Character) - for batch in validated_batches(input_path, batch_size): - table.add(batch) - - table.optimize() - return table - - -if __name__ == "__main__": - ingest_oss(Path("data/camelot.json")) -# --8<-- [end:camelot_oss_ingestion] - - -def test_camelot_oss_ingestion(tmp_path): - source = Path( - "docs/web/static/assets/tutorials/build-with-ai-agents/camelot/data/camelot.json" - ) - table = ingest_oss( - source, - uri=str(tmp_path / "camelot.lancedb"), - table_name="camelot", - ) - - rows = ( - table.search() - .select(["id", "name", "image", "image_filename"]) - .limit(8) - .to_list() - ) - assert len(rows) == 8 - assert all(row["image"] for row in rows) - assert all(row["image_filename"].endswith(".jpg") for row in rows) diff --git a/docs/web-tests/py/test_connection.py b/docs/web-tests/py/test_connection.py index f5c1f2b22..b7a6256ca 100644 --- a/docs/web-tests/py/test_connection.py +++ b/docs/web-tests/py/test_connection.py @@ -41,6 +41,7 @@ def connect_enterprise_quickstart_config(): api_key=os.environ["LANCEDB_API_KEY"], region=os.environ.get("LANCEDB_REGION", "us-east-1"), host_override=os.environ["LANCEDB_HOST_OVERRIDE"], # https://your-endpoint + sql_host_override=os.environ["LANCEDB_SQL_HOST_OVERRIDE"], ) # --8<-- [end:connect_enterprise_quickstart] return db @@ -60,6 +61,9 @@ def test_connect_enterprise_quickstart(monkeypatch): monkeypatch.setenv("LANCEDB_API_KEY", "your-api-key") monkeypatch.delenv("LANCEDB_REGION", raising=False) monkeypatch.setenv("LANCEDB_HOST_OVERRIDE", "https://your-endpoint") + monkeypatch.setenv( + "LANCEDB_SQL_HOST_OVERRIDE", "grpc+tls://your-sql-endpoint:10026" + ) assert connect_enterprise_quickstart_config() is not None assert captured == { @@ -67,6 +71,7 @@ def test_connect_enterprise_quickstart(monkeypatch): "api_key": "your-api-key", "region": "us-east-1", "host_override": "https://your-endpoint", + "sql_host_override": "grpc+tls://your-sql-endpoint:10026", } @@ -79,6 +84,16 @@ def test_connect_enterprise_quickstart_requires_an_endpoint(monkeypatch): connect_enterprise_quickstart_config() +def test_connect_enterprise_quickstart_requires_a_sql_endpoint(monkeypatch): + monkeypatch.setenv("LANCEDB_URI", "db://your-database") + monkeypatch.setenv("LANCEDB_API_KEY", "your-api-key") + monkeypatch.setenv("LANCEDB_HOST_OVERRIDE", "https://your-endpoint") + monkeypatch.delenv("LANCEDB_SQL_HOST_OVERRIDE", raising=False) + + with pytest.raises(KeyError, match="LANCEDB_SQL_HOST_OVERRIDE"): + connect_enterprise_quickstart_config() + + def connect_object_storage_config(): # --8<-- [start:connect_object_storage] import lancedb @@ -169,6 +184,7 @@ def test_namespace_admin_ops(tmp_path, monkeypatch, capsys): ) assert db.list_namespaces().namespaces == [] + async def connect_object_storage_config_async(): # --8<-- [start:connect_object_storage_async] import lancedb @@ -199,6 +215,7 @@ def test_connect_enterprise_placeholders(monkeypatch): api_key="your-api-key", region="us-east-1", host_override="https://your-endpoint", + sql_host_override="grpc+tls://your-sql-endpoint:10026", ) # --8<-- [end:connect_enterprise_placeholders] assert db is not None @@ -207,4 +224,5 @@ def test_connect_enterprise_placeholders(monkeypatch): "api_key": "your-api-key", "region": "us-east-1", "host_override": "https://your-endpoint", + "sql_host_override": "grpc+tls://your-sql-endpoint:10026", } diff --git a/docs/web-tests/py/test_curation_sampling.py b/docs/web-tests/py/test_curation_sampling.py index d50b8a43f..dd1053fd1 100644 --- a/docs/web-tests/py/test_curation_sampling.py +++ b/docs/web-tests/py/test_curation_sampling.py @@ -3,7 +3,6 @@ def test_sample_dataset(): - # --8<-- [start:sample_dataset] from tempfile import TemporaryDirectory import lancedb @@ -11,6 +10,7 @@ def test_sample_dataset(): with TemporaryDirectory(prefix="lancedb-sampling-") as uri: db = lancedb.connect(uri) + # --8<-- [start:sample_dataset] table = db.create_table("records", [{"id": i} for i in range(10)]) splits = ( permutation_builder(table).split_random(counts=[3, 7], seed=42).execute() diff --git a/docs/web-tests/py/test_embedding.py b/docs/web-tests/py/test_embedding.py index 490be268e..eed12ba81 100644 --- a/docs/web-tests/py/test_embedding.py +++ b/docs/web-tests/py/test_embedding.py @@ -25,6 +25,8 @@ def test_create_embedding_function(): @pytest.mark.skip(reason="OpenAI is not available in the test environment") def test_embeddings_openai(): # --8<-- [start:openai_embeddings] + import lancedb + db = lancedb.connect("/tmp/db") func = get_registry().get("openai").create(name="text-embedding-ada-002") @@ -46,6 +48,8 @@ def test_embeddings_openai(): async def test_embeddings_openai_async(): uri = "memory://" # --8<-- [start:async_openai_embeddings] + import lancedb + db = await lancedb.connect_async(uri) func = get_registry().get("openai").create(name="text-embedding-ada-002") @@ -65,6 +69,8 @@ async def test_embeddings_openai_async(): @pytest.mark.skip(reason="OpenAI is not available in the test environment") def test_embeddings_manual_query(): # --8<-- [start:manual_query_embeddings] + import lancedb + db = lancedb.connect("/tmp/db") func = get_registry().get("openai").create(name="text-embedding-ada-002") diff --git a/docs/web-tests/py/test_function.py b/docs/web-tests/py/test_function.py index a89424316..147520b18 100644 --- a/docs/web-tests/py/test_function.py +++ b/docs/web-tests/py/test_function.py @@ -6,14 +6,15 @@ Registering a Function and filling its column need a LanceDB Enterprise deployment, so `test_function_enterprise` runs only when LANCEDB_DOCS_TEST_DEPLOYMENT=1 asks for one, with the connection variables the -Enterprise examples already use: LANCEDB_URI, LANCEDB_API_KEY and -LANCEDB_HOST_OVERRIDE, plus LANCEDB_REGION if the deployment needs one. The +Enterprise examples already use: LANCEDB_URI, LANCEDB_API_KEY, +LANCEDB_HOST_OVERRIDE and LANCEDB_SQL_HOST_OVERRIDE, plus LANCEDB_REGION if the +deployment needs one. The walkthrough calls its table `function_demo` and its Function `double`; the test creates both under names unique to its run, never replaces an existing object, and drops only what it created. The other tests run locally and check the client side of the same code: what -`@udf` sends for registration, how a registered version binds a column, where a +`@function` sends for registration, how a registered version binds a column, where a local connection stops, and when the Enterprise test connects. They do not run a Function remotely. """ @@ -31,18 +32,18 @@ from lancedb import col from lancedb.functions import FunctionApplication, FunctionVersion # --8<-- [start:function_define] -from lancedb import udf +from lancedb import function -@udf +@function def double(value: float) -> float: return value * 2 # --8<-- [end:function_define] -# The definition the walkthrough registers. The Enterprise test registers a copy -# of it under a name that only its run uses. +# The definitions the walkthrough registers. The Enterprise test registers a +# copy of each under a name that only its run uses. WALKTHROUGH_DOUBLE = double @@ -51,7 +52,7 @@ def describe(value: float): # --8<-- [start:function_class_define] -@udf(pip=["sentence-transformers"]) +@function(pip=["sentence-transformers"]) class embed: def __init__(self, model: str = "all-MiniLM-L6-v2"): # Runs on the worker, once per instance: only the worker needs the package. @@ -68,6 +69,8 @@ class embed: # --8<-- [end:function_class_define] +WALKTHROUGH_EMBED = embed + # A Function version as the service returns it after registration: the SDK's # shared golden reply, with the name and signature of the definition above. @@ -91,7 +94,12 @@ def registered_version(definition) -> FunctionVersion: return FunctionVersion.from_json(json.dumps(reply)) -DEPLOYMENT = ("LANCEDB_URI", "LANCEDB_HOST_OVERRIDE", "LANCEDB_API_KEY") +DEPLOYMENT = ( + "LANCEDB_URI", + "LANCEDB_HOST_OVERRIDE", + "LANCEDB_SQL_HOST_OVERRIDE", + "LANCEDB_API_KEY", +) # The connection settings alone never send this test to a deployment. OPT_IN = "LANCEDB_DOCS_TEST_DEPLOYMENT" @@ -138,7 +146,7 @@ def test_function_output_nullability(): pa.field("half", pa.float64(), nullable=False), pa.field("note", pa.string(), nullable=True), ] - struct = udf(input_schema=inputs, output_schema=pa.schema(fields))(describe) + struct = function(input_schema=inputs, output_schema=pa.schema(fields))(describe) output = struct.registration_request.signature.output assert output.kind == "named_struct" assert [(field.name, field.nullable) for field in output.fields] == [ @@ -152,7 +160,7 @@ def test_function_output_nullability(): pa.field("result", pa.struct(fields), nullable=True), ): with pytest.raises(ValueError, match="non-nullable"): - udf(input_schema=inputs, output_schema=nullable)(describe) + function(input_schema=inputs, output_schema=nullable)(describe) def test_function_registration_is_remote(tmp_path): @@ -181,7 +189,10 @@ def test_function_version_binds_a_column(tmp_path): # The binding is accepted by add_columns, which a local table refuses: # a Function column needs LanceDB Cloud or Enterprise. table = lancedb.connect(tmp_path).create_table("t", [{"value": 1.0}]) - with pytest.raises(NotImplementedError, match="Cloud and Enterprise"): + with pytest.raises( + NotImplementedError, + match="Function columns are supported only in LanceDB Enterprise", + ): table.add_columns({"doubled": application}) @@ -223,6 +234,7 @@ def test_function_enterprise(monkeypatch): api_key=os.environ["LANCEDB_API_KEY"], region=os.environ.get("LANCEDB_REGION", "us-east-1"), host_override=os.environ["LANCEDB_HOST_OVERRIDE"], + sql_host_override=os.environ["LANCEDB_SQL_HOST_OVERRIDE"], ) # --8<-- [end:function_connect] @@ -230,7 +242,10 @@ def test_function_enterprise(monkeypatch): # this run creates both under names only it uses, and drops only those. run = uuid.uuid4().hex[:12] table_name = f"function_demo_{run}" - double = udf(name=f"double_{run}")(WALKTHROUGH_DOUBLE.__wrapped__) + double = function(name=f"double_{run}")(WALKTHROUGH_DOUBLE.__wrapped__) + embed = function(name=f"embed_{run}", pip=["sentence-transformers"])( + WALKTHROUGH_EMBED.__wrapped__ + ) create_table = db.create_table def create_run_table(name, *args, **kwargs): @@ -241,6 +256,7 @@ def test_function_enterprise(monkeypatch): table = None version = None + embedder = None try: # --8<-- [start:function_create_table] import pyarrow as pa @@ -284,11 +300,18 @@ def test_function_enterprise(monkeypatch): (2.0, 4.0), (3.0, 6.0), ] + + # --8<-- [start:function_class_register] + embedder = db.create_function_async(embed).wait() + # --8<-- [end:function_class_register] + assert embedder.name == f"embed_{run}" finally: if table is not None: db.drop_table(table_name) if version is not None: db.drop_function(version.name, version=version.version) + if embedder is not None: + db.drop_function(embedder.name, version=embedder.version) class ReachedConnection(Exception): @@ -298,6 +321,7 @@ class ReachedConnection(Exception): SETTINGS = { "LANCEDB_URI": "db://docs-test", "LANCEDB_HOST_OVERRIDE": "https://deployment.invalid", + "LANCEDB_SQL_HOST_OVERRIDE": "grpc+tls://sql.deployment.invalid:10026", "LANCEDB_API_KEY": "docs-test-key", } @@ -375,5 +399,6 @@ def test_function_enterprise_connects_when_asked(monkeypatch, connect_attempts, "api_key": "docs-test-key", "region": region or "us-east-1", "host_override": "https://deployment.invalid", + "sql_host_override": "grpc+tls://sql.deployment.invalid:10026", } ] diff --git a/docs/web-tests/py/test_indexing.py b/docs/web-tests/py/test_indexing.py index 80010343c..f342f1b3b 100644 --- a/docs/web-tests/py/test_indexing.py +++ b/docs/web-tests/py/test_indexing.py @@ -177,30 +177,69 @@ def test_vector_index_query_ivf(tmp_db): def test_vector_index_nprobes(tmp_db): - dim = 128 + from lancedb.index import IvfFlat + + dim = 16 + rng = np.random.default_rng(180) data = [ - {"id": i, "keywords_embeddings": np.random.random(dim).tolist()} + {"id": i, "vector": rng.random(dim).astype(np.float32).tolist()} for i in range(512) ] table = tmp_db.create_table("vector_index_nprobes", data, mode="overwrite") table.create_index( - metric="cosine", - vector_column_name="keywords_embeddings", + "vector", + config=IvfFlat(distance_type="cosine", num_partitions=64, max_iterations=2), ) + query_vector = data[123]["vector"] + + # --8<-- [start:vector_index_auto] + # Start with Auto. + auto = table.search(query_vector).limit(10).to_arrow() + # --8<-- [end:vector_index_auto] + + # --8<-- [start:vector_index_search_effort] + # Search more partitions to try to improve recall. + higher_effort = table.search(query_vector).search_effort(0.75).limit(10).to_arrow() + # --8<-- [end:vector_index_search_effort] + + # --8<-- [start:vector_index_fixed_probes] + # Use a fixed probe count. + fixed = table.search(query_vector).nprobes(20).limit(10).to_arrow() + # --8<-- [end:vector_index_fixed_probes] # --8<-- [start:vector_index_nprobes] - # Always scan 10 partitions; scan up to 50 only if the initial pass - # returns fewer than `limit` results (common with narrow filters). - ( - table.search(np.random.random(128)) + # Let Auto choose between 10 and 50 partitions per segment, if available. + filtered = ( + table.search(query_vector) .minimum_nprobes(10) .maximum_nprobes(50) .where("id > 100") .limit(5) - .to_pandas() + .to_arrow() ) # --8<-- [end:vector_index_nprobes] + for result, expected_count in [ + (auto, 10), + (higher_effort, 10), + (fixed, 10), + (filtered, 5), + ]: + assert result.num_rows == expected_count + assert result["id"][0].as_py() == 123 + assert np.isfinite(result["_distance"].to_numpy()).all() + exact_query = ( + table.search(query_vector).distance_type("cosine").bypass_vector_index() + ) + if result is filtered: + exact_query = exact_query.where("id > 100") + expected_ids = set( + exact_query.limit(expected_count).to_arrow()["id"].to_pylist() + ) + recall = len(set(result["id"].to_pylist()) & expected_ids) / expected_count + assert recall >= 0.5 + assert all(row_id > 100 for row_id in filtered["id"].to_pylist()) + def test_vector_index_distance_range(tmp_db): dim = 128 @@ -295,6 +334,7 @@ def test_vector_index_hnsw(tmp_db): def test_vector_index_binary(tmp_db): + db = tmp_db table_name = "hamming-index-tbl" ndim = 256 schema = pa.schema( @@ -305,7 +345,7 @@ def test_vector_index_binary(tmp_db): ) # --8<-- [start:vector_index_binary_schema] - table = tmp_db.create_table(table_name, schema=schema, mode="overwrite") + table = db.create_table(table_name, schema=schema, mode="overwrite") # --8<-- [end:vector_index_binary_schema] data = [] diff --git a/docs/web-tests/py/test_ingestion_examples.py b/docs/web-tests/py/test_ingestion_examples.py index 0dedc1458..bca28afd4 100644 --- a/docs/web-tests/py/test_ingestion_examples.py +++ b/docs/web-tests/py/test_ingestion_examples.py @@ -3,13 +3,13 @@ def test_create_table_from_dicts(): - # --8<-- [start:create_table_from_dicts] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_table_from_dicts] data = [ {"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}, {"vector": [0.2, 1.8], "lat": 40.1, "long": -74.1}, @@ -24,13 +24,13 @@ def test_create_table_from_dicts(): def test_create_table_conflict_handling(): - # --8<-- [start:create_table_conflict_handling] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_table_conflict_handling] data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}] db.create_table("conflict_table", data) # Idempotent open: reuse the existing table if it exists. @@ -45,13 +45,13 @@ def test_create_table_conflict_handling(): def test_create_table_custom_schema(): - # --8<-- [start:create_table_custom_schema] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_table_custom_schema] import pyarrow as pa custom_schema = pa.schema( @@ -76,13 +76,13 @@ def test_create_table_custom_schema(): def test_create_table_from_pandas(): - # --8<-- [start:create_table_from_pandas] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_table_from_pandas] import pandas as pd data = pd.DataFrame( @@ -98,13 +98,13 @@ def test_create_table_from_pandas(): def test_create_table_from_polars(): - # --8<-- [start:create_table_from_polars] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_table_from_polars] import polars as pl data = pl.DataFrame( @@ -122,13 +122,13 @@ def test_create_table_from_polars(): def test_create_table_from_arrow(): - # --8<-- [start:create_table_from_arrow] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_table_from_arrow] import numpy as np import pyarrow as pa @@ -158,13 +158,13 @@ def test_create_table_from_arrow(): def test_create_table_from_pydantic(): - # --8<-- [start:create_table_from_pydantic] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_table_from_pydantic] from lancedb.pydantic import LanceModel, Vector class Content(LanceModel): @@ -186,13 +186,13 @@ def test_create_table_from_pydantic(): def test_create_table_nested_schema(): - # --8<-- [start:create_table_nested_schema] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_table_nested_schema] from lancedb.pydantic import LanceModel, Vector from pydantic import BaseModel @@ -213,13 +213,13 @@ def test_create_table_nested_schema(): def test_create_empty_table(): - # --8<-- [start:create_empty_table] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_empty_table] import pyarrow as pa schema = pa.schema( @@ -237,13 +237,13 @@ def test_create_empty_table(): def test_create_empty_table_pydantic(): - # --8<-- [start:create_empty_table_pydantic] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_empty_table_pydantic] from lancedb.pydantic import LanceModel, Vector class Item(LanceModel): @@ -261,13 +261,13 @@ def test_create_empty_table_pydantic(): def test_open_existing_table(): - # --8<-- [start:open_existing_table] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:open_existing_table] # Create a table first data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}] db.create_table("test_table", data, mode="overwrite") @@ -284,13 +284,13 @@ def test_open_existing_table(): def test_drop_table(): - # --8<-- [start:drop_table] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:drop_table] # Create a table first data = [{"vector": [1.1, 1.2], "lat": 45.5}] db.create_table("my_table", data, mode="overwrite") @@ -300,40 +300,35 @@ def test_drop_table(): # --8<-- [end:drop_table] -def test_add_from_dataset(): +def test_add_from_dataset(tmp_db, tmp_path, monkeypatch): + db = tmp_db + monkeypatch.chdir(tmp_path) + # --8<-- [start:add_from_dataset] - from tempfile import TemporaryDirectory + import pyarrow as pa + import pyarrow.parquet as pq - import lancedb + data_path = "input.parquet" + pq.write_table(pa.table({"id": [1, 2], "name": ["Alice", "Bob"]}), data_path) + import pyarrow.dataset as ds - with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: - db = lancedb.connect(uri) - from pathlib import Path + dataset = ds.dataset(data_path, format="parquet") + table = db.create_table("my_table", schema=dataset.schema, mode="overwrite") + table.add(dataset) - import pyarrow as pa - import pyarrow.parquet as pq - - data_path = str(Path(uri) / "input.parquet") - pq.write_table(pa.table({"id": [1, 2], "name": ["Alice", "Bob"]}), data_path) - import pyarrow.dataset as ds - - dataset = ds.dataset(data_path, format="parquet") - table = db.create_table("my_table", schema=dataset.schema, mode="overwrite") - table.add(dataset) - - print("Rows:", table.count_rows()) - # --8<-- [end:add_from_dataset] - assert table.count_rows() == 2 + print("Rows:", table.count_rows()) + # --8<-- [end:add_from_dataset] + assert table.count_rows() == 2 def test_create_table_from_iterator(): - # --8<-- [start:create_table_from_iterator] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:create_table_from_iterator] import pyarrow as pa schema = pa.schema( @@ -367,13 +362,13 @@ def test_create_table_from_iterator(): def test_update_operation(): - # --8<-- [start:update_operation] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:update_operation] import pyarrow as pa table = db.create_table( @@ -396,13 +391,13 @@ def test_update_operation(): def test_update_using_sql(): - # --8<-- [start:update_using_sql] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:update_using_sql] import pyarrow as pa table = db.create_table( @@ -425,13 +420,13 @@ def test_update_using_sql(): def test_merge_matched_update_only(): - # --8<-- [start:merge_matched_update_only] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:merge_matched_update_only] import pyarrow as pa table = db.create_table( @@ -462,13 +457,13 @@ def test_merge_matched_update_only(): def test_insert_if_not_exists(): - # --8<-- [start:insert_if_not_exists] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:insert_if_not_exists] import pyarrow as pa table = db.create_table( @@ -499,13 +494,13 @@ def test_insert_if_not_exists(): def test_merge_update_insert(): - # --8<-- [start:merge_update_insert] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:merge_update_insert] import pyarrow as pa table = db.create_table( @@ -542,13 +537,13 @@ def test_merge_update_insert(): def test_merge_delete_missing_by_source(): - # --8<-- [start:merge_delete_missing_by_source] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:merge_delete_missing_by_source] import pyarrow as pa table = db.create_table( @@ -586,13 +581,13 @@ def test_merge_delete_missing_by_source(): def test_merge_partial_columns(): - # --8<-- [start:merge_partial_columns] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:merge_partial_columns] import pyarrow as pa table = db.create_table( @@ -670,13 +665,13 @@ def test_write_workflow(): def test_append_rows(): - # --8<-- [start:append_rows] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:append_rows] table = db.create_table("users", [{"id": 1, "name": "Alice"}]) table.add([{"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}]) rows = sorted(table.search().to_list(), key=lambda row: row["id"]) @@ -687,13 +682,13 @@ def test_append_rows(): def test_delete_rows(): - # --8<-- [start:delete_rows] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:delete_rows] table = db.create_table( "users", [ @@ -713,7 +708,6 @@ def test_delete_rows(): def test_add_progress(): - # --8<-- [start:add_progress] from tempfile import TemporaryDirectory import lancedb @@ -723,6 +717,7 @@ def test_add_progress(): with TemporaryDirectory(prefix="lancedb-ingestion-") as uri: db = lancedb.connect(uri) + # --8<-- [start:add_progress] table = db.create_table("users", [{"id": 1, "name": "Alice"}]) table.add( [{"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}], diff --git a/docs/web-tests/py/test_integrations.py b/docs/web-tests/py/test_integrations.py index 84c4560ae..447b3b601 100644 --- a/docs/web-tests/py/test_integrations.py +++ b/docs/web-tests/py/test_integrations.py @@ -167,46 +167,31 @@ def test_embedding_huggingface_usage() -> None: def test_frameworks_lerobot_lancedb_usage() -> None: require_flag("RUN_LEROBOT_LANCEDB_SNIPPETS") - # --8<-- [start:frameworks_lerobot_lancedb_image_dataset] - from lerobot_lancedb import LeRobotLanceDataset - - dataset = LeRobotLanceDataset( - repo_id="your-org/your-lerobot-lance-images", - delta_timestamps={ - "observation.images.front": [-0.2, -0.1, 0.0], - }, - return_uint8=True, - ) + # --8<-- [start:frameworks_lerobot_lancedb_dataset] + from lerobot_lancedb import LanceDBDataset, lance_mp_context + from torch.utils.data import DataLoader + dataset = LanceDBDataset(root="hf://datasets/lance-format/pusht-lance") sample = dataset[0] print(sample["observation.state"].shape) print(sample["action"].shape) - # --8<-- [end:frameworks_lerobot_lancedb_image_dataset] - # --8<-- [start:frameworks_lerobot_lancedb_video_dataset] - from lerobot_lancedb import LeRobotLanceVideoDataset - - video_dataset = LeRobotLanceVideoDataset( - repo_id="lance-format/lerobot-pusht-lance", - delta_timestamps={ - "observation.images.image": [-0.2, -0.1, 0.0], - }, - return_uint8=True, + loader = DataLoader( + dataset, + batch_size=32, + num_workers=8, + multiprocessing_context=lance_mp_context(), ) - - video_sample = video_dataset[0] - print(video_sample["observation.images.image"].shape) - # --8<-- [end:frameworks_lerobot_lancedb_video_dataset] + # --8<-- [end:frameworks_lerobot_lancedb_dataset] # --8<-- [start:frameworks_lerobot_open_lance_tables] import lancedb - db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data") + db = lancedb.connect("hf://datasets/lance-format/pusht-lance") frames = db.open_table("frames") - episodes = db.open_table("episodes") videos = db.open_table("videos") - print(len(frames), len(episodes), len(videos)) + print(len(frames), len(videos)) print(frames.schema) # --8<-- [end:frameworks_lerobot_open_lance_tables] @@ -723,7 +708,9 @@ def test_embedding_voyageai_multimodal() -> None: # Add images using URLs tbl.add( [ - {"image_uri": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/300px-PNG_transparency_demonstration_1.png"}, + { + "image_uri": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/300px-PNG_transparency_demonstration_1.png" + }, ] ) @@ -1359,6 +1346,8 @@ def test_frameworks_pydantic_examples() -> None: # --8<-- [end:frameworks_pydantic_base_model] # --8<-- [start:frameworks_pydantic_set_url] + import lancedb + db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "pydantic-docs")) # --8<-- [end:frameworks_pydantic_set_url] @@ -1691,6 +1680,8 @@ def test_platforms_pandas_examples() -> None: # --8<-- [end:platforms_pandas_imports] # --8<-- [start:platforms_pandas_create_table] + import lancedb + pandas_df = pd.DataFrame( [ {"id": "1", "text": "dragon", "vector": [0.9, 0.1, 0.3]}, @@ -1713,6 +1704,8 @@ def test_platforms_pandas_examples() -> None: # --8<-- [end:platforms_pandas_vector_search] # --8<-- [start:platforms_pandas_async_example] + import lancedb + async def run_pandas_async_example() -> pd.DataFrame: async_db = await lancedb.connect_async( str(Path(tempfile.mkdtemp()) / "pandas-async") @@ -1752,6 +1745,8 @@ def test_platforms_polars_examples() -> None: # --8<-- [end:platforms_polars_imports] # --8<-- [start:platforms_polars_create_table] + import lancedb + birds = pl.DataFrame( { "text": ["phoenix", "sparrow"], diff --git a/docs/web-tests/py/test_quickstart.py b/docs/web-tests/py/test_quickstart.py index bdcb8abff..c0bcc3b3a 100644 --- a/docs/web-tests/py/test_quickstart.py +++ b/docs/web-tests/py/test_quickstart.py @@ -45,6 +45,7 @@ class OwnedTables: self.db = db self.suffix = uuid.uuid4().hex[:12] self.claimed = [] + self.claimed_namespaces = [] def claim(self, name, existing, mode): owned = f"{name}_{self.suffix}" @@ -67,11 +68,42 @@ class OwnedTables: owned, mode = self.claim(name, self.table_names(), mode) return self.db.create_table(owned, *args, mode=mode, **kwargs) + def claim_namespace(self): + """A namespace only this test can see, for SQL text that must show + readers a literal, unqualified table name (so suffixing the name + itself, as `claim` does, isn't an option). The namespace is created + exclusively (no check-then-act): a collision raises instead of + silently sharing someone else's. `drop_claimed` cascades through it, + so individual tables and views inside never need their own claim. + """ + namespace_path = [f"quickstart_{self.suffix}"] + self.db.create_namespace(namespace_path, mode="create") + self.claimed_namespaces.append(namespace_path) + return NamespacedDB(self.db, namespace_path) + def drop_claimed(self): existing = self.table_names() for name in self.claimed: if name in existing: self.db.drop_table(name) + for namespace_path in self.claimed_namespaces: + self.db.drop_namespace(namespace_path, mode="skip", behavior="cascade") + + +class NamespacedDB: + """A `db.create_table` / `db.execute_query` view scoped to one namespace.""" + + def __init__(self, db, namespace_path): + self.db = db + self.namespace_path = namespace_path + + def create_table(self, name, *args, **kwargs): + kwargs.setdefault("namespace_path", self.namespace_path) + return self.db.create_table(name, *args, **kwargs) + + def execute_query(self, query, **kwargs): + kwargs.setdefault("default_namespace_path", self.namespace_path) + return self.db.execute_query(query, **kwargs) class AsyncOwnedTables(OwnedTables): @@ -193,21 +225,6 @@ def test_quickstart(db): # --8<-- [end:quickstart_output_pandas] assert result["frame_id"].to_list() == ["2", "4"] - # --8<-- [start:quickstart_curate_with_metadata] - curated = ( - table.search(query_vector) - .where("stats.motion >= 4") - .select(["frame_id", "video_id", "caption", "_distance"]) - .limit(2) - .to_polars() - ) - print(curated) - # --8<-- [end:quickstart_curate_with_metadata] - assert curated["frame_id"].to_list() == ["2", "4"] - - curated = table.search(query_vector).where("stats.motion < 4").limit(2).to_list() - assert [row["frame_id"] for row in curated] == ["1", "3"] - @pytest.mark.asyncio async def test_quickstart_async_api(async_db): @@ -234,66 +251,167 @@ async def test_quickstart_async_api(async_db): query_vector = [0.2, 0.8, 0.4, 0.9] # Ensure you run `pip install polars` beforehand - async_result = await ( - await async_table.search(query_vector) - ).select(["frame_id", "video_id", "caption", "_distance"]).limit(2).to_polars() + async_result = ( + await (await async_table.search(query_vector)) + .select(["frame_id", "video_id", "caption", "_distance"]) + .limit(2) + .to_polars() + ) print(async_result) # --8<-- [end:quickstart_vector_search_1_async] assert async_result["frame_id"].to_list() == ["2"] -def test_quickstart_derived_feature(db): +def test_quickstart_curate_with_sql(deployment): + # create_frames and the dedupe statement below name tables directly, to + # keep the extracted snippets reading like the quickstart. Run inside a + # namespace only this test can see, so a concurrent run can never + # overwrite this run's 'frames' or drop it out from under this one. + db = deployment.claim_namespace() table = create_frames(db) - # --8<-- [start:quickstart_add_feature] + # --8<-- [start:quickstart_curate_sample] + sample = db.execute_query( + "SELECT frame_id FROM frames TABLESAMPLE (2 ROWS)" + ).read_all() + print(sample.to_pylist()) + # --8<-- [end:quickstart_curate_sample] + assert sample.num_rows == 2 + + # --8<-- [start:quickstart_curate_dedupe_setup] + # Frame 5 is a near-duplicate of frame 2: the gripper is still closing, + # one video frame later, with an almost identical embedding. + table.add( + [ + { + "frame_id": "5", + "video_id": "clip-1", + "caption": "the two-finger gripper still closing on the cup", + "stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2}, + "embedding": [0.2, 0.9, 0.4, 0.89], + } + ] + ) + from lancedb.index import IvfFlat + + table.create_index( + "embedding", config=IvfFlat(num_partitions=1, distance_type="l2") + ) + table.wait_for_index(["embedding_idx"]) + # --8<-- [end:quickstart_curate_dedupe_setup] + + # --8<-- [start:quickstart_curate_dedupe] + db.execute_query(""" + CREATE MATERIALIZED VIEW frames_deduped AS + SELECT * FROM dedupe( + 'frames', + 'embedding', + distance_threshold => 0.03 + ) + """) + # --8<-- [end:quickstart_curate_dedupe] + + # --8<-- [start:quickstart_curate_dedupe_query] + deduped = db.execute_query( + "SELECT frame_id FROM frames_deduped ORDER BY frame_id" + ).read_all() + print(deduped.to_pylist()) + # --8<-- [end:quickstart_curate_dedupe_query] + assert deduped.column("frame_id").to_pylist() in ( + ["1", "2", "3", "4"], + ["1", "3", "4", "5"], + ) + + +def quality_scores(table): + rows = table.search().select(["frame_id", "video_id", "quality_score"]).to_list() + return {row["frame_id"]: row["quality_score"] for row in rows} + + +EXPECTED_QUALITY_SCORES = {"1": 3.5, "2": 4.0, "3": 3.0, "4": 3.75} + + +def flatten_stats(table): + # --8<-- [start:quickstart_flatten_stats] table.add_columns( { - "quality_score": "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)" + "motion": "cast(stats.motion as float)", + "sharpness": "cast(stats.sharpness as float)", + "exposure": "cast(stats.exposure as float)", + "framing": "cast(stats.framing as float)", } ) + # --8<-- [end:quickstart_flatten_stats] + + +def test_quickstart_derived_feature(db_path_factory): + db = lancedb.connect(db_path_factory("derived_feature")) + table = create_frames(db) + flatten_stats(table) + + # --8<-- [start:quickstart_add_feature] + from lancedb import col, udf + + @udf + def quality_score( + motion: float, sharpness: float, exposure: float, framing: float + ) -> float: + return (motion + sharpness + exposure + framing) / 4.0 + + version = db.create_function_async(quality_score).wait() + table.add_columns( + { + "quality_score": version( + motion=col("motion"), + sharpness=col("sharpness"), + exposure=col("exposure"), + framing=col("framing"), + ) + } + ) + table.refresh_column("quality_score") # --8<-- [end:quickstart_add_feature] # --8<-- [start:quickstart_query_feature] - features = table.search().select(["frame_id", "video_id", "quality_score"]).to_polars() + features = ( + table.search().select(["frame_id", "video_id", "quality_score"]).to_polars() + ) print(features) # --8<-- [end:quickstart_query_feature] - assert sorted(zip(features["frame_id"], features["quality_score"])) == [ - ("1", 3.5), - ("2", 4.0), - ("3", 3.0), - ("4", 3.75), - ] + assert quality_scores(table) == EXPECTED_QUALITY_SCORES -def caption_lengths(table): - rows = table.search().select(["caption", "caption_length"]).to_list() - return {row["caption"]: row["caption_length"] for row in rows} - - -def test_quickstart_computed_column(db_path_factory): - table = create_frames(lancedb.connect(db_path_factory("computed"))) - - # --8<-- [start:quickstart_computed_feature] - table.add_columns(computed={"caption_length": "length(caption)"}) - table.refresh_column("caption_length") - # --8<-- [end:quickstart_computed_feature] - lengths = caption_lengths(table) - assert lengths == {text: len(text) for text in lengths} - - -def test_quickstart_computed_column_on_a_deployment(deployment): +def test_quickstart_derived_feature_on_a_deployment(deployment): table = create_frames(deployment) + flatten_stats(table) - # --8<-- [start:quickstart_computed_feature_enterprise] - table.add_columns(computed={"caption_length": "length(caption)"}) - job = table.refresh_column_async("caption_length") + from lancedb import col, udf + + @udf + def quality_score( + motion: float, sharpness: float, exposure: float, framing: float + ) -> float: + return (motion + sharpness + exposure + framing) / 4.0 + + version = deployment.db.create_function_async(quality_score).wait() + table.add_columns( + { + "quality_score": version( + motion=col("motion"), + sharpness=col("sharpness"), + exposure=col("exposure"), + framing=col("framing"), + ) + } + ) + + # --8<-- [start:quickstart_add_feature_enterprise] + job = table.refresh_column_async("quality_score") job.wait() - # --8<-- [end:quickstart_computed_feature_enterprise] - lengths = caption_lengths(table) - assert len(lengths) == 4 - assert lengths == {text: len(text) for text in lengths} + # --8<-- [end:quickstart_add_feature_enterprise] + assert quality_scores(table) == EXPECTED_QUALITY_SCORES with pytest.raises(Exception): - table.refresh_column("caption_length") + table.refresh_column("quality_score") def test_quickstart_multimodal(db, tmp_path, monkeypatch): @@ -327,19 +445,17 @@ def test_quickstart_multimodal(db, tmp_path, monkeypatch): def test_quickstart_training(db): table = create_frames(db) + # The real walkthrough reaches this step with motion/sharpness already + # added back in flatten_stats(); add them here too so this test stands + # on its own, without repeating the add_columns call the snippet shows. + flatten_stats(table) # --8<-- [start:quickstart_training] import torch - from lancedb.permutation import Permutation + from lancedb.streaming import StreamingDataset - table.add_columns( - { - "motion": "cast(stats.motion as float)", - "sharpness": "cast(stats.sharpness as float)", - } - ) - dataset = Permutation.identity(table).select_columns(["motion", "sharpness"]) - dataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, shuffle=True) + dataset = StreamingDataset(table, columns=["motion", "sharpness"], shuffle_seed=42) + dataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, num_workers=0) # --8<-- [end:quickstart_training] batches = list(dataloader) assert len(batches) == 1 diff --git a/docs/web-tests/py/test_read_consistency.py b/docs/web-tests/py/test_read_consistency.py index 886bb5676..39d40c016 100644 --- a/docs/web-tests/py/test_read_consistency.py +++ b/docs/web-tests/py/test_read_consistency.py @@ -2,32 +2,31 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors -def test_read_consistency(): +def test_read_consistency(tmp_path): + uri = str(tmp_path) # --8<-- [start:read_consistency] from datetime import timedelta - from tempfile import TemporaryDirectory import lancedb - with TemporaryDirectory(prefix="lancedb-consistency-") as uri: - writer = lancedb.connect(uri) - table = writer.create_table("documents", [{"id": 1, "text": "first"}]) + writer = lancedb.connect(uri) + table = writer.create_table("documents", [{"id": 1, "text": "first"}]) - default_reader = lancedb.connect(uri).open_table("documents") - latest_reader = lancedb.connect( - uri, read_consistency_interval=timedelta(0) - ).open_table("documents") + default_reader = lancedb.connect(uri).open_table("documents") + latest_reader = lancedb.connect( + uri, read_consistency_interval=timedelta(0) + ).open_table("documents") - table.add([{"id": 2, "text": "second"}]) + table.add([{"id": 2, "text": "second"}]) - default_count = default_reader.count_rows() - latest_count = latest_reader.count_rows() - print(f"Default reader: {default_count} rows") # 1 - print(f"Zero-interval reader: {latest_count} rows") # 2 + default_count = default_reader.count_rows() + latest_count = latest_reader.count_rows() + print(f"Default reader: {default_count} rows") # 1 + print(f"Zero-interval reader: {latest_count} rows") # 2 - default_reader.checkout_latest() - refreshed_count = default_reader.count_rows() - print(f"After explicit refresh: {refreshed_count} rows") # 2 + default_reader.checkout_latest() + refreshed_count = default_reader.count_rows() + print(f"After explicit refresh: {refreshed_count} rows") # 2 # --8<-- [end:read_consistency] assert default_count == 1 diff --git a/docs/web-tests/py/test_search.py b/docs/web-tests/py/test_search.py index 4b7e8a9c7..03b957d58 100644 --- a/docs/web-tests/py/test_search.py +++ b/docs/web-tests/py/test_search.py @@ -60,6 +60,8 @@ class LanceSchema(LanceModel): def test_vector_search(): # --8<-- [start:exhaustive_search] + import lancedb + uri = "data/sample-lancedb" db = lancedb.connect(uri) data = [ @@ -112,6 +114,8 @@ def test_vector_search(): @pytest.mark.asyncio async def test_vector_search_async(): # --8<-- [start:exhaustive_search_async] + import lancedb + uri = "data/sample-lancedb" async_db = await lancedb.connect_async(uri) data = [ @@ -240,6 +244,8 @@ def test_fts_boost_query(): def test_fts_native(): # --8<-- [start:basic_fts] + import lancedb + uri = "data/sample-lancedb" db = lancedb.connect(uri) @@ -287,6 +293,8 @@ def test_fts_native(): @pytest.mark.asyncio async def test_fts_native_async(): # --8<-- [start:basic_fts_async] + import lancedb + uri = "data/sample-lancedb" async_db = await lancedb.connect_async(uri) @@ -651,6 +659,8 @@ def test_hybrid_search(): # --8<-- [end:class-Documents] # --8<-- [start:basic_hybrid_search] + import lancedb + data = [ {"text": "rebel spaceships striking from a hidden base"}, {"text": "have won their first victory against the evil Galactic Empire"}, @@ -700,6 +710,8 @@ async def test_hybrid_search_async(): # --8<-- [end:class-Documents] # --8<-- [start:basic_hybrid_search_async] + import lancedb + uri = "data/sample-lancedb" async_db = await lancedb.connect_async(uri) data = [ diff --git a/docs/web-tests/py/test_search_examples.py b/docs/web-tests/py/test_search_examples.py index 241a0f771..eccf50bfb 100644 --- a/docs/web-tests/py/test_search_examples.py +++ b/docs/web-tests/py/test_search_examples.py @@ -3,13 +3,13 @@ def test_vector_search(): - # --8<-- [start:vector_search] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-search-") as uri: db = lancedb.connect(uri) + # --8<-- [start:vector_search] table = db.create_table( "documents", [ @@ -48,7 +48,6 @@ def test_vector_search(): def test_text_search(): - # --8<-- [start:text_search] from tempfile import TemporaryDirectory import lancedb @@ -56,6 +55,7 @@ def test_text_search(): with TemporaryDirectory(prefix="lancedb-search-") as uri: db = lancedb.connect(uri) + # --8<-- [start:text_search] table = db.create_table( "documents", [ @@ -91,7 +91,6 @@ def test_text_search(): def test_hybrid_search(): - # --8<-- [start:hybrid_search] from tempfile import TemporaryDirectory import lancedb @@ -99,6 +98,7 @@ def test_hybrid_search(): with TemporaryDirectory(prefix="lancedb-search-") as uri: db = lancedb.connect(uri) + # --8<-- [start:hybrid_search] table = db.create_table( "documents", [ @@ -143,13 +143,13 @@ def test_hybrid_search(): def test_filter_search(): - # --8<-- [start:filter_search] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-search-") as uri: db = lancedb.connect(uri) + # --8<-- [start:filter_search] table = db.create_table( "documents", [ @@ -188,13 +188,13 @@ def test_filter_search(): def test_query_plan(): - # --8<-- [start:query_plan] from tempfile import TemporaryDirectory import lancedb with TemporaryDirectory(prefix="lancedb-search-") as uri: db = lancedb.connect(uri) + # --8<-- [start:query_plan] table = db.create_table( "documents", [ diff --git a/docs/web-tests/py/test_storage.py b/docs/web-tests/py/test_storage.py index f08ab07cf..207678ca3 100644 --- a/docs/web-tests/py/test_storage.py +++ b/docs/web-tests/py/test_storage.py @@ -43,18 +43,26 @@ def fake_connect(monkeypatch): def test_storage_snippets(fake_connect): # --8<-- [start:storage_connect_s3] + import lancedb + db = lancedb.connect("s3://bucket/path") # --8<-- [end:storage_connect_s3] # --8<-- [start:storage_connect_gcs] + import lancedb + db = lancedb.connect("gs://bucket/path") # --8<-- [end:storage_connect_gcs] # --8<-- [start:storage_connect_azure] + import lancedb + db = lancedb.connect("az://bucket/path") # --8<-- [end:storage_connect_azure] # --8<-- [start:storage_connect_timeout] + import lancedb + db = lancedb.connect( "s3://bucket/path", storage_options={"timeout": "60s"}, @@ -70,12 +78,16 @@ def test_storage_snippets(fake_connect): # --8<-- [end:storage_table_timeout] # --8<-- [start:storage_s3_ddb] + import lancedb + db = lancedb.connect( "s3+ddb://bucket/path?ddbTableName=my-dynamodb-table", ) # --8<-- [end:storage_s3_ddb] # --8<-- [start:storage_s3_ddb_local] + import lancedb + db = lancedb.connect( "s3+ddb://bucket/path?ddbTableName=my-dynamodb-table", storage_options={ @@ -87,6 +99,8 @@ def test_storage_snippets(fake_connect): # --8<-- [end:storage_s3_ddb_local] # --8<-- [start:storage_s3_sse_kms] + import lancedb + db = lancedb.connect( "s3://bucket/path", storage_options={ @@ -97,6 +111,8 @@ def test_storage_snippets(fake_connect): # --8<-- [end:storage_s3_sse_kms] # --8<-- [start:storage_azure_sas] + import lancedb + db = lancedb.connect( "az://my-container/my-database", storage_options={ @@ -107,6 +123,8 @@ def test_storage_snippets(fake_connect): # --8<-- [end:storage_azure_sas] # --8<-- [start:storage_s3_minio] + import lancedb + db = lancedb.connect( "s3://bucket/path", storage_options={ @@ -117,6 +135,8 @@ def test_storage_snippets(fake_connect): # --8<-- [end:storage_s3_minio] # --8<-- [start:storage_s3_express] + import lancedb + db = lancedb.connect( "s3://my-bucket--use1-az4--x-s3/path", storage_options={ @@ -127,6 +147,8 @@ def test_storage_snippets(fake_connect): # --8<-- [end:storage_s3_express] # --8<-- [start:storage_gcs_service_account] + import lancedb + db = lancedb.connect( "gs://my-bucket/my-database", storage_options={ @@ -136,6 +158,8 @@ def test_storage_snippets(fake_connect): # --8<-- [end:storage_gcs_service_account] # --8<-- [start:storage_azure_account] + import lancedb + db = lancedb.connect( "az://my-container/my-database", storage_options={ @@ -146,6 +170,8 @@ def test_storage_snippets(fake_connect): # --8<-- [end:storage_azure_account] # --8<-- [start:storage_tigris_connect] + import lancedb + db = lancedb.connect( "s3://your-bucket/path", storage_options={ diff --git a/docs/web-tests/py/test_tables.py b/docs/web-tests/py/test_tables.py index d17344aec..93c3729f7 100644 --- a/docs/web-tests/py/test_tables.py +++ b/docs/web-tests/py/test_tables.py @@ -99,12 +99,12 @@ def test_update_connect_local_snippet(monkeypatch): def test_table_creation_from_dicts(tmp_db): - # --8<-- [start:create_table_from_dicts] data = [ {"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}, {"vector": [0.2, 1.8], "lat": 40.1, "long": -74.1}, ] db = tmp_db + # --8<-- [start:create_table_from_dicts] db.create_table("test_table", data, mode="overwrite") tbl = db["test_table"] tbl.head() @@ -133,7 +133,6 @@ def test_create_table_conflict_handling(tmp_db): def test_table_creation_from_pandas(tmp_db): - # --8<-- [start:create_table_from_pandas] import pandas as pd data = pd.DataFrame( @@ -144,13 +143,13 @@ def test_table_creation_from_pandas(tmp_db): } ) db = tmp_db + # --8<-- [start:create_table_from_pandas] db.create_table("my_table_pandas", data, mode="overwrite") db["my_table_pandas"].head() # --8<-- [end:create_table_from_pandas] def test_table_creation_with_custom_schema(tmp_db): - # --8<-- [start:create_table_custom_schema] import pyarrow as pa custom_schema = pa.schema( @@ -166,6 +165,7 @@ def test_table_creation_with_custom_schema(tmp_db): {"vector": [0.2, 1.8, 0.4, 3.6], "lat": 40.1, "long": -74.1}, ] db = tmp_db + # --8<-- [start:create_table_custom_schema] tbl = db.create_table( "my_table_custom_schema", data, schema=custom_schema, mode="overwrite" ) @@ -173,7 +173,6 @@ def test_table_creation_with_custom_schema(tmp_db): def test_table_creation_from_polars(tmp_db): - # --8<-- [start:create_table_from_polars] import polars as pl data = pl.DataFrame( @@ -184,12 +183,12 @@ def test_table_creation_from_polars(tmp_db): } ) db = tmp_db + # --8<-- [start:create_table_from_polars] tbl = db.create_table("my_table_pl", data, mode="overwrite") # --8<-- [end:create_table_from_polars] def test_table_creation_from_arrow(tmp_db): - # --8<-- [start:create_table_from_arrow] import numpy as np import pyarrow as pa @@ -209,12 +208,12 @@ def test_table_creation_from_arrow(tmp_db): ["vector", "text"], ) db = tmp_db + # --8<-- [start:create_table_from_arrow] tbl = db.create_table("f16_tbl", data, schema=schema, mode="overwrite") # --8<-- [end:create_table_from_arrow] def test_table_creation_from_pydantic(tmp_db): - # --8<-- [start:create_table_from_pydantic] from lancedb.pydantic import LanceModel, Vector class Content(LanceModel): @@ -229,12 +228,12 @@ def test_table_creation_from_pydantic(tmp_db): return f"https://www.imdb.com/title/tt{self.imdb_id}" db = tmp_db + # --8<-- [start:create_table_from_pydantic] tbl = db.create_table("movielens_small", schema=Content, mode="overwrite") # --8<-- [end:create_table_from_pydantic] def test_table_creation_nested_schema(tmp_db): - # --8<-- [start:create_table_nested_schema] from lancedb.pydantic import LanceModel, Vector # --8<-- [start:tables_document_model] @@ -252,6 +251,7 @@ def test_table_creation_nested_schema(tmp_db): document: Document db = tmp_db + # --8<-- [start:create_table_nested_schema] tbl = db.create_table("nested_table", schema=NestedSchema, mode="overwrite") # --8<-- [end:create_table_nested_schema] @@ -314,11 +314,11 @@ def test_add_from_dataset(tmp_db, tmp_path): data_path = str(tmp_path) - # --8<-- [start:add_from_dataset] import pyarrow.dataset as ds dataset = ds.dataset(data_path, format="parquet") db = tmp_db + # --8<-- [start:add_from_dataset] table = db.create_table("my_table", schema=dataset.schema, mode="overwrite") table.add(dataset) # --8<-- [end:add_from_dataset] @@ -326,7 +326,6 @@ def test_add_from_dataset(tmp_db, tmp_path): def test_table_creation_from_iterator(tmp_db): - # --8<-- [start:create_table_from_iterator] import pyarrow as pa schema = pa.schema( @@ -352,12 +351,13 @@ def test_table_creation_from_iterator(tmp_db): ) db = tmp_db + # --8<-- [start:create_table_from_iterator] db.create_table("batched_table", make_batches(), schema=schema, mode="overwrite") # --8<-- [end:create_table_from_iterator] def test_open_existing_table(tmp_db): - # --8<-- [start:open_existing_table] db = tmp_db + # --8<-- [start:open_existing_table] # Create a table first data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}] db.create_table("test_table", data, mode="overwrite") @@ -371,7 +371,6 @@ def test_open_existing_table(tmp_db): def test_create_empty_table(tmp_db): - # --8<-- [start:create_empty_table] import pyarrow as pa schema = pa.schema( @@ -382,12 +381,12 @@ def test_create_empty_table(tmp_db): ] ) db = tmp_db + # --8<-- [start:create_empty_table] tbl = db.create_table("test_empty_table", schema=schema, mode="overwrite") # --8<-- [end:create_empty_table] def test_create_empty_table_pydantic(tmp_db): - # --8<-- [start:create_empty_table_pydantic] from lancedb.pydantic import LanceModel, Vector class Item(LanceModel): @@ -396,6 +395,7 @@ def test_create_empty_table_pydantic(tmp_db): price: float db = tmp_db + # --8<-- [start:create_empty_table_pydantic] tbl = db.create_table( "test_empty_table_new", schema=Item.to_arrow_schema(), mode="overwrite" ) @@ -403,8 +403,8 @@ def test_create_empty_table_pydantic(tmp_db): def test_drop_table(tmp_db): - # --8<-- [start:drop_table] db = tmp_db + # --8<-- [start:drop_table] # Create a table first data = [{"vector": [1.1, 1.2], "lat": 45.5}] db.create_table("my_table", data, mode="overwrite") @@ -865,6 +865,7 @@ def _setup_schema_add_table(db): def _setup_schema_alter_table(tmp_db, data=None): + db = tmp_db # --8<-- [start:schema_alter_setup] table_name = "schema_evolution_alter_example" if data is None: @@ -893,12 +894,13 @@ def _setup_schema_alter_table(tmp_db, data=None): "vector": pa.list_(pa.float32(), 128), } ) - table = tmp_db.create_table(table_name, data, schema=schema, mode="overwrite") + table = db.create_table(table_name, data, schema=schema, mode="overwrite") # --8<-- [end:schema_alter_setup] return table def _setup_schema_drop_table(tmp_db, data=None): + db = tmp_db # --8<-- [start:schema_drop_setup] if data is None: data = [ @@ -927,7 +929,7 @@ def _setup_schema_drop_table(tmp_db, data=None): "vector": np.random.random(128).tolist(), }, ] - table = tmp_db.create_table("schema_evolution_drop_example", data, mode="overwrite") + table = db.create_table("schema_evolution_drop_example", data, mode="overwrite") # --8<-- [end:schema_drop_setup] return table @@ -1061,9 +1063,10 @@ def test_alter_columns_multiple(tmp_db): def test_alter_columns_with_expression(tmp_db): + db = tmp_db # --8<-- [start:alter_columns_with_expression] # For custom transforms, create a new column from a SQL expression. - expression_table = tmp_db.create_table( + expression_table = db.create_table( "schema_evolution_expression_example", [{"id": 1, "price_text": "$100"}], mode="overwrite", @@ -1111,10 +1114,10 @@ def test_drop_columns_multiple(tmp_db): def test_alter_vector_column(tmp_db): - # --8<-- [start:alter_vector_column] vector_dim = 768 # Your embedding dimension table_name = "vector_alter_example" db = tmp_db + # --8<-- [start:alter_vector_column] data = [ { "id": 1, @@ -1197,10 +1200,10 @@ def _setup_versioning_table(tmp_db, data=None, table_name="quotes_versioning_exa def test_versioning_basic_setup(tmp_db): - # --8<-- [start:versioning_basic_setup] import pyarrow as pa db = tmp_db + # --8<-- [start:versioning_basic_setup] table_name = "quotes_versioning_example" data = [ @@ -1478,11 +1481,12 @@ def test_branches(tmp_db): # ============================================================================ -def test_consistency_strong(tmp_db): +def test_consistency_strong(tmp_path): + uri = str(tmp_path) # --8<-- [start:consistency_strong] + import lancedb from datetime import timedelta - uri = str(tmp_db.uri) writer_db = lancedb.connect(uri) reader_db = lancedb.connect(uri, read_consistency_interval=timedelta(0)) writer_table = writer_db.create_table( @@ -1496,11 +1500,12 @@ def test_consistency_strong(tmp_db): assert rows_after_write == 2 -def test_consistency_eventual(tmp_db): +def test_consistency_eventual(tmp_path): + uri = str(tmp_path) # --8<-- [start:consistency_eventual] + import lancedb from datetime import timedelta - uri = str(tmp_db.uri) writer_db = lancedb.connect(uri) reader_db = lancedb.connect(uri, read_consistency_interval=timedelta(seconds=3600)) writer_table = writer_db.create_table( @@ -1514,9 +1519,11 @@ def test_consistency_eventual(tmp_db): assert rows_after_write == 1 -def test_consistency_checkout_latest(tmp_db): +def test_consistency_checkout_latest(tmp_path): + uri = str(tmp_path) # --8<-- [start:consistency_checkout_latest] - uri = str(tmp_db.uri) + import lancedb + writer_db = lancedb.connect(uri) reader_db = lancedb.connect(uri) writer_table = writer_db.create_table( diff --git a/docs/web-tests/rs/quickstart.rs b/docs/web-tests/rs/quickstart.rs index b0df4daba..e957b2b9c 100644 --- a/docs/web-tests/rs/quickstart.rs +++ b/docs/web-tests/rs/quickstart.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use lancedb::{connect, table::NewColumnTransform}; +use lancedb::connect; // --8<-- [start:quickstart_define_struct] use std::sync::Arc; @@ -54,14 +54,12 @@ fn frames_schema() -> Arc { ])) } -fn frames_to_reader( - schema: Arc, - rows: &[Frame], -) -> Box { - let frame_ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.frame_id.as_str())); - let video_ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.video_id.as_str())); - let captions = - LargeStringArray::from_iter_values(rows.iter().map(|row| row.caption.as_str())); +fn frames_to_reader(schema: Arc, rows: &[Frame]) -> Box { + let frame_ids = + LargeStringArray::from_iter_values(rows.iter().map(|row| row.frame_id.as_str())); + let video_ids = + LargeStringArray::from_iter_values(rows.iter().map(|row| row.video_id.as_str())); + let captions = LargeStringArray::from_iter_values(rows.iter().map(|row| row.caption.as_str())); let motion = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.motion)); let sharpness = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.sharpness)); @@ -220,31 +218,6 @@ async fn main() { assert_eq!(frame_id_col.get(0).unwrap(), "2"); assert_eq!(frame_id_col.get(1).unwrap(), "4"); - // --8<-- [start:quickstart_curate_with_metadata] - let curated = table - .query() - .nearest_to(&query_vector) - .unwrap() - .only_if("stats.motion >= 4") - .select(Select::Columns(vec![ - "frame_id".to_string(), - "video_id".to_string(), - "caption".to_string(), - "_distance".to_string(), - ])) - .limit(2) - .execute() - .await - .unwrap() - .into_polars() - .await - .unwrap(); - println!("{curated:?}"); - // --8<-- [end:quickstart_curate_with_metadata] - let curated_frame_id_col = curated.column("frame_id").unwrap().str().unwrap(); - assert_eq!(curated_frame_id_col.get(0).unwrap(), "2"); - assert_eq!(curated_frame_id_col.get(1).unwrap(), "4"); - // --8<-- [start:quickstart_output_array] let result = table .query() @@ -268,38 +241,6 @@ async fn main() { let frame_id_col = result.column("frame_id").unwrap().str().unwrap(); assert_eq!(frame_id_col.get(0).unwrap(), "2"); - // --8<-- [start:quickstart_add_feature] - table - .add_columns( - NewColumnTransform::SqlExpressions(vec![( - "quality_score".to_string(), - "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)" - .to_string(), - )]), - None, - ) - .await - .unwrap(); - // --8<-- [end:quickstart_add_feature] - - // --8<-- [start:quickstart_query_feature] - let features = table - .query() - .select(Select::Columns(vec![ - "frame_id".to_string(), - "video_id".to_string(), - "quality_score".to_string(), - ])) - .execute() - .await - .unwrap() - .into_polars() - .await - .unwrap(); - println!("{features:?}"); - // --8<-- [end:quickstart_query_feature] - assert_eq!(features.column("quality_score").unwrap().len(), 4); - // What the quickstart's download step leaves in an application's directory. let app = tempfile::tempdir().unwrap(); std::fs::create_dir(app.path().join("data")).unwrap(); diff --git a/docs/web-tests/ts/connection.test.ts b/docs/web-tests/ts/connection.test.ts index 651be7d36..8cab34c26 100644 --- a/docs/web-tests/ts/connection.test.ts +++ b/docs/web-tests/ts/connection.test.ts @@ -93,6 +93,12 @@ async function connectObjectStorageExample() { async function namespaceTableOpsExample() { // --8<-- [start:namespace_table_ops] + async function collectNames(items: AsyncIterable): Promise { + const names: string[] = []; + for await (const name of items) names.push(name); + return names; + } + const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" }); // Create namespace tree: prod/search and prod/recommendations @@ -124,6 +130,12 @@ async function namespaceTableOpsExample() { async function namespaceAdminOpsExample() { // --8<-- [start:namespace_admin_ops] + async function collectNames(items: AsyncIterable): Promise { + const names: string[] = []; + for await (const name of items) names.push(name); + return names; + } + const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" }); const namespace = ["prod", "search"]; @@ -131,7 +143,10 @@ async function namespaceAdminOpsExample() { await db.createNamespace(["prod", "search"]); const childNamespaces = await collectNames(db.listNamespaces(["prod"])); - console.log(`Child namespaces under ${JSON.stringify(namespace)}:`, childNamespaces); + console.log( + `Child namespaces under ${JSON.stringify(namespace)}:`, + childNamespaces, + ); // Child namespaces under ["prod","search"]: [ 'search' ] const metadata = await db.describeNamespace(["prod", "search"]); diff --git a/docs/web-tests/ts/quickstart.test.ts b/docs/web-tests/ts/quickstart.test.ts index 6796e0613..d1f2c6000 100644 --- a/docs/web-tests/ts/quickstart.test.ts +++ b/docs/web-tests/ts/quickstart.test.ts @@ -154,49 +154,6 @@ describe.each(connections)("quickstart (%s)", (connection) => { console.table(result); // --8<-- [end:quickstart_vector_search_1] expect(result.map((row) => row.frame_id)).toEqual(["2", "4"]); - - // --8<-- [start:quickstart_curate_with_metadata] - const curated = await table - .search(queryVector) - .where("stats.motion >= 4") - .select(["frame_id", "video_id", "caption", "_distance"]) - .limit(2) - .toArray(); - console.table(curated); - // --8<-- [end:quickstart_curate_with_metadata] - expect(curated.map((row) => row.frame_id)).toEqual(["2", "4"]); - }); - }); - - test("a derived feature", async () => { - await withDatabase(connection, async (db) => { - const table = await createFrames(db); - - // --8<-- [start:quickstart_add_feature] - await table.addColumns([ - { - name: "quality_score", - valueSql: - "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)", - }, - ]); - // --8<-- [end:quickstart_add_feature] - - // --8<-- [start:quickstart_query_feature] - const features = await table - .query() - .select(["frame_id", "video_id", "quality_score"]) - .toArray(); - console.table(features); - // --8<-- [end:quickstart_query_feature] - expect( - features.map((row) => [row.frame_id, row.quality_score]).sort(), - ).toEqual([ - ["1", 3.5], - ["2", 4], - ["3", 3], - ["4", 3.75], - ]); }); }); diff --git a/docs/web/.mintignore b/docs/web/.mintignore index 79cce2724..8fea3d17d 100644 --- a/docs/web/.mintignore +++ b/docs/web/.mintignore @@ -1,22 +1,8 @@ -# Functions are documented before their release. At release, remove these -# entries, restore the /feature-engineering/functions redirect to -# /management/function, publish the drafts marked "Draft for the Functions -# release", restore `availability` frontmatter (removed while gated, since -# the comparison table on index.mdx links every page that declares one, -# draft or not) to management/function.mdx and sql/ddl/function.mdx -- each -# currently carries a plain `Enterprise` instead -# -- and re-link curation/chunking.mdx's plain-text `CREATE FUNCTION`/ -# `add_columns` mentions to /management/function and /sql/ddl/function#create -# now that those pages have a route. Chunking stays published ahead of -# Functions shipping, so its examples intentionally do not link to either -# gated page -- only an unrouted page would break. -management/function.mdx -sql/ddl/function.mdx - -# GRANT/REVOKE currently only covers privileges on Secrets and Functions -# (CREATE SECRET, CREATE FUNCTION, USAGE on a secret or function), which are -# themselves part of the Functions release: see the "Draft for the Functions -# release" block in governance/authorization.mdx#privileges. At release, -# remove this entry, add the page to the navigation in docs.json, and give it -# `availability` frontmatter like the rest of the SQL reference. -sql/ddl/grant.mdx +tools/cli.mdx +# Branching is Beta; not documented until early access. tables/branching.mdx +# stays reachable (out of the nav only): SDK error messages link to it. +# To restore: docs.json Tutorials > Feature Engineering, after tutorials/feature-engineering/materialized-views. +agent-branch-experiments.mdx +# JSON columns are Beta; not documented until early access. +# To restore: docs.json Documentation > SQL Reference > DQL, after sql/dql/vector-distance. +sql/dql/json-functions.mdx diff --git a/docs/web/agent-branch-experiments.mdx b/docs/web/agent-branch-experiments.mdx index 30a3893e7..fce32ffb1 100644 --- a/docs/web/agent-branch-experiments.mdx +++ b/docs/web/agent-branch-experiments.mdx @@ -26,28 +26,30 @@ process-wide current branch. Install the model packages, then download the `nomic-embed-text` model from Ollama (or any other model you prefer): -```bash + +```bash Bash icon="terminal" uv add sentence-transformers ollama ollama pull nomic-embed-text ``` + It's always recommended to measure the results of an experiment on a fixed evaluation set. Here's an example of how you could ask the agent to run both experiments and compare the results: ```text Agent prompt Use the lancedb plugin and the LanceDB branching documentation to compare two -embedding experiments on the `camelot_multimodal` table. +embedding experiments on the `frames` table from the quickstart. 1. Fork `embed-minilm` from `main`. Build normalized embeddings from - `"{role}. {description}"` with - `sentence-transformers/all-MiniLM-L6-v2` and add them as `vector_minilm`. + `caption` with `sentence-transformers/all-MiniLM-L6-v2` and add them as + `vector_minilm`. 2. Fork `embed-nomic` from `main`. Embed the identical text with Ollama `nomic-embed-text` and add the results as `vector_nomic`. 3. Process rows in batches and write only through each branch-scoped table handle. Verify that neither new column appears on `main`. -4. Evaluate both branches with the queries "wise magical advisor", - "treacherous rebel", and "virtuous Grail knight". Report the top three names, - latency, and whether the expected character ranks first. +4. Evaluate both branches with the queries "a gripper closing on an object", + "a robot arm holding steady", and "lowering an object onto a surface". + Report the top match, latency, and whether the expected frame ranks first. 5. Do not modify `main` and do not delete either branch. Recommend a winner based on the results. ``` diff --git a/docs/web/api-reference/rest/index.mdx b/docs/web/api-reference/rest/index.mdx index d6364d92c..3b89b8320 100644 --- a/docs/web/api-reference/rest/index.mdx +++ b/docs/web/api-reference/rest/index.mdx @@ -33,11 +33,13 @@ To authenticate to the Enterprise REST API, you need the endpoint for your deplo 2. Export those values in your terminal: -```bash + +```bash Bash icon="terminal" export LANCEDB_API_KEY="" export LANCEDB_HOST_OVERRIDE="https://your-enterprise-endpoint.com" export LANCEDB_DATABASE="your-database-name" ``` + `LANCEDB_HOST_OVERRIDE` is the endpoint the SDKs take as `host_override`; the database name is the part of its `db://` URI after `db://`. @@ -48,11 +50,13 @@ database name is the part of its `db://` URI after `db://`. 4. Check that you can reach the deployment and list tables: -```bash + +```bash Bash icon="terminal" curl -X GET "$LANCEDB_HOST_OVERRIDE/v1/table/" \ -H "x-api-key: $LANCEDB_API_KEY" \ -H "x-lancedb-database: $LANCEDB_DATABASE" ``` + The response lists one page of table names, with a token for the next page when there are more. @@ -62,7 +66,8 @@ If your deployment endpoint already includes the database host name, you can omi 5. Create a table to confirm write access. Let's call it `words`. A table is created from an Arrow IPC stream, which this writes with PyArrow: -```bash + +```bash Bash icon="terminal" python -c "import pyarrow as pa, sys; t = pa.table({'word': ['hello', 'world']}); w = pa.ipc.new_stream(sys.stdout.buffer, t.schema); w.write_table(t); w.close()" > words.arrow curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/create" \ @@ -71,16 +76,19 @@ curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/create" \ -H "x-lancedb-database: $LANCEDB_DATABASE" \ --data-binary @words.arrow ``` + 6. Check that the table has been created: -```bash + +```bash Bash icon="terminal" curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/describe" \ -H "Content-Type: application/json" \ -H "x-api-key: $LANCEDB_API_KEY" \ -H "x-lancedb-database: $LANCEDB_DATABASE" \ -d '{}' ``` + That's it. You're connected! Now, you can start adding data and querying it. You can visit the tutorial section to build your own applications with LanceDB. diff --git a/docs/web/basics/agentic-skills.mdx b/docs/web/basics/agentic-skills.mdx index b87574dff..d88b5dddf 100644 --- a/docs/web/basics/agentic-skills.mdx +++ b/docs/web/basics/agentic-skills.mdx @@ -6,12 +6,6 @@ icon: robot keywords: ["agents", "plugin", "claude code", "codex", "cursor", "copilot"] --- -import { - PyCamelotSchema, - PyCamelotBatches, - PyCamelotOssIngestion, -} from '/snippets/build_with_ai_agents.mdx'; - A coding agent writing LanceDB code from memory writes whatever was in its training data: often an older API, sometimes one that never existed. The LanceDB agent plugin fixes that by supplying the current reference at the point @@ -74,219 +68,79 @@ The `npx plugins` installer defaults to the same user-wide scope. Pass everyone working in it gets the same plugin, or `-t ` to install for a single agent rather than every one it detects: -```bash + +```bash Bash icon="terminal" npx plugins add lancedb/lancedb-agent-plugins --scope project -t cursor ``` + Not every agent supports project scope; `npx plugins targets` lists what it found and what each target supports. -### Get started with the LanceDB agent plugin {#get-started-with-the-lancedb-agent-plugin} +## Example prompts {#example-prompts} -This tutorial uses the Camelot dataset from the [quickstart](/quickstart), with -a portrait added for each character. Each LanceDB row contains validated -metadata and raw JPEG bytes. Text, images, and any embeddings you add later -remain in the same table. +These prompts show the kind of work the plugin helps an agent get right on +the first try. Adapt the dataset names, columns, and models to your own data. -### 1\. Download the multimodal dataset {#1-download-the-multimodal-dataset} +### Ingest and search robotics data {#example-robotics} -From a new project directory, download the JSON file and portraits: + +```text Prompt +Import the HuggingFace dataset `lance-format/koch_pick_place_5_lego-lance` +into LanceDB. -```bash -mkdir -p data/img +Create a Function `extract_frames(video, timestamp)` that extracts each frame +from the videos table and stores the output as JPEG in a Lance blob column. +Use `torchcodec` to decode frames on a GPU, and stream the video through the +blob input instead of loading it into memory. Install dependencies with pip, +not conda. -BASE_URL="https://docs.lancedb.com/static/assets/tutorials/build-with-ai-agents/camelot/data" -curl -fsSL "$BASE_URL/camelot.json" -o data/camelot.json +Create a table `koch_frames` from `extract_frames`, populated from the videos +and frames metadata in the existing tables. -for image in \ - arthur.jpg \ - guinevere.jpg \ - merlin.jpg \ - mordred.jpg \ - sir_galahad.jpg \ - sir_gawain.jpg \ - sir_lancelot.jpg \ - sir_percival.jpg -do - curl -fsSL "$BASE_URL/img/$image" -o "data/img/$image" -done +Create a Function that uses a vision-language model to caption each frame, +and add its output as a column named `caption` on `koch_frames`. It needs a +GPU. + +Create a full-text search index on `koch_frames.caption`. ``` + -Each JSON record has this shape: +### Deduplicate near-identical images {#example-dedup} -```json -{ - "id": 2, - "name": "Merlin", - "role": "Wizard and Advisor", - "description": "A powerful wizard and prophet who mentors Arthur.", - "stats": { - "strength": 2, - "courage": 4, - "magic": 5, - "wisdom": 5 - }, - "img": "data/img/merlin.jpg" -} + +```text Prompt +Import the HuggingFace dataset `lance-format/BDD100K-enriched` into LanceDB. + +Create a Function `phash(image)` that computes a perceptual hash with the +`ImageHash` package, and add it as a column named `phash`. + +Build a vector index on `phash` using Hamming distance, and pick good index +parameters for this dataset size. + +Create a materialized view that clusters images whose `phash` Hamming +distance is less than 1, using `duplicate_pairs`. + +Summarize the result: cluster count, cluster size distribution, and the 10 +largest clusters with sample image ids. ``` + -JSON input may have missing fields, unexpected fields, or values of the wrong -type. The LanceDB plugin tells the agent to validate each record with strict -Pydantic models before writing it. +### Ingest a large code dataset {#example-code} -After the agent writes the pipeline, inspect the schema, batching, and write -path rather than assuming it followed the plugin's guidance correctly. + +```text Prompt +Import the C, C++, and Python metadata from the HuggingFace dataset +`bigcode/the-stack-v2` into a single table `stack_v2_code`, with an extra +`language` column recording which of the three it is. -### 2\. Prompt your agent to build the pipeline {#2-prompt-your-agent-to-build-the-pipeline} +Add a `content` column and backfill it with each file's source, downloaded +from `s3://softwareheritage/content/{blob_id}` using the `blob_id` already in +the table. Compress `content` with the best codec LanceDB supports for code +text. -Install the Python packages used by the example: - -```bash icon="terminal" -uv init -uv add lancedb pyarrow pydantic +Use `bigcode/starcoder2-3b` to add a `perplexity_starcoder2` column, then +build an index on it. ``` - -If you're using LanceDB Enterprise, ask the agent to ingest into an Enterprise table, -provide the relevant environment variables for connecting to your Enterprise deployment -in a local `.env` file, and point the agent to it. - -```text .env -LANCEDB_URI=db://your_project_name -LANCEDB_API_KEY=your_api_key_here -LANCEDB_REGION=us-east-1 -LANCEDB_HOST_OVERRIDE=https://your-enterprise-endpoint.com -``` - -If you're using LanceDB Embedded, no connection settings are required, as it runs as an -embedded retrieval library. A simple prompt like this should work: - -```text Agent prompt -# If using LanceDB Embedded -Use the lancedb plugin to ingest the dataset in `data/` into a LanceDB -Embedded table. - -# If using enterprise -Use the lancedb plugin to ingest the dataset in `data/` into a LanceDB -Enterprise table using the connection information in `.env`. -``` - -Because the plugin is registered with the agent's own plugin system, the agent -should pick it up on its own once you restart the session. If it does not, -simply ask it to use the `lancedb` plugin in the prompt, as shown above. - -That should be enough! The agent will create `ingest_multimodal.py`, or similar. -The following sections inspect the script to verify that it follows the plugin's guidance. - -#### Data validation {#data-validation} - -The plugin encourages the agent to validate each record with Pydantic before writing it. -The agent should ideally define a schema for the table and a nested schema for the -`stats` field. - - - {PyCamelotSchema} - - -In this case, our agent correctly defined `Character` and `Stats` Pydantic models -and validated the JSON before adding it to the table. - -#### Batched ingestion {#batched-ingestion} - -Naively calling `table.add()` once per row is slow, and is considered an anti-pattern -in LanceDB. The plugin encourages the agent to collect incoming rows into batches and -write them with a single `table.add()` call. When you use the plugin, the agent should -produce something like this: - - - {PyCamelotBatches} - - -The script calls `Character.model_validate(...)` before adding a record to the -batch. If validation fails, that batch is never written. The function yields up -to `batch_size` rows at a time, providing an iterable of batches for the ingestion step, -shown next. - -#### Table maintenance {#table-maintenance} -For LanceDB Embedded, the plugin instructs the agent to call -`table.optimize()` after the ingestion loop. This compacts small fragments, cleans up -old versions according to the retention policy, and incorporates new data into indexes. - - - {PyCamelotOssIngestion} - - -If you're using LanceDB Enterprise, the plugin mentions that this step is not needed -because LanceDB Enterprise handles maintenance automatically. - - - -This example dataset has only eight rows, so the default batch size writes it in -one call. Larger inputs should still avoid single-row write commits. - - -### 3\. Run the Embedded pipeline {#3-run-the-oss-pipeline} - -```bash -uv run python ingest_multimodal.py -``` - -The table now contains the validated character records and their JPEG bytes. -Here are the first three rows: - -| Image | Character | Role | -| --- | --- | --- | -| King Arthur | King Arthur | King of Camelot | -| Merlin | Merlin | Wizard and Advisor | -| Queen Guinevere | Queen Guinevere | Queen of Camelot | - -Once your pipeline works, you can [run experiments on branches](/agent-branch-experiments) -to try new embedding models, parsers, or search settings without touching `main`. - -### Takeaways {#takeaways} - -The example in this tutorial was small, but similar ideas apply to other workflows, too. -Give the agent the data source, the constraints it must respect, and the -artifacts it should return. - -The plugin supplies LanceDB-specific guidance, but it's the user's responsibility to -ensure the output makes sense for the application. - -### Try the plugin with your own dataset {#try-the-plugin-with-your-own-dataset} - -The plugin shown in this tutorial should generalize reasonably well to other use cases. -If you find any issues, open [an issue](https://github.com/lancedb/lancedb-agent-plugins/issues) -on GitHub, clearly describing the intended behavior. - -You can choose LanceDB Embedded or LanceDB Enterprise based on how the work will run: - -Start with [LanceDB Embedded](/quickstart) during the early stages of a project -when an agent is helping you prototype, -explore a dataset, or run small workflows on a subset of the data. The application owns -the storage and lifecycle work, so ask the agent to validate inputs, write in -batches, and it will include table maintenance operations such as `optimize()` -where appropriate. - -Choose [LanceDB Enterprise](/enterprise) when the resulting table becomes -shared production infrastructure, and the workload needs distributed capacity, -private deployment, or platform-managed operations. The data format and the core -table API stay the same, so the pipeline's table and search code carries over: -the agent connects to an Enterprise `db://` table, leaves maintenance to the -deployment instead of calling `optimize()`, and submits long-running work as -[jobs](/basics/jobs). - -## What agents are good at here {#workflows} - -The walkthrough above is one pattern. The other has its own tutorial. - - - - Isolate agent-driven experiments on a branch, evaluate them on a fixed test - set, and promote only the winner. - - - -It is the more interesting pattern. [Branches](/management/table#versioning) -give an agent somewhere to be wrong safely: it can rewrite a schema, recompute a -column, or try three embedding models without touching `main`, and you keep only -what measured better. + diff --git a/docs/web/basics/catalog.mdx b/docs/web/basics/catalog.mdx index 976aac300..1e95aeca4 100644 --- a/docs/web/basics/catalog.mdx +++ b/docs/web/basics/catalog.mdx @@ -1,9 +1,9 @@ --- -title: "LanceDB Catalog" -sidebarTitle: "LanceDB Catalog" +title: "LanceDB Lakehouse" +sidebarTitle: "LanceDB Lakehouse" description: "LanceDB Lakehouse objects are organized into a catalog of databases, namespaces and tables -- connect to a database to work with them." icon: sitemap -keywords: ["catalog", "namespace", "hierarchy", "governance", "database", "table", "view", "connect", "uri", "embedded", "object storage", "s3", "enterprise", "db://"] +keywords: ["catalog", "namespace", "namespace path", "hierarchy", "governance", "database", "table", "view", "connect", "uri", "embedded", "object storage", "s3", "enterprise", "db://"] --- import { @@ -17,39 +17,168 @@ import { TsConnectEnterprisePlaceholders, TsConnectObjectStorage, } from '/snippets/connection.mdx'; +import { + PyStorageS3Minio, + PyStorageS3Express, + PyStorageS3SseKms, + TsStorageS3Minio, + TsStorageS3Express, + TsStorageS3SseKms, +} from '/snippets/storage.mdx'; -## Catalog overview {#catalog} +## Catalog Hierarchy {#hierarchy} A catalog keeps track of named data objects, such as tables and views, so -applications can discover and access them. In LanceDB, it organizes those -objects into databases and namespaces -- similar to a catalog in Postgres, -Snowflake, or other database systems. +applications can discover and access them. In LanceDB Enterprise, the +catalog is the top-level entry point: it organizes databases, which in turn +organize namespaces and tables -- similar to a catalog in Postgres, +Snowflake, or other database systems. The catalog itself has no name of its +own -- it's just the root -- and an Enterprise deployment's catalog is +identified by its endpoint, not a name like the objects beneath it. + +LanceDB Embedded has no catalog at all. Connect directly to a +[database](#connecting-to-database) instead of going through a catalog. + +A database contains namespaces that group related tables and views. +Namespaces can also contain other namespaces, letting teams organize data by +project, environment or purpose. + +For example, a search application can keep production and staging data in +separate namespaces within the same database, with `prod` further split into +a nested `search` namespace: + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TD + catalog["root catalog"] --> database["ai_data · database"] + database --> prod["prod · namespace"] + database --> staging["staging · namespace"] + prod --> search["search · namespace"] + search --> search_docs["documents · table"] + search --> search_view["recent_documents · view"] + search --> search_fn["embed · function"] + staging --> staging_docs["documents · table"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TD + catalog["root catalog"] --> database["ai_data · database"] + database --> prod["prod · namespace"] + database --> staging["staging · namespace"] + prod --> search["search · namespace"] + search --> search_docs["documents · table"] + search --> search_view["recent_documents · view"] + search --> search_fn["embed · function"] + staging --> staging_docs["documents · table"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 +``` + +
+ +| Object | What it represents | +| --- | --- | +| [Catalog](/management/catalog) | The unnamed root of an Enterprise deployment, identified by its endpoint; lists, creates and drops databases. Not present in Embedded. | +| [Database](/management/database) | A container for namespaces and their data objects. | +| [Namespace](/management/namespace) | A named group of catalog objects -- tables, views, secrets, functions, storage integrations, or nested namespaces -- addressed by its namespace path. | +| [Table](/management/table) | Data stored as rows and columns. | +| [View](/management/view) | A saved query, evaluated when read. Available in Enterprise. | +| [Materialized view](/management/materialized-view) | The stored results of a query, updated by a refresh. Available in Enterprise. | +| [Secret](/management/secret) | A named credential that a Function binds by reference. Available in Enterprise. | +| [Storage integration](/management/storage-integration) | A named credential for reading or importing from storage outside the deployment's own tables, such as an S3 prefix or a HuggingFace repository. Available in Enterprise. | +| [Function](/management/function) | Registered code used to compute column values. Available in Enterprise. | + + + +### Namespace name and path {#namespace-path} + +A namespace's **name** is just its own component, such as `search`. Its +**path** is the full sequence of names from the database down to it: in the +diagram above, `search` sits inside `prod`, so its path is the sequence +`prod`, `search`. A namespace path is never written by joining those names +with `.` -- a dot is a valid character inside a name, so a dot-joined path +couldn't always be split back into its components unambiguously. The two +forms below are how SQL actually writes one. + +### Schema {#schema} + +SQL addresses a namespace path as a **schema**, the ANSI standard's term for +the same concept: a nested path collapses into one identifier, its +components joined by `$` instead of `.`. The path's length changes what the +schema looks like: + +| Path | Schema | +| --- | --- | +| `[]` (the database root) | `public` -- the reserved name for the empty path | +| `["prod"]` | `prod` -- one component needs no joining | +| `["prod", "search"]` | `` `prod$search` `` -- joined, and backtick-quoted because `$` isn't a bare-identifier character | + +`$` can't appear in an ordinary name, so a schema can always be split back +into its exact path, unlike a dot-joined one. (This "schema" is the +namespace path as a SQL identifier -- distinct from a table's Arrow schema, +its column names and types.) + +### Object identifier {#identifier} + +An object -- a table, view, function, secret, or storage integration -- is +addressed in SQL by the ANSI three-part identifier `database.schema.name`, +where `schema` is exactly the `$`-joined path above. The `documents` table +in `search`, nested inside `prod`, in database `ai_data`, is +`` ai_data.`prod$search`.documents ``. One directly under the database root +uses `public`: `ai_data.public.documents`. + +See [Namespace](/sql/ddl/namespace) for the full `CREATE`/`ALTER`/`DROP` +syntax. ## Connecting {#connecting} You always run table and query operations within a **database**; cross-database operations go through SQL instead. The same Python, TypeScript and Rust SDKs -reach a database two ways: +reach a database and the catalog separately. -- **Directly, the common case.** `lancedb.connect(uri)` opens one database in a - single call -- a local directory, an object-storage path, or (with a `db://` - URI) a specific Enterprise database. -- **Through the catalog, for admin and cross-database work.** `connect_catalog(endpoint)` - connects to Enterprise's root catalog, which can list, create and drop - databases across the whole deployment. Its `connect_database(name)` and - `create_database(name)` then return the same kind of database connection - `lancedb.connect()` does. Local filesystem and object-store deployments have - no catalog to connect to -- each is already scoped to one database. +### Connecting to Catalog {#connecting-to-catalog} -The table below shows which URI reaches which kind of database directly. +`connect_catalog(endpoint)` connects to Enterprise's root catalog, which can +list, create and drop databases across the whole deployment. Its +`connect_database(name)` and `create_database(name)` then return the same +kind of database connection `lancedb.connect()` does. -| URI | Where queries run | -| --- | --- | -| A local path, such as `./data` | Embedded: in your process | -| `s3://`, `gs://` or `az://` | Embedded: in your process, reading object storage | -| `db://` | LanceDB Enterprise: queries run on your cluster | +This connection is for database administration, not table or query work: +list, create and drop databases through it, then switch to a **database** +connection for everything else -- tables, queries, and SQL all run within a +database, never directly against the catalog. Local filesystem and +object-store deployments have no catalog to connect to -- each is already +scoped to one database. -### A local directory {#local} +### Connecting to Database {#connecting-to-database} + +`lancedb.connect(uri)` opens one database in a single call -- a local +directory, an object-storage path, or (with a `db://` URI) a specific +Enterprise database. The table below shows which URI reaches which kind of +database directly. + +| URI | Mode | Where queries run | +| --- | --- | --- | +| A local path, such as `./data` | Embedded | In your process | +| `s3://`, `gs://` or `az://` | Embedded | In your process, reading object storage | +| `db://` | Enterprise | On your cluster | + +#### A local directory {#local} Embedded in your application, LanceDB reads and writes the tables in a directory on disk. @@ -75,12 +204,11 @@ directory on disk. -### Object storage {#object-storage} +#### Object storage {#object-storage} With an object storage URI the library is still embedded: your process runs -every query and reads and writes the bucket directly, with the credentials from -its environment or its storage options. [Configuring storage](/deployment/storage) -covers credentials, endpoints and provider options. +every query and reads and writes the bucket directly, with credentials from +its environment or its connection's `storage_options`. @@ -99,7 +227,85 @@ covers credentials, endpoints and provider options. In Rust, pass the same URI to `connect`. -### LanceDB Enterprise {#enterprise} +LanceDB supports these object storage backends: + +| Backend | URI scheme | Credentials | +| --- | --- | --- | +| AWS S3, and S3-compatible stores (MinIO, Tigris, ...) | `s3://` | `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`, or `storage_options`. Compatible stores also need `endpoint` and `region`. | +| Google Cloud Storage | `gs://` | `GOOGLE_SERVICE_ACCOUNT` (path to a service account JSON), or `storage_options` | +| Azure Blob Storage | `az://` | `AZURE_STORAGE_ACCOUNT_NAME` + `AZURE_STORAGE_ACCOUNT_KEY` (or a SAS token), or `storage_options` | +| Tencent COS | `cos://` | `TENCENTCLOUD_SECRET_ID` / `TENCENTCLOUD_SECRET_KEY`, or `storage_options` | +| GooseFS (a cache layer over COS or S3) | `goosefs://` | Reads from the GooseFS client environment | + +Pass credentials as environment variables (uppercase), or as a +`storage_options` dict at connection or table level (lowercase keys); a +table's `storage_options` inherit the connection's and override on a +per-key basis. + +Choosing among these is a tradeoff between latency, scalability, cost and +operational complexity, before you even pick a cloud-specific backend: +object storage (S3, GCS, Azure Blob) has the highest latency but is the +cheapest and scales storage effectively without limit; networked file +storage (EFS, Filestore, Azure Files) and third-party stores (MinIO, +WekaFS) sit in between; block storage (EBS, Persistent Disk, Managed Disk) +and local NVMe are the fastest but tie data to one instance, so scaling +means sharding or copying it yourself. + +##### S3-compatible stores {#s3-compatible-stores} + + + + {PyStorageS3Minio} + + + {TsStorageS3Minio} + + + +If the endpoint is `http://` (common in local development), also set +`ALLOW_HTTP=true` or pass `allow_http=True` in `storage_options`. + +##### S3 Express {#s3-express} + + + + {PyStorageS3Express} + + + {TsStorageS3Express} + + + +Consult AWS's networking requirements for S3 Express before enabling it. + +##### Server-side encryption with KMS {#server-side-encryption-with-kms} + +Set `aws_server_side_encryption` to `aws:kms` and `aws_sse_kms_key_id` to +the key ID or ARN to encrypt at rest with an AWS KMS key. The same options +apply at connection or table level, and combine with bucket-level default +encryption. + + + + {PyStorageS3SseKms} + + + {TsStorageS3SseKms} + + + +The IAM principal needs `kms:Encrypt`, `kms:Decrypt` and +`kms:GenerateDataKey` on the configured KMS key. + + +**Tencent COS and GooseFS build availability.** Both are bundled by +default in the Python wheel. In the Node binding, GooseFS is bundled by +default but COS is not -- build with the `cos` Cargo feature enabled to +use it there. In Rust, neither is in the default feature set; build with +the `cos` or `goosefs` Cargo feature enabled to use either one. + + +#### LanceDB Enterprise {#enterprise} A `db://` URI connects directly to one database in LanceDB Enterprise, where your cluster runs queries and background work. Get the database URI, API key, @@ -124,40 +330,6 @@ instead of an API key, see [Authentication](/enterprise/authentication); for every connection option, see [Database](/management/database#deployment). -## Databases, namespaces and tables {#objects} - -A database contains namespaces that group related tables and views. Namespaces -can also contain other namespaces, allowing teams to organize data by project, -environment or purpose. - -For example, a search application can keep production and staging data in -separate namespaces within the same database: - -```mermaid -flowchart TD - database["ai_data · database"] --> prod["prod · namespace"] - database --> staging["staging · namespace"] - prod --> prod_docs["documents · table"] - staging --> staging_docs["documents · table"] -``` - - - -| Object | What it represents | -| --- | --- | -| [Database](/management/database) | A container for namespaces and their data objects. | -| [Namespace](/management/namespace) | A named group of tables, views or nested namespaces. | -| [Table](/management/table) | Data stored as rows and columns. | -| [View](/management/view) | A saved query, evaluated when read. Available in Enterprise. | -| [Materialized view](/management/materialized-view) | The stored results of a query, updated by a refresh. Available in Enterprise. | - -{/* -Draft for the Functions release. Add this row to the table above: -| [Function](/management/function) | Registered code used to compute column values. Available in Enterprise. | -*/} - - - ## Organization and access control {#governance} - **Separate projects and environments.** Keep production and staging tables @@ -167,12 +339,13 @@ Draft for the Functions release. Add this row to the table above: - **Control access in Enterprise.** Use permissions on databases, namespaces and tables to manage who can access shared data and what they can do with it. - - ## Learn more {#next} +- [Catalog](/management/catalog): initial access to a new deployment, and the superuser bootstrap. - [Databases](/management/database): connect to and manage a database. - [Namespaces](/management/namespace): create groups and address tables within them. - [Tables](/management/table): create, inspect and manage your data. - [Views](/management/view) and [materialized views](/management/materialized-view): work with query-defined data. +- [Secrets](/management/secret): store a credential that a Function can bind by reference. +- [Storage integrations](/management/storage-integration): read or import from storage outside your own tables. - [Authorization](/governance/authorization): configure Enterprise access permissions. diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx new file mode 100644 index 000000000..a4e00040b --- /dev/null +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -0,0 +1,175 @@ +--- +title: "Embedded vs Enterprise" +sidebarTitle: "Embedded vs Enterprise" +description: "A feature-by-feature comparison between LanceDB Embedded and LanceDB Enterprise." +icon: "scale-balanced" +keywords: ["embedded vs enterprise", "comparison", "oss vs enterprise"] +--- + +LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. +[LanceDB Enterprise](/enterprise/index) distributes query execution, indexing, maintenance and refresh work across +a cluster of many machines, outside your application. Both are built on the same [Lance](/basics/lance) columnar +file format, so moving data from one edition to the other does not require a data conversion step. See +[Architecture](/index#architecture) for how each one's components fit together. + +## How they differ {#how-they-differ} + +| Dimension | LanceDB Embedded | LanceDB Enterprise | What the difference means | +|:----------|:------------|:-------------------|:-------------------------| +| **Mode** | Single process | Distributed fleet | LanceDB Embedded runs on one host, so scale is limited to what it can provide. Enterprise spreads work across nodes, adds capacity by adding nodes, and keeps serving even if one node fails. | +| **Query serving** | Uses the resources of your application process | Adds independently scaled query compute | Size the Enterprise cluster for your workload and latency target. See the expected-performance sections on [vector search](/search/vector-search#expected-performance) and [full-text search](/search/full-text-search#expected-performance) for representative measurements. | +| **Cache** | In-process index and metadata caches | Adds a distributed NVMe data cache | LanceDB Embedded caches indexes and metadata in your application's memory. Enterprise also keeps hot table data near compute on NVMe and avoids repeated S3 calls -- see the [Data Page Cache](/enterprise/data-page-cache). | +| **Indexing & compaction** | Manual | Platform-managed workflows | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/indexing/). | +| **Data format** | Lance | Lance | Both use the same open table format. Plan catalog registration, access and transfer when moving existing data. | +| **Deployment** | Embedded in your code | BYOC or Managed | Enterprise adds deployment operations and support for shared workloads. | +| **SQL analytics** | Not available | Arrow Flight SQL | Enterprise runs joins, grouping, sampling and [curation](/curation) over SQL. See [SQL reference](/sql). | +| **Native vector dedup** | Not available | `dedupe()` / `duplicate_pairs()` | Index-partition deduplication as a SQL table function, with no full pairwise scan. See [DEDUPE](/sql/dql/dedupe). | +| **Materialized views** | Not available | Server-side, distributed compute | Enterprise derives and refreshes a table from a query as a background job. See [Materialized views](/feature-engineering/materialized-views). | + +## Compare features {#compare} + +| Area | Feature | Embedded | Enterprise | +| --- | --- | :-: | :-: | +| **Data Ingestion** | [Insert data](/ingestion/insert) | ✅ | ✅ | +| | [RTE Write (Upsert)](/ingestion/realtime-write) | ✅ | ✅ | +| | [Distributed RTE Write](/enterprise/distributed-real-time-write) | ❌ | ✅ | +| | [Attach Database](/ingestion/migrate-from-embedded) | ❌ | ✅ | +| | [Import Datasets](/ingestion/import) | ❌ | ✅ | +| | [Distributed Write](/enterprise/distributed-write) | ❌ | ✅ | +| **Search** | [Vector search](/search/vector-search) | ✅ | ✅ | +| | [Full-text search](/search/full-text-search) | ✅ | ✅ | +| | [Hybrid search](/search/hybrid-search) | ✅ | ✅ | +| | [Filtering](/search/filtering) | ✅ | ✅ | +| | [Reranking](/reranking) | ✅ | ✅ | +| | [Distributed Search](/enterprise/distributed-search) | ❌ | ✅ | +| | [RTE Read](/search/realtime-read) | ✅ | ✅ | +| | [Distributed RTE Read](/enterprise/distributed-real-time-read) | ❌ | ✅ | +| | [Cache Prewarm](/enterprise/cache-prewarm) | ❌ | ✅ | +| **Data Curation** | [Inspect Datasets](/curation/inspect-datasets) | ❌ | ✅ | +| | [Statistical Sampling](/curation/statistical-sampling) | ❌ | ✅ | +| | [Selective Sampling](/curation/selective-sampling) | ✅ | ✅ | +| | [Aggregation and profiling](/curation/aggregate) | ❌ | ✅ | +| | [Joins](/curation/join) | ❌ | ✅ | +| | [Blob Late Materialization](/curation/blob-late-materialization) | ❌ | ✅ | +| | [Ranking](/curation/windowing) | ❌ | ✅ | +| | [Near-duplicate detection](/curation/dedupe) | ❌ | ✅ | +| | [Chunking](/curation/chunking) | ❌ | ✅ | +| | [Changes since a version](/curation/changes) | ❌ | ✅ | +| **Feature Engineering** | [Computed columns](/feature-engineering/add-computed-column) | ❌ | ✅ | +| | [Incremental Refresh](/enterprise/incremental-refresh) | ❌ | ✅ | +| | [Auto Refresh](/enterprise/auto-refresh) | ❌ | ✅ | +| | [Checkpointing](/enterprise/checkpointing) | ❌ | ✅ | +| | [Adaptive Execution](/enterprise/adaptive-execution) | ❌ | ✅ | +| | [Refresh Materialized View](/feature-engineering/refresh-materialized-view) | ❌ | ✅ | +| | [Embedding registry](/embedding) | ✅ | ✅ | +| **Training** | [PyTorch data loader](/training/data-loading) | ✅ | ✅ | +| | [Training Cache](/training/training-cache) | ❌ | ✅ | +| | [Permutations](/training/permutation) | ✅ | ✅ | +| | [Distributed training](/training/distributed-training) | ✅ | ✅ | +| | [Observability](/training/observability) | ✅ | ✅ | +| | [Checkpointing](/training/checkpointing) | ✅ | ✅ | +| | [Resuming](/training/resuming) | ✅ | ✅ | +| **Management** | [Catalog](/management/catalog) | ❌ | ✅ | +| | [Database](/management/database) | ✅ | ✅ | +| | [Namespace](/management/namespace) | ✅ | ✅ | +| | [Table](/management/table) | ✅ | ✅ | +| | [View](/management/view) | ❌ | ✅ | +| | [Materialized view](/management/materialized-view) | ❌ | ✅ | +| | [Secret](/management/secret) | ❌ | ✅ | +| | [Function](/management/function) | ❌ | ✅ | +| | [Storage integration](/management/storage-integration) | ❌ | ✅ | +| | [Console](/enterprise/console) | ❌ | ✅ | +| **Maintenance** | [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance) | ❌ | ✅ | +| | [Vector Indexing](/indexing/vector-index) | ✅ | ✅ | +| | [FTS Indexing](/indexing/fts-index) | ✅ | ✅ | +| | [Scalar Indexing](/indexing/scalar-index) | ✅ | ✅ | +| | [Incremental Indexing](/indexing/incremental-indexing) | ✅ | ✅ | +| | [Distributed Indexing](/enterprise/distributed-indexing) | ❌ | ✅ | +| | [GPU Indexing](/indexing/gpu-indexing) | ✅ | ✅ | +| | [Compaction](/maintenance/compaction) | ✅ | ✅ | +| | [RTE Compaction](/enterprise/realtime-engine-compaction) | ❌ | ✅ | +| | [Garbage Collection](/maintenance/cleanup) | ✅ | ✅ | +| | [Distributed Compaction](/enterprise/distributed-compaction) | ❌ | ✅ | +| | [Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution) | ❌ | ✅ | +| **Security** | [Authentication](/enterprise/authentication) | ❌ | ✅ | +| | [Authorization](/governance/authorization) | ❌ | ✅ | +| | [Audit Log](/governance/audit-log) | ❌ | ✅ | +| **Deployment** | [Horizontal Scaling](/enterprise/horizontal-scaling) | ❌ | ✅ | +| | [OpenTelemetry](/deployment/opentelemetry) | ✅ | ✅ | +| | [Kubernetes](/enterprise/deployment/kubernetes) | ❌ | ✅ | +| | [Multicloud](/deployment/multicloud) | ❌ | ✅ | +| | [Slurm](/deployment/slurm) | ❌ | ✅ | + +{/* +Draft until branching reaches early access; restore to the Management rows. +| | [Branches](/tables/branching) | ✅ | ✅ | +*/} + +## Usage differences between Enterprise and Embedded {#usage-differences-between-enterprise-and-oss} + +The [quickstart](/quickstart) guide shows both LanceDB Embedded connections and Enterprise `db://...` +connections. Once connected to LanceDB, the table API is largely the same: create a table, search, +filter, evolve the schema, and store multimodal records. However, there are some semantic differences +worth understanding when your code is talking to LanceDB Enterprise. + +### 1\. Connection model {#1-connection-model} + +In LanceDB Enterprise, your app connects via a `db://...` URI and sends requests to the cluster API. +The cluster executes table operations on your behalf. Your code is coupled to a **managed service endpoint**, +whereas LanceDB Embedded is directly coupled to local or object-storage paths. + +### 2\. Returned table type {#2-returned-table-type} + +Connecting to an Enterprise table via `open_table(...)` returns a `RemoteTable`, unlike LanceDB Embedded, +which returns a `LanceTable`. `RemoteTable` is a catalog-backed table accessed through a server/cluster, +and does not support all the same methods as `LanceTable` (see below). + +### 3\. Materialization APIs {#3-materialization-apis} + +For Python users working with LanceDB Enterprise, `RemoteTable` does not support table-level +materialization methods like `table.to_arrow()` or `table.to_pandas()`. This protects users from +accidentally materializing tables that are too large to fit in memory. + +Instead, materialize results through query/search builders, for example +`table.search(...).limit(...).to_pandas()` for a vector or full-text search, or +`table.search().where(...).limit(...).to_arrow()` for a filtered scan. For quick previews, use +`table.head()`. + +### 4\. Maintenance lifecycle {#4-maintenance-lifecycle} + +In LanceDB Embedded, you run maintenance yourself: `optimize()` compacts data files, adds new rows to +existing indexes, and removes old table versions. In Enterprise, the cluster runs this work -- along with +async write and reindexing workflows -- as background jobs, and the SDK's maintenance calls do not trigger +it. On an Enterprise table, the synchronous Python `optimize()`, `compact_files()`, and +`cleanup_old_versions()` only emit a warning, and the asynchronous Python, TypeScript, and Rust clients +reject `optimize()` as not supported. + +That means maintenance is managed by platform behavior and cluster configuration, not by explicit +per-table maintenance calls in your application code. + +### 5\. Guardrails and limits {#5-guardrails-and-limits} + +Enterprise can enforce platform-level guardrails, such as index/table limits and safety checks around +operations like `merge_insert` when too many rows are unindexed. LanceDB Embedded mostly exposes +storage/format-level behavior, and you tune many lifecycle tasks yourself. + +This means an operation in LanceDB Enterprise can fail due to service-level policy, not just because +of local table shape or schema mismatch. + + +As a rule of thumb, all you need to remember is this: treat `db://...` as a network service boundary, +use query builders to fetch results, and otherwise interact with your tables as you would in LanceDB +Embedded. + + +## Which one should I use? {#which-one-should-i-use} + +[It's very simple to get started with LanceDB Embedded](/quickstart/): Get started with `pip install lancedb` and begin ingesting +your data and vectors into LanceDB. LanceDB Embedded (open source) makes sense when your dataset fits on one machine, traffic is still +modest, and your team is comfortable handling maintenance tasks such as compaction or reindexing itself. + +Move to LanceDB Enterprise when retrieval becomes shared infrastructure for your business: your data or traffic has +outgrown a single machine, you need private deployment options, or you want platform support for monitoring, security, +and large-scale feature workflows. + +If these sound like your use cases, [reach out to us](https://www.lancedb.com/contact) and we can help you scope your workload and arrange an Enterprise proof of concept. diff --git a/docs/web/basics/guarantees.mdx b/docs/web/basics/guarantees.mdx index bdfe86286..85f71b9f1 100644 --- a/docs/web/basics/guarantees.mdx +++ b/docs/web/basics/guarantees.mdx @@ -85,7 +85,7 @@ cannot undo `drop_table`. - [Consistency](/tables/consistency): control when reads observe updates. - [Table versioning](/management/table#versioning): inspect and restore history. -- [Cleanup](/maintenance/cleanup): configure retention and understand protected versions. -- [Jobs](/basics/jobs): distinguish submission, completion and cancellation. +- [Garbage Collection](/maintenance/cleanup): configure retention and understand protected versions. +- [Job Framework](/basics/jobs): distinguish submission, completion and cancellation. - [Refresh a computed column](/feature-engineering/refresh-column): understand partial progress. - [Architecture](/index#architecture): understand storage and background maintenance. diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index a15f10fee..5336d1dfd 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -1,11 +1,11 @@ --- -title: "Jobs" -sidebarTitle: "Job" +title: "Job Framework" +sidebarTitle: "Job Framework" description: "Track background work from submission to completion." icon: hourglass-half keywords: ["job", "background", "progress", "events", "cancel"] availability: - embedded: available + embedded: unavailable enterprise: available --- @@ -23,13 +23,15 @@ so check its status before waiting or requesting cancellation. See the operation's API reference for when the method returns. -```python + +```python Python icon="python" job = tbl.create_index_async("vector", replace=True) print(job.id) print(job.job_type) print(job.status()) ``` + ## Submit and wait for a job {#waiting} @@ -41,14 +43,22 @@ print(job.status()) results it committed before stopping. In Python, `job.status()` reports the current state and `job.wait()` waits for -completion, raising if the job fails or is cancelled. If `job.wait()` times out, the client stops waiting. -The timeout does not cancel the server job. +completion, raising if the job fails or is cancelled. Both `Job.wait()` and +`AsyncJob.wait()` retry transient connection and read errors with capped +exponential backoff within the caller's timeout. Without a timeout, retries +continue indefinitely. -```python +If the timeout expires while disconnected, the wait raises `ConnectionError` +with the job ID and instructions to resume waiting. A timeout while connected +raises `TimeoutError`. The job may still be running; timing out does not cancel it. + + +```python Python icon="python" from datetime import timedelta from lancedb.exceptions import JobFailedError, JobCancelledError job = tbl.create_index_async("vector", replace=True) +job_id = job.id # Save the ID to reopen an Enterprise registry job later. try: result = job.wait(timeout=timedelta(minutes=10)) @@ -56,9 +66,23 @@ except JobFailedError: print(f"job failed: {job.failure}") except JobCancelledError: print("job was cancelled") +except ConnectionError as exc: + print(exc) # The job may still be running on the server. except TimeoutError: print(f"still running: {job.status()}") ``` + + +After connectivity returns, reopen an Enterprise registry job by its saved ID +and continue waiting on the existing operation: + +```python +job = db.open_job(job_id) +result = job.wait(timeout=timedelta(minutes=10)) +``` + +For SQL-backed jobs, call `wait()` again on the original handle. These jobs +cannot be reopened with `db.open_job()`; see [SQL-backed job handles](#sql-backed-job-handles). @@ -75,7 +99,8 @@ except TimeoutError: Reopening a job retrieves the existing operation; it does not restart failed work. Treat the ID as an opaque identifier and pass it unchanged to the jobs API. -```python + +```python Python icon="python" job = db.open_job(job_id) # raises JobNotFoundError if unknown job.refresh() # pull the latest status from the server print(job.status()) @@ -85,23 +110,113 @@ print(events.to_pylist()) job.cancel() ``` + List jobs on a connection, paging through the results: -```python + +```python Python icon="python" for info in db.list_jobs(page_limit=50): print(info.job_id, info.job_type, info.state) ``` + Event responses have [row limits](/basics/limits#jobs). An explicit limit can request more than the default, but it does not guarantee a complete event history. -## Embedded and Distributed execution {#in-process} +{/* +Draft for the Functions release. Add this section before "Embedded and +Enterprise execution": + +### Progress snapshots and observers + +Enterprise registry handles expose a structured progress snapshot. This +includes index and refresh handles returned directly by their async submission +methods, as well as handles reopened with `open_job()`. Call `progress()` for a +point-in-time snapshot, or pass a callback to `wait()` to observe the same +server polls that drive completion. The callback receives running and terminal +observations; it does not start another polling loop. It is a synchronous +observer and is not awaited. If it throws, `wait()` logs the error and continues +waiting; callback exceptions do not reject `wait()`. + +```python +def show_progress(progress): + print( + progress.get("state"), + progress.get("phase"), + progress.get("rows_computed"), + progress.get("rows_planned"), + ) + +job = tbl.refresh_column_async("embedding") +snapshot = job.progress() +if snapshot is not None: + show_progress(snapshot) + +result = job.wait(progress=show_progress) +``` + +```typescript +const showProgress = (progress: lancedb.JobProgress) => { + console.log( + progress.state, + progress.phase, + progress.rows_computed, + progress.rows_planned, + ); +}; + +const job = await tbl.refreshColumnAsync("embedding"); +const snapshot = await job.progress(); +if (snapshot !== null) { + showProgress(snapshot); +} + +await job.wait(showProgress); +``` + +```rust +let job = table.refresh_column_async("embedding").await?; +if let Some(progress) = job.progress().await? { + println!( + "state={:?} rows={:?}/{:?}", + progress.get("state"), + progress.get("rows_computed"), + progress.get("rows_planned"), + ); +} + +let result = job + .wait_with_progress(|description| { + let progress = description.progress_snapshot(); + println!( + "state={:?} rows={:?}/{:?}", + progress.get("state"), + progress.get("rows_computed"), + progress.get("rows_planned"), + ); + }) + .await?; +``` + +Job-type-specific counters are optional. A missing `rows_computed`, +`rows_planned`, or `rows_remaining` field means the server did not report that +counter; it does not mean zero, complete, or failed. Embedded handles and +SQL-backed query handles do not have registry progress records. Use their +`status()` and `wait()` APIs, and use registry progress only on handles backed +by the jobs API. + +`estimated_remaining_time_millis` is a best-effort client-side estimate. It is +omitted while a job is initializing, queued, or paused, and when there is no +positive progress rate from two compatible samples. +*/} + +## Embedded and Enterprise execution {#in-process} The following table describes LanceDB Embedded operations and registry jobs on -LanceDB Distributed (provided by LanceDB Enterprise). -SQL-backed job handles follow the query lifecycle described below. +LanceDB Enterprise. SQL-backed job handles follow the query lifecycle +described below. | | Embedded | Enterprise registry job | | --- | --- | --- | @@ -112,31 +227,37 @@ SQL-backed job handles follow the query lifecycle described below. ### SQL-backed job handles -On Enterprise, materialized-view CREATE, REFRESH, and DROP use the SQL query backend. -Python's `create_materialized_view_async()`, `mv.refresh_async()`, and -`drop_materialized_view_async()` return job handles with `status()`, `wait()`, -and `cancel()`. Synchronous creation, refresh, and drop wait on the same SQL -execution before returning. A completed DROP means the catalog binding has been -removed; physical cleanup continues in the background. +On Enterprise, several catalog operations return a job handle backed by the +SQL query engine rather than the job registry: -The existing `job.job_type` identifies query-backed handles as `"query"` from -submission, and `job.id` contains the connection-scoped SQL query UUID string. -Use `describe_query(job.id)` on the submitting connection to inspect the query. -Registry handles retain their server-reported job types (available after -`status()` or `refresh()`) and registry IDs. Local handles have no ID or job type. +| Operation | SDK methods | Behavior | +| --- | --- | --- | +| Materialized views | `create_materialized_view_async()`, `refresh_async()`, `drop_materialized_view_async()` | Synchronous variants wait on the same SQL execution. Drop removes the catalog binding immediately; physical cleanup continues in the background. | +| Functions | Registration, `drop_function_async()` | Registration waits for catalog publication before returning the immutable FunctionVersion. Drop confirms catalog removal while cleanup continues separately. | +| Secrets | Create, alter, list, describe, drop | Credential values are bound as SQL parameters, never embedded in SQL text or returned in results. `DESCRIBE SECRET` additionally exposes rotation history. | +| Views | Create, describe, list, drop | Create returns the stored definition and schema. Drop confirms catalog removal while cleanup continues separately. | -SQL-backed handles do not expose registry records or event history and cannot -be reopened through `open_job()` or reattached after a client restart. Their IDs -are not durable resume tokens. Cancellation follows the SQL server's -capabilities and can be unsupported. +All of these report `job.job_type` as `"query"`, with `job.id` holding the +connection-scoped SQL query UUID -- use `describe_query(job.id)` to inspect +one. Unlike registry handles, they don't expose event history, can't be +reopened through `open_job()` or reattached after a client restart, and +cancellation depends on the SQL server's support for it. -The server decides whether SQL executes on its serving fleet or starts SQL job -workers. That placement does not change the handle's query-backed identity. +### Object teardown {#teardown} + +The "physical cleanup continues in the background" behavior above, for a +dropped table, view, materialized view, Secret or Function, is a job type of +its own: `drop_object` deletes the dropped object's content, then clears it +from the database's cleanup backlog. You trigger it indirectly, by dropping +one of those objects or a [namespace](/management/namespace) -- it runs as +this job rather than inline with the call. Whether a dropped table runs as +`drop_object` or as [`drop_table`](/management/table#drop), which fences the +table's directory with its own marker instead, depends on how the deployment +stores its catalog. ## Learn more {#next} -- [Build and repair indexes](/indexing/reindexing): submit index work. +- [Incremental Indexing](/indexing/incremental-indexing): submit index work. - [Refresh a computed column](/feature-engineering/refresh-column): populate derived values. -- [Background jobs](/maintenance/background-jobs): understand Enterprise maintenance. - [SQL job commands](/sql/ddl/job): list jobs and inspect errors. - [SDKs](/basics/sdk): find the job API for your client. diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index 42d474de9..0341ee333 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -34,12 +34,45 @@ those fields together. - **Independent column updates.** Add embeddings or other derived features without rewriting the existing image, video or text columns. +## Opening Lance datasets in Python {#python-packages} + +Any `.lance` dataset directory is a LanceDB table. Pass the parent directory to +`lancedb.connect()` and open the table by its directory stem: + +```python +import lancedb + +db = lancedb.connect("/data") # pass storage_options=... for S3, GCS or Azure +tbl = db.open_table("frames") # opens /data/frames.lance; version=N pins a version +``` + +Use `lancedb` for search, retrieval, data curation, multimodal blob access and +application code. Install `pylance` (`import lance`) only when building query +engines or connectors, calling format-level fragment APIs directly, or +converting plain-scan lazy or legacy blob columns with `to_pandas()` (see +[Multimodal data and blobs](/management/table#multimodal) for `pylance`-free +conversions). + +| `pylance` (`import lance`) | `lancedb` (`import lancedb`) | +| --- | --- | +| `lance.dataset("/data/frames.lance")` | `lancedb.connect("/data").open_table("frames")` | +| `lance.write_dataset(data, "/data/frames.lance")` | `lancedb.connect("/data").create_table("frames", data)` | +| `lance.vector.vec_to_table(mat)` | `db.create_table(name, pa.table({"vector": list(mat)}))` | +| `lance.blob_field("video")` | `lancedb.blob("video")` | +| `ds.take_blobs("video", ids=row_ids)` | `tbl.fetch_blob_files("video", row_ids)` (seekable handles) or `tbl.fetch_blobs("video", row_ids)` (`pa.LargeBinaryArray`) | +| `ds.to_table(columns=cols, filter=expr, limit=n)` | `tbl.search().where(expr).select(cols).limit(n).to_arrow()` | +| `ds.to_batches(batch_size=k)` | `tbl.search().to_batches(k)` | +| `ds.take(offsets)` | `tbl.__getitems__(offsets)` (preserves offset order) or `tbl.take_offsets(offsets).to_arrow()` (unordered) | +| `ds.versions()`, `ds.checkout_version(v)`, `ds.restore()` | `tbl.list_versions()`, `tbl.checkout(v)`, `tbl.restore()` | +| `ds.optimize.compact_files(...)`, `ds.cleanup_old_versions(...)` | `tbl.optimize(compaction_options=..., cleanup_older_than=...)` | + ## Learn more {#next} - [Lance format specification](https://lance.org/format): how the format works. +- [Multimodal data and blobs](/management/table#multimodal): declare `lancedb.blob()` columns and read blobs on demand. - [Table versioning](/management/table#versioning): read and manage table versions. - [Computed columns](/feature-engineering/add-computed-column): add derived features to your data. - [Architecture](/index#architecture): how LanceDB Embedded and Enterprise build on Lance. diff --git a/docs/web/basics/lancedb-embedded.mdx b/docs/web/basics/lancedb-embedded.mdx new file mode 100644 index 000000000..cd9c11fff --- /dev/null +++ b/docs/web/basics/lancedb-embedded.mdx @@ -0,0 +1,46 @@ +--- +title: "LanceDB Embedded" +sidebarTitle: "LanceDB Embedded" +description: "The open-source, embedded retrieval library that runs inside your application process." +icon: cube +keywords: ["embedded", "open source", "oss", "local", "sdk", "lancedb embedded"] +--- + +**LanceDB Embedded** is an open-source, embedded retrieval library, with client SDKs in Python, TypeScript and +Rust -- the application itself plans queries, builds indexes, and runs background work, with no separate database +server to deploy. It reads and writes tables on local disk or in object storage from inside your application +process, on the same [Lance](/basics/lance) format and table model that [LanceDB Enterprise](/enterprise/index) +builds on. + + + LanceDB Embedded architecture + + +## Why use LanceDB Embedded? {#why-use-lancedb-embedded} + +LanceDB Embedded fits local retrieval applications, notebooks, development, and single-node data pipelines, where +your application controls its own compute resources and [table maintenance](/maintenance/compaction). + +- **No infrastructure to run** -- the library runs inside your process. There is no server to deploy, configure, + or keep available. +- **Free and open source** -- `pip install lancedb` (or the TypeScript or Rust equivalent) and start reading and + writing tables, with no account or service to set up first. +- **Full local control** -- your application decides where table data lives, when maintenance such as compaction + and indexing runs, and how much compute each operation gets. +- **The same table format as Enterprise** -- Embedded and [Enterprise](/enterprise/index) share the same Lance + format and table model, so moving to a distributed deployment later does not require a data conversion step. + +## Get started {#get-started} + + + + Create a table, add data, and run your first search in a few lines of code. + + + Pick between the Python, TypeScript, and Rust SDKs. + + + +When your data or traffic outgrows a single machine, or you need managed infrastructure, private deployment, or +platform support, see [LanceDB Enterprise](/enterprise/index) and the +[feature-by-feature comparison](/basics/embedded-vs-enterprise). diff --git a/docs/web/basics/limits.mdx b/docs/web/basics/limits.mdx index c4af28c45..a3d5cbb8c 100644 --- a/docs/web/basics/limits.mdx +++ b/docs/web/basics/limits.mdx @@ -65,7 +65,7 @@ before creating one over it. ## Learn more {#next} - [Naming Rules](/basics/naming): choose portable names and paths. -- [Jobs](/basics/jobs): track work and inspect events. +- [Job Framework](/basics/jobs): track work and inspect events. - [Full-text indexes](/indexing/fts-index): configure tokenization. - [SQL](/basics/sql) and [SDKs](/basics/sdk): check interface support. - [Enterprise support](/deployment/support): discuss deployment capacity. diff --git a/docs/web/basics/naming.mdx b/docs/web/basics/naming.mdx index b570e5bee..b00f50bf4 100644 --- a/docs/web/basics/naming.mdx +++ b/docs/web/basics/naming.mdx @@ -10,7 +10,7 @@ keywords: ["names", "naming", "table name", "namespace", "identifier", "limits"] -Databases, namespaces, tables, views and branches all have names. Choose names +Databases, namespaces, tables and views all have names.{/* Draft until branching reaches early access: restore "Databases, namespaces, tables, views and branches all have names." */} Choose names that describe their purpose, such as `documents`, `prod` or `training_2026`. Consistent names make data easier to find and application code easier to read. @@ -21,21 +21,20 @@ Use the following rules for names that work across LanceDB Embedded and LanceDB | Table, materialized view, view | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters | | Namespace component | ASCII letters and digits, `-`, `_`, `.` | 1 to 64 characters; at most 10 components in a path | | Database | ASCII letters and digits, `-`, `_`, `.`, with `/` between components | 1 to 64 characters for the whole name | +| Secret | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters | +| Function | ASCII letters and digits, `_` | 1 to 128 characters | + +{/* +Draft until branching reaches early access; restore after the Database row. | Branch | Avoid `$` and `:`; use ASCII letters, digits, `-` and `_` for portability | Keep to 1 to 64 characters | +*/} - Names and individual namespace or database components must not be empty. - Table, view, namespace and database components cannot be `.` or `..`. +- Secret names cannot be `.` or `..`. - Avoid `$` and `:` because they separate parts of qualified identifiers. - A namespace path beginning with `public` cannot contain another component. -{/* -Draft for the Functions release. Add these rows to the end of the table above: -| Secret | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters | -| Function | ASCII letters and digits, `_` | 1 to 128 characters | -Add this item to the list above, after the rule for `.` and `..`: -- Secret names cannot be `.` or `..`. -*/} - ## Namespace paths {#paths} A namespace path is a list of names. `["prod", "search"]` identifies the @@ -65,5 +64,9 @@ The empty path `[]` identifies the root namespace. ## Learn more {#next} - [Namespaces](/management/namespace): create namespaces and address tables. -- [Branches](/tables/branching): name and manage separate lines of table history. - [Limits](/basics/limits): check other constraints before designing your schema. + +{/* +Draft until branching reaches early access; restore after Namespaces. +- [Branches](/tables/branching): name and manage separate lines of table history. +*/} diff --git a/docs/web/basics/sdk.mdx b/docs/web/basics/sdk.mdx index 1d9312f77..2ff1a4ba7 100644 --- a/docs/web/basics/sdk.mdx +++ b/docs/web/basics/sdk.mdx @@ -3,15 +3,15 @@ title: "SDKs" sidebarTitle: "SDKs" description: "Choose a LanceDB SDK and find the API reference for your language." icon: code-compare -keywords: ["python", "typescript", "rust", "java", "sdk", "rest", "api reference"] +keywords: ["python", "typescript", "rust", "java", "sdk", "api reference"] --- Use a LanceDB SDK to create tables, add data, build indexes and run searches from your application. Python, TypeScript and Rust work with both LanceDB Embedded and LanceDB Enterprise. LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. LanceDB -Enterprise runs LanceDB Distributed: query execution, indexing and maintenance -run on the Enterprise service, outside your application. +Enterprise distributes query execution, indexing, maintenance and refresh +work across the service, outside your application. The [quickstart](/quickstart) includes installation instructions and complete examples in all three languages. For connection settings, see @@ -36,16 +36,13 @@ provide a SQL execution method. ## Lance Namespace SDKs {#lance-namespace-sdks} -LanceDB Enterprise's catalog and table operations follow -[Lance Namespace](https://lance.org/format/namespace), an open specification -for describing access to tables in a multimodal lakehouse, including its REST -Namespace Spec. LanceDB Enterprise exposes this as an HTTP API for catalog and -table operations -- the [REST API reference](/api-reference/rest) describes -its endpoints and request formats. Use it when integrating a language or tool -without a LanceDB SDK; for SQL queries, connect through -[Flight SQL](/basics/sql) instead. Any client that implements a Lance -Namespace REST client can integrate with LanceDB this way, not only the -official SDKs above. +LanceDB Enterprise's catalog and table operations follow the +[Lance Namespace Client SDK Specification](https://lance.org/format/namespace), +an open specification for describing access to tables in a multimodal +lakehouse. Any client that implements it can integrate with LanceDB this +way, not only the official SDKs above -- useful for a language or tool +without a LanceDB SDK. For SQL queries, connect through +[Flight SQL](/basics/sql) instead. | Language | Package | Used by | | --- | --- | --- | @@ -55,13 +52,13 @@ official SDKs above. LanceDB's Java client builds on this Lance Namespace Java core: table creation, listing and most other catalog operations go through the generated -`LanceNamespace` interface talking to Enterprise's REST Namespace endpoint. +`LanceNamespace` interface talking to Enterprise's Namespace endpoint. The [real time engine](/tables/realtime-engine) is the one area with its own, LanceDB-specific Java client on top, since RTE's LSM write path is not part of -the Lance Namespace specification. +the Lance Namespace Client SDK Specification. See [lance.org/format/namespace](https://lance.org/format/namespace) for the -full spec and its other catalog implementations (Directory, Apache Polaris, +full specification and its other catalog implementations (Directory, Apache Polaris, Unity Catalog, Apache Hive Metastore, Apache Iceberg REST Catalog, and more). ## Community SDKs {#community-sdks} diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index bb4f2cd4a..31e3af1f3 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -3,33 +3,85 @@ title: "SQL" sidebarTitle: "SQL" description: "Query LanceDB Enterprise with SQL from Python or an Arrow Flight SQL client." icon: table-list -keywords: ["sql", "flight sql", "datafusion", "reference", "dialect"] +keywords: ["sql", "flight sql", "datafusion", "reference", "dialect", "query plan", "explain"] --- +import { PyQueryPlan, TsQueryPlanBody, TsQueryPlanTail } from '/snippets/search_examples.mdx'; +import { RsExampleBody as RsQueryPlanBody, RsExampleTail as RsQueryPlanTail } from '/snippets/search_query_plan.mdx'; + Use SQL in LanceDB Enterprise to filter records, join tables, calculate aggregates, and prepare datasets. SQL queries work with the same Lance tables you create and update through the SDKs, without exporting the data to another system. -This guide covers the two ways to run SQL, connection settings, a first query, +This guide starts with when to reach for SQL instead of SDK table operations, +then covers the three ways to run SQL, connection settings, a first query, parameterized queries, and how to read and manage the results. +## Choose SQL or SDK table operations {#choosing} + +An SDK gives you a programming-language-specific API for invoking LanceDB's +functionality: create a table, insert rows, build an index, run a vector +search, each its own method call. Every one of those functionalities also +has a corresponding SQL operation. SQL covers a wider surface than any one +SDK method and lets you chain operations together in a single statement -- +running a vector search and then joining the results with another table, +for example -- where SDK methods stay separate calls. + +Use **SQL** for joins, aggregations, window functions, analytical queries, +and whenever you want to chain operations together. Use **SDK table +operations** to build applications around table management, ingestion, +filtering, and search, including applications that run with LanceDB +Embedded, where SQL is not available. + +You can combine them. For example, create and populate a table with an SDK, +then query it with SQL to prepare a training dataset. In Python, both +workflows can use the same Enterprise connection. + +Both interfaces work with the same Lance tables, through the same Arrow +schema. Applications in different languages can work with the same tables: +connect to the same database and namespace, use the appropriate credentials, +and account for [read consistency](/tables/consistency) when another process +writes data. A fixed-size vector column stores vectors of a consistent +dimension; see the [data types reference](/sql/data-types) for the supported +element types and other column types. + +### Common SQL operations {#sdk-parity} + +Several tasks are available through both interfaces, but the methods and SQL +statements do not have identical coverage. SDK support also differs by +language. These SQL reference pages describe the supported statements: + +| Task | SQL reference | +| --- | --- | +| Create a table | [CREATE TABLE](/sql/ddl/table) | +| Insert or change rows | [INSERT](/sql/dml/insert), [UPDATE](/sql/dml/update), [DELETE](/sql/dml/delete) | +| Build an index | [CREATE INDEX](/sql/ddl/index) | +| Join and aggregate data | [SELECT](/sql/dql/select) | +| Save a query as a view | [CREATE VIEW](/sql/ddl/view) | + +[Computed columns](/feature-engineering/add-computed-column) store SQL +expressions whose values are populated by a refresh. They are separate +from registered Python Functions. See the computed-column and +[materialized-view](/management/materialized-view) guides for their SDK and SQL +operations and Enterprise setup requirements. + ## Access LanceDB with SQL {#access} -There are two ways to run SQL against LanceDB Enterprise, both against the +There are three ways to run SQL against LanceDB Enterprise, all against the same [Arrow Flight SQL](https://arrow.apache.org/docs/format/FlightSql.html) endpoint, returning results as Arrow record batches: 1. **`db.execute_query()`** on the Python SDK's Enterprise connection, shown - below. This is LanceDB's native SQL execution method, and we recommend it + below, or **`Connection::execute_query_async()`** on the Rust SDK's. These + are LanceDB's native SQL execution methods, and we recommend them for the best performance -- see [Adaptive query execution](#adaptive). -2. **An Arrow Flight SQL client.** Use this from TypeScript and other - languages, whose LanceDB SDKs do not expose a SQL execution method, or from - any tool with its own Flight SQL integration. A LanceDB-specific SDK is not - required to submit SQL. - -From the command line, use `lancedb` to open the [SQL shell](/tools/cli) -or execute a statement or file. +2. **An Arrow Flight SQL client.** Use this from TypeScript, whose LanceDB SDK + does not expose a SQL execution method, or from any tool with its own + Flight SQL integration. A LanceDB-specific SDK is not required to submit + SQL. +3. **The LanceDB CLI.** Open an interactive SQL shell, or run a + statement or file, directly from the command line with no code at all. The [SQL reference](/sql#connecting) shows a query from Python. See [SDKs](/basics/sdk) for the LanceDB language clients. @@ -78,8 +130,6 @@ This example reads an existing `frames` table, with a `video_id` and a ```python Python icon="python" -import lancedb - db = lancedb.connect( "db://your-database", api_key="your-api-key", @@ -109,7 +159,8 @@ separately, use `execute_query_async()`. Pass a `parameters` argument to bind values into a query, instead of formatting them into the SQL string: -```python + +```python Python icon="python" import numpy as np reader = db.execute_query( @@ -117,6 +168,7 @@ reader = db.execute_query( parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10], ) ``` + Values travel as Arrow, not interpolated SQL text, so a vector binds as a fixed-size list with no manual formatting and no injection risk. Reference a @@ -132,12 +184,47 @@ binding: `parameters` is a LanceDB-specific mechanism, separate from the Flight SQL -protocol's `PREPARE`/bind step, which -[a deployment does not implement](/sql/prepared-statements#parameters). Bind -values with `parameters` from the Python SDK; a generic Flight SQL client has -no equivalent. +protocol's `PREPARE`/bind step, which a deployment does not implement; see +[Prepared statements](#prepared-statements) below. Bind values with +`parameters` from the Python SDK; a generic Flight SQL client has no +equivalent. +## Prepared statements {#prepared-statements} + +A Flight SQL client can prepare a statement before it runs it. A deployment +accepts that, but it keeps no plan between runs and does not accept the +parameter values described above at this protocol layer. + + +There is no SQL `PREPARE` / `EXECUTE` here. Preparation is part of the +**Arrow Flight SQL protocol**, so you reach it through your client rather than +by sending a statement. A script containing `PREPARE name AS SELECT ...` will +not run. + + +A Flight SQL client takes these steps, whatever it calls them: + +1. **Prepare:** send the SQL and get back a handle and the result schema. The + statement is parsed and planned at this point, so a syntax or name error + surfaces here rather than at execution. +2. **Execute:** run the handle and read the result. The deployment plans the + statement again each time it runs, so reusing a handle does not save + planning time. +3. **Close:** release the handle. + +A client that binds values to placeholders such as `$1` and `$2` at this +protocol layer gets a "not implemented" error when it executes the +statement. Use `parameters` [above](#parameters) instead; do not put +untrusted input directly into prepared statement text, since quoting it does +not protect the statement the way binding a parameter would. + +Prepare a statement when your client requires it, or to get a statement's +result schema and catch syntax and name errors without running it. Preparing +does not make a repeated statement faster. To give a reusable query a name, +create a [view](/management/view). To store its result for later queries, +create a [materialized view](/management/materialized-view). + ## Read and manage results {#results} - **Collect the results** when you want a list, Arrow table or DataFrame that @@ -160,45 +247,545 @@ cancellation. Background operations such as index builds return a [job](/basics/jobs) handle instead. Use the API for the returned handle to check status and retrieve results. -## Choose SQL or SDK table operations {#choosing} +## Query plans {#query-plans} -Use **SQL** for joins, aggregations, window functions, and analytical queries -written in SQL. Use **SDK table operations** to build applications around table -management, ingestion, filtering, and search, including applications that run -with LanceDB Embedded. +Use query plans to understand how LanceDB reads data, applies filters and uses +indexes. `explain_plan()` shows the planned operations. `analyze_plan()` runs +the query and adds measurements, including execution time and rows processed. -You can combine them. For example, create and populate a table with an SDK, -then query it with SQL to prepare a training dataset. In Python, both workflows -can use the same Enterprise connection. +### Inspect a plan or measure execution {#inspect-a-query-plan} -Both interfaces work with the same Lance tables, through the same Arrow -schema. Applications in different languages can work with the same tables: -connect to the same database and namespace, use the appropriate credentials, -and account for [read consistency](/tables/consistency) when another process -writes data. A fixed-size vector column stores vectors of a consistent -dimension; see the [data types reference](/sql/data-types) for the supported -element types and other column types. +| Operation | Python / Rust | TypeScript | +|:----------|:--------------|:-----------| +| Inspect the plan without executing the query | `explain_plan()` | `explainPlan()` | +| Execute the query and report runtime measurements | `analyze_plan()` | `analyzePlan()` | -### Common SQL operations {#sdk-parity} +Use the first to inspect query structure and the second to investigate work +actually performed. Operator names and available measurements can differ +between LanceDB Embedded and LanceDB Enterprise. SQL provides [EXPLAIN and EXPLAIN ANALYZE](/sql/dql/explain). -Several tasks are available through both interfaces, but the methods and SQL -statements do not have identical coverage. SDK support also differs by -language. These SQL reference pages describe the supported statements: + -| Task | SQL reference | -| --- | --- | -| Create a table | [CREATE TABLE](/sql/ddl/table) | -| Insert or change rows | [INSERT](/sql/dml/insert), [UPDATE](/sql/dml/update), [DELETE](/sql/dml/delete) | -| Build an index | [CREATE INDEX](/sql/ddl/index) | -| Join and aggregate data | [SELECT](/sql/dql/select) | -| Save a query as a view | [CREATE VIEW](/sql/ddl/view) | + -[Computed columns](/feature-engineering/add-computed-column) store SQL -expressions whose values are populated by a refresh. {/* Draft for the Functions release: -They are separate from registered Python Functions. */} -See the computed-column and -[materialized-view](/management/materialized-view) guides for their SDK and SQL -operations and Enterprise setup requirements. +These examples use three sample records and hand-written vectors, so no +embedding service is needed. Each program creates a temporary local table +and removes it when finished. + +- **Python:** Install with `pip install lancedb`, save as `query_plan.py`, then run `python query_plan.py`. +- **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `query_plan.mts`, then run `node query_plan.mts` with Node.js 22.18 or later. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin query_plan` from the extracted directory. + + + +{PyQueryPlan} + + +{TsQueryPlanBody + "\n" + TsQueryPlanTail} + + +{RsQueryPlanBody + "\n" + RsQueryPlanTail} + + + +This tiny table demonstrates the API, not a performance benchmark. The plan +uses a scan because the example has no vector index. The following larger +example illustrates how to read scans, filters and index operations. + + + +### Read scans, filters and result retrieval {#reading-the-execution-plan} + +The recorded example below uses 1.2 million rows sampled from the +[Wikipedia dataset](https://huggingface.co/datasets/wikimedia/wikipedia). +The counts describe that run. The table initially has no indexes, so the plan +shows a scan. This Enterprise plan includes `RemoteTake` and hides storage paths +as `uri=***`. A local plan shows the dataset path instead, and fetches the result +rows with Lance's `Take` or, depending on the library version, a second +`LanceRead` whose `source` is `stream(_rowid)`. + +Let's examine a vector search query that: + +- Filters rows where `identifier` is between 0 and 1,000,000 +- Returns the top 100 matches +- Projects specific columns: `chunk_index`, `title`, and `identifier` + + +```python Python icon="python" +# explain_plan +query_explain_plan = ( + table.search(query_embed) + .where("identifier > 0 AND identifier < 1000000") + .select(["chunk_index", "title", "identifier"]) + .limit(100) + .explain_plan(True) +) +``` + +```typescript TypeScript icon="square-js" +// explain_plan +const explainPlan = await table + .search(queryEmbed) + .where("identifier > 0 AND identifier < 1000000") + .select(["chunk_index", "title", "identifier"]) + .limit(100) + .explainPlan(true); +``` + + +#### Execution Plan Components {#execution-plan-components} + + + + +The execution plan reveals the sequence of operations performed to execute your query. Let's examine each component: + +``` +ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance] + RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title" + CoalesceBatchesExec: target_batch_size=1024 + GlobalLimitExec: skip=0, fetch=100 + FilterExec: _distance@3 IS NOT NULL + SortExec: TopK(fetch=100), expr=[_distance@3 ASC NULLS LAST], preserve_partitioning=[false] + KNNVectorDistance: metric=l2 + FilterExec: identifier@1 > 0 AND identifier@1 < 1000000 + LanceScan: uri=***, projection=[vector, identifier], row_id=true, row_addr=false, ordered=false +``` + +##### 1\. Base Layer (LanceScan) {#1-base-layer-lancescan} + +- Initial data scan loading only specified columns to minimize I/O +- Unordered scan enabling parallel processing + +``` +LanceScan: +- projection=[vector, identifier] +- row_id=true, row_addr=false, ordered=false +``` + +##### 2\. First Filter {#2-first-filter} + +- Apply requested filter on `identifier` column +- Reduces the number of vectors that need KNN computation + +``` +FilterExec: identifier@1 > 0 AND identifier@1 < 1000000 +``` + +##### 3\. Vector Search {#3-vector-search} + +- Computes squared L2 distances between query vector and all vectors that passed the filter + +``` +KNNVectorDistance: metric=l2 +``` + +##### 4\. Results Processing {#4-results-processing} + +- Filters out null distance results +- Sorts by distance and takes top 100 results +- Coalesces output into batches targeting 1,024 rows in this plan + +``` +SortExec: TopK(fetch=100) +- expr=[_distance@3 ASC NULLS LAST] +- preserve_partitioning=[false] +FilterExec: _distance@3 IS NOT NULL +GlobalLimitExec: skip=0, fetch=100 +CoalesceBatchesExec: target_batch_size=1024 +``` + +##### 5\. Data Retrieval {#5-data-retrieval} + +- `RemoteTake` is the deployment's operator for this step; a LanceDB Embedded plan shows Lance's `Take` or a `LanceRead` over the selected row IDs, depending on the library version +- Handles efficient data retrieval from remote storage locations +- Fetches specific rows and columns needed for the final output +- Optimizes network bandwidth by only retrieving required data + +``` +RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title" +``` + +##### 6\. Final Output {#6-final-output} + +- Returns only requested columns and maintains column ordering + +```text +ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance] +``` + +This plan demonstrates a basic search without index optimizations: it performs a full scan and filter before vector search. + + + + +### Non-vector queries {#analyzing-non-vector-queries} + +Query plans also cover filters and full-text search. Python can show both +sub-plans of a hybrid query. Check where a filter runs and how many rows flow +through each operator; a separate `FilterExec` does not by itself establish +that the plan is inefficient or that an index is missing. + +#### FTS queries {#fts-queries} + + +```python Python icon="python" +plan = ( + table.search("puppy", query_type="fts") + .where("category = 'animals'", prefilter=True) + .limit(10) + .explain_plan(True) +) +print(plan) +``` + +```typescript TypeScript icon="square-js" +const plan = await table + .query() + .fullTextSearch("puppy") + .where("category = 'animals'") + .limit(10) + .explainPlan(true); +``` + + +Look for the text-index operation and any scan of unindexed rows. A scan can +be needed to include records written after the index was built. Use index +coverage and execution measurements to determine whether that extra work +matters. Check filter placement separately from text-index use. + +#### Hybrid queries {#hybrid-queries} + +For hybrid queries, `explain_plan` returns the reranker label followed by the vector and FTS sub-plans, indented for readability: + + +```python Python icon="python" +plan = ( + table.search("flower moon", query_type="hybrid") + .where("category = 'film'", prefilter=True) + .limit(10) + .explain_plan(True) +) +print(plan) +# RRFReranker(...) +# +# +``` + + +`analyze_plan` executes both sub-queries and labels them `Vector Search Plan:` +and `FTS Search Plan:`. Compare their filter placement and execution measurements. + +`analyze_plan` executes the query and returns the physical plan annotated with +runtime metrics such as elapsed time, rows produced, bytes read and index comparisons. +Where [`explain_plan`](#inspect-a-query-plan) tells you what a query intends to do, +analysis shows the work performed. + + +The SQL equivalent is [`EXPLAIN ANALYZE`](/sql/dql/explain). + + +### Read execution measurements {#analyze-a-query-plan} + +Executes the query and provides detailed runtime metrics, including: + +- Operation duration (`_elapsed_compute_`) +- Data processing statistics (`_output_rows_`, `_bytes_read_`) +- Index effectiveness (`_index_comparisons_`, `_indices_loaded_`) +- Resource utilization (`_iops_`, `_requests_`) + +### Measure the example query {#performance-analysis} + +Let's use `analyze_plan` to run the query and analyze the query performance, which will help us identify potential bottlenecks: + + +```python Python icon="python" +# analyze_plan +query_analyze_plan = ( + table.search(query_embed) + .where("identifier > 0 AND identifier < 1000000") + .select(["chunk_index", "title", "identifier"]) + .limit(100) + .analyze_plan() +) +``` + +```typescript TypeScript icon="square-js" +// analyze_plan +const analyzePlan = await table + .search(queryEmbed) + .where("identifier > 0 AND identifier < 1000000") + .select(["chunk_index", "title", "identifier"]) + .limit(100) + .analyzePlan(); +``` + + +#### Performance Metrics Analysis {#performance-metrics-analysis} + + + + +``` +ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance], metrics=[output_rows=100, elapsed_compute=1.424µs] + RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title", metrics=[output_rows=100, elapsed_compute=175.53097ms, output_batches=1, remote_takes=100] + CoalesceBatchesExec: target_batch_size=1024, metrics=[output_rows=100, elapsed_compute=2.748µs] + GlobalLimitExec: skip=0, fetch=100, metrics=[output_rows=100, elapsed_compute=1.819µs] + FilterExec: _distance@3 IS NOT NULL, metrics=[output_rows=100, elapsed_compute=10.275µs] + SortExec: TopK(fetch=100), expr=[_distance@3 ASC NULLS LAST], preserve_partitioning=[false], metrics=[output_rows=100, elapsed_compute=39.259451ms, row_replacements=546] + KNNVectorDistance: metric=l2, metrics=[output_rows=1099508, elapsed_compute=56.783526ms, output_batches=1076] + FilterExec: identifier@1 > 0 AND identifier@1 < 1000000, metrics=[output_rows=1099508, elapsed_compute=17.136819ms] + LanceScan: uri=***, projection=[vector, identifier], row_id=true, row_addr=false, ordered=false, metrics=[output_rows=1200000, elapsed_compute=21.348178ms, bytes_read=1852931072, iops=78, requests=78] +``` + +##### 1\. Data Loading (LanceScan) {#1-data-loading-lancescan} + +- Scanned 1,200,000 rows from the LanceDB table +- Read 1.86GB of data in 78 I/O operations +- Only loaded necessary columns (`vector` and `identifier`) +- Unordered scan for parallel processing + +##### 2\. Filtering and Search {#2-filtering-and-search} + +- Applied prefilter condition (`identifier > 0 AND identifier < 1000000`) +- Reduced dataset from 1.2M to 1,099,508 rows +- KNN search used L2 (Euclidean) distance metric +- Vector comparisons processed in 1076 batches + +##### 3\. Results Processing {#3-results-processing} + +- KNN results sorted by distance (TopK with fetch=100) +- Null distances filtered out +- Batches coalesced to target size of 1024 rows +- Additional columns fetched for final results +- Remote take operation for 100 results +- Final projection of required columns + + + + +#### Distributed metrics on LanceDB Enterprise {#distributed-metrics-on-remote-tables} + +Enterprise + +When you call `analyze_plan` against a LanceDB Enterprise deployment that distributes its queries across a pool of workers, the query runs on those workers. By default the returned plan aggregates each operator's metrics into a single value, matching the single-node output of LanceDB Embedded. Pass a `distributed_metrics` mode when you need to see how work was split across workers: + +| Mode | What it shows | When to use it | +| :------------ | :----------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | +| `aggregate` | One summary value per operator (default). Same shape as Embedded `analyze_plan`. | Everyday performance checks and comparisons against an Embedded plan. | +| `per_worker` | Metrics reported separately for each worker that participated in the query. | Diagnosing stragglers or uneven work distribution across the cluster. | +| `full` | Both the aggregate summary and the per-worker breakdown. | Deep investigations where you need the totals *and* the per-worker detail in a single output. | + +Python exposes this option through `distributed_metrics`. In TypeScript, pass +the same mode to `analyzePlan()` as its `distributedMetrics` argument. Python +queries on LanceDB Embedded ignore the distributed mode and return single-node +measurements. + + +```python Python icon="python" +# Show a per-worker breakdown for a query on LanceDB Enterprise +plan = ( + table.search(query_embed) + .where("identifier > 0 AND identifier < 1000000") + .limit(100) + .analyze_plan(distributed_metrics="per_worker") +) +print(plan) +``` + + + + + +Use `per_worker` or `full` sparingly; the plan output grows with the size of your worker pool. Stick with the default `aggregate` mode for routine tuning. + + +#### Identify expensive operations {#key-observations} + +- The query computes distances for 1,099,508 vectors; inspect timings to assess its contribution to latency +- The scan reads 1.86 GB in this recorded run +- Full table scan due to lack of indices +- Compare this scan with an indexed plan using the same query + +### Compare the query after adding indexes {#optimized-query-execution} + + + + +The recorded query after adding vector and scalar indexes produced this plan: + +``` +ProjectionExec: expr=[chunk_index@3 as chunk_index, title@4 as title, identifier@2 as identifier, _distance@0 as _distance] + RemoteTake: columns="_distance, _rowid, identifier, chunk_index, title" + CoalesceBatchesExec: target_batch_size=1024 + GlobalLimitExec: skip=0, fetch=100 + SortExec: TopK(fetch=100), expr=[_distance@0 ASC NULLS LAST], preserve_partitioning=[false] + ANNSubIndex: name=vector_idx, k=100, deltas=1 + ANNIvfPartition: uuid=83916fd5-fc45-4977-bad9-1f0737539bb9, nprobes=20, deltas=1 + ScalarIndexQuery: query=AND(identifier > 0,identifier < 1000000) +``` + +#### Optimized Plan Analysis {#optimized-plan-analysis} + +##### 1\. Scalar Index Query {#1-scalar-index-query} + +``` +ScalarIndexQuery: query=AND(identifier > 0,identifier < 1000000) +metrics=[ + output_rows=2 + index_comparisons=2,301,824 + indices_loaded=2 + output_batches=1 + parts_loaded=562 + elapsed_compute=86.979354ms +] +``` + +- Range filter using scalar index +- Only 2 index files and 562 scalar index parts loaded +- 2.3M index comparisons for matches + +##### 2\. Vector Search {#2-vector-search} + +``` +ANNSubIndex: name=vector_idx, k=100, deltas=1 +metrics=[ + output_rows=2,000 + index_comparisons=25,893 + indices_loaded=0 + output_batches=20 + parts_loaded=20 + elapsed_compute=111.849043ms +] +``` + +- IVF index with 20 probes +- Only 20 index parts loaded +- 25,893 vector comparisons +- 2,000 matching vectors + +##### 3\. Results Processing {#3-results-processing-2} + +``` +SortExec: TopK(fetch=100), expr=[_distance@0 ASC NULLS LAST], preserve_partitioning=[false] +GlobalLimitExec: skip=0, fetch=100 +CoalesceBatchesExec: target_batch_size=1024 +``` + +- Sorts by distance +- Limits to top 100 results +- Batches into groups of 1024 + +##### 4\. Data Fetching {#4-data-fetching} + +``` +RemoteTake: columns="_distance, _rowid, identifier, chunk_index, title" +metrics=[output_rows=100, elapsed_compute=113.491859ms, output_batches=1, remote_takes=100] +``` + +- Single output batch +- One remote take per row + +##### 5\. Final Projection {#5-final-projection} + +``` +ProjectionExec: expr=[chunk_index@3 as chunk_index, title@4 as title, identifier@2 as identifier, _distance@0 as _distance] +``` + +- Returns specified columns: chunk_index, title, identifier, and distance + +#### Performance Improvements {#performance-improvements} + +##### 1\. Initial Data Access {#1-initial-data-access} + +``` +ScalarIndexQuery metrics: +- indices_loaded=2 +- parts_loaded=562 +- output_batches=1 +``` + +- Before: Full table scan of 1.2M rows, 1.86GB data +- After: Only 2 indices and 562 scalar index parts loaded +- Benefit: Eliminated table scans for prefilter + +##### 2\. Vector Search Efficiency {#2-vector-search-efficiency} + +``` +ANNSubIndex: +- index_comparisons=25,893 +- indices_loaded=0 +- parts_loaded=20 +- output_batches=20 +``` + +- Before: L2 calculations on 1,099,508 vectors +- After: + - About 97.6% fewer vector comparisons (25,893 versus 1,099,508) + - Decreased output batches from 1,076 to 20 + +##### 3\. Data Retrieval Optimization {#3-data-retrieval-optimization} + +``` +RemoteTake: +- remote_takes=100 +- output_batches=1 +``` + +- RemoteTake operation remains consistent + + + + +### Choose a change to measure {#performance-optimization-guide} + +#### 1\. Index Implementation {#1-index-implementation} + +##### When to Create Indices {#when-to-create-indices} + +- Columns used in WHERE clauses +- Vector columns for similarity searches +- Join columns used in `merge_insert` + +##### Index Type Selection {#index-type-selection} + +| Data Type | Recommended Index | Use Case | +| ----------- | ------------------ | ---------------------------------------- | +| Vector | IVF_PQ/IVF_HNSW_SQ/IVF_HNSW_FLAT | Approximate nearest neighbor search | +| Scalar | B-Tree | Equality and range filters | +| Categorical | Bitmap | Multi-value filters and set operations | +| `List` | Label_list | Multi-label classification and filtering | + + +Use `table.index_stats()` to monitor index coverage. +Unindexed rows can add scan work. Use their count alongside query measurements +to decide when index maintenance is needed. + + +#### 2\. Query Plan Optimization {#2-query-plan-optimization} + +##### Common Patterns and Fixes {#common-patterns-and-fixes} + +| Plan Pattern | Optimization | +| ------------------------------------------ | --------------------------------------------- | +| Scan with high bytes read or I/O count | Check index coverage and whether the query can use an index | +| | Use `select()` to limit returned columns | +| | Check whether the dataset has been compacted | +| Multiple filters | Check their placement and row counts; compare the plan after changing the query | + + +Regularly analyze your query plans to identify and address performance +bottlenecks. The `analyze_plan` output provides detailed metrics to guide +optimization efforts. + + +#### 3\. Getting Started with Optimization {#3-getting-started-with-optimization} + +Keep the query, data and result limit fixed while changing one factor. Compare +rows processed, bytes read, timings and returned results. For ANN changes, +measure recall too: doing less work is useful only if retrieval quality meets +your application's needs. See [vector indexes](/indexing/vector-index) and +[scalar indexes](/indexing/scalar-index) for index choices. ## Vector and full-text search {#no-vector-sql} @@ -212,8 +799,8 @@ The [SDK vector search API](/search/vector-search) is also available in LanceDB Enterprise and LanceDB Embedded. Use it when you prefer the SDK query builder or need to search embedded tables. -For full-text search in SQL, use the [`fts()`](/sql/functions#fts) table -function or the [`contains_tokens`](/sql/scalar-functions#contains-tokens) +For full-text search in SQL, use the [`fts()`](/sql/dql/fts) table +function or the [`contains_tokens`](/sql/dql/contains-tokens) predicate. ## SQL syntax and API references {#reference} diff --git a/docs/web/curation/aggregate.mdx b/docs/web/curation/aggregate.mdx index 4fbca58f4..170af5696 100644 --- a/docs/web/curation/aggregate.mdx +++ b/docs/web/curation/aggregate.mdx @@ -27,7 +27,8 @@ a record; `doc_id` identifies the document it describes. Run each statement separately in a scratch database or namespace. Create these tables once for the whole section, using fresh names if they already exist. -```sql + +```sql SQL icon="database" CREATE TABLE curation_documents ( row_id BIGINT, doc_id BIGINT, version BIGINT, source VARCHAR, caption VARCHAR, score DOUBLE @@ -44,6 +45,7 @@ CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); INSERT INTO curation_labels VALUES (10, 'cat'), (20, 'dog'), (30, 'cat'); ``` + `score` is a sample quality score, not a search result score. Document 10 has two versions. Document 30 has two records at the same version. Document 40 @@ -56,13 +58,15 @@ has no label. These cases let you check the effect of each operation. Use `count(*)` to count rows and `count(column)` to count non-null values. Add `DISTINCT` to count unique values: -```sql + +```sql SQL icon="database" SELECT count(*) AS records, count(DISTINCT doc_id) AS documents, count(caption) AS captioned, count(*) FILTER (WHERE caption IS NULL) AS missing_caption FROM curation_documents; ``` + The example returns **6 records, 4 documents, 4 populated captions and 2 missing captions**. `count(column)` excludes null values; it does not check whether a @@ -72,12 +76,14 @@ string is empty or whether a value is useful for the task. Use `GROUP BY` to calculate a summary for each label: -```sql + +```sql SQL icon="database" SELECT label, count(*) AS documents FROM curation_labels GROUP BY label ORDER BY documents DESC, label; ``` + There are **2 cats and 1 dog** in the label table. Document 40 is absent, so this query does not measure labeling coverage across all source documents. Use a @@ -90,7 +96,8 @@ To cap the number selected per label, use ## Count records that match a condition {#conditional} -```sql + +```sql SQL icon="database" SELECT source, count(*) AS records, count(*) FILTER (WHERE score >= 0.9) AS high_score, @@ -99,6 +106,7 @@ FROM curation_documents GROUP BY source ORDER BY source; ``` + `FILTER` applies a condition to one aggregate. Here, `books` has 2 records, 1 high-score record and no missing captions. `web` has 4 records, 1 high-score @@ -112,22 +120,54 @@ Use `count(DISTINCT column)` for the number of distinct non-null values. For numeric fields, group by a range or summarize their distribution. For example, this query counts records in score buckets of width 0.1: -```sql + +```sql SQL icon="database" SELECT floor(score * 10) / 10 AS score_bucket, count(*) AS records FROM curation_documents GROUP BY score_bucket ORDER BY score_bucket; ``` + For time-based data, group by the time interval relevant to the task. The [aggregation reference](/sql/dql/aggregation) and -[scalar function reference](/sql/scalar-functions) cover additional summaries, +[scalar function reference](/sql/dql/scalar-functions) cover additional summaries, including approximate counts and percentiles. Use an approximate aggregate when an estimate is sufficient; use an exact count when the result must be precise. +## Aggregate over a Function's result {#functions} + +An aggregate can summarize a [Function](/curation/create-function)'s +output the same as any other expression -- the engine computes the +Function once per row, then aggregates. Register `caption_quality` the +same way any other curation Function is registered: + + +```python Python icon="python" +from lancedb import udf + +@udf +def caption_quality(caption: str) -> float: + ... # score the caption, e.g. with a lightweight heuristic or model + +db.create_function_async(caption_quality).wait() +``` + +```sql SQL icon="database" +SELECT source, avg(caption_quality(caption)) AS avg_quality +FROM curation_documents +WHERE caption IS NOT NULL +GROUP BY source +ORDER BY source; +``` + + +Filtering out null captions first avoids calling the Function on rows with +nothing to score. + ## Profile a sample {#sampling} -A [sample](/curation/sampling) can help you explore a large dataset before a +A [sample](/curation/statistical-sampling) can help you explore a large dataset before a full scan. Report the sample size and method alongside the result. A sample can miss rare classes, and fragment sampling can reflect the order in which records were written. @@ -136,7 +176,7 @@ constraints directly rather than inferring them from a small sample. ## Continue curating {#reference} -Use these measurements to choose a [sample](/curation/sampling), +Use these measurements to choose a [sample](/curation/statistical-sampling), [attach missing metadata](/curation/join), or [select one record per document](/curation/windowing). See [Aggregation](/sql/dql/aggregation) for complete SQL syntax. diff --git a/docs/web/curation/blob-late-materialization.mdx b/docs/web/curation/blob-late-materialization.mdx new file mode 100644 index 000000000..81398a112 --- /dev/null +++ b/docs/web/curation/blob-late-materialization.mdx @@ -0,0 +1,176 @@ +--- +title: "Blob Late Materialization" +sidebarTitle: "Blob Late Materialization" +description: "Deferring a wide BlobV2 or vector column's read until after a join has already narrowed down which rows survive." +icon: clock +keywords: ["late materialization", "blob", "blobv2", "join", "remotetake", "take"] +availability: + embedded: unavailable + enterprise: available +--- + +A join that includes a wide column -- a [BlobV2](/management/table#managed-blobs) +or an embedding -- can multiply that column's read far past the result's +own row count: a naive plan reads the wide column for every candidate row +the join considers, then throws most of that work away once the join +condition filters non-matches. Blob late materialization is the +optimizer rewrite that avoids this, deferring the wide read until after +the join has already settled which rows survive. + +## The two plan shapes {#plan-shapes} + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TB + subgraph Naive["Naive: wide column read before filtering"] + direction TB + N1["Scan wide column
for every row"] --> N2["Join"] + N2 --> N3["Rows that didn't match
are discarded --
their wide read was wasted"] + end + + subgraph Deferred["Late materialization: wide column read after filtering"] + direction TB + D1["Scan only the join key
(+ early columns)"] --> D2["Join on the key"] + D2 --> D3["RemoteTake:
fetch the wide column,
once per surviving row"] + end + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class D3 accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TB + subgraph Naive["Naive: wide column read before filtering"] + direction TB + N1["Scan wide column
for every row"] --> N2["Join"] + N2 --> N3["Rows that didn't match
are discarded --
their wide read was wasted"] + end + + subgraph Deferred["Late materialization: wide column read after filtering"] + direction TB + D1["Scan only the join key
(+ early columns)"] --> D2["Join on the key"] + D2 --> D3["RemoteTake:
fetch the wide column,
once per surviving row"] + end + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class D3 accent +``` + +
+ +In the naive plan, the wide column is read once per **candidate** row -- +every row either side of the join could possibly produce -- before the +join has thrown any of them away. In the rewritten plan, the join +operates on a narrowed schema (the key, any small "early" columns, and a +row id), and a `RemoteTake` node fetches the wide column afterward, once +per row that actually **survived** the join. + +## Eligibility {#eligibility} + +This is a physical-plan optimizer rewrite, not something you opt into +with special syntax -- the optimizer decides whether a given join +qualifies. It applies to a plain inner equi-join (a single `ON left_col += right_col` condition, no additional filter fused into the join, no +`LIMIT` fused into it) where one side -- and only one side -- bottoms out +at a single, otherwise-unfiltered table scan: no existing row filter, +scan range, fragment subset, deleted-row handling, or +[RTE write](/ingestion/realtime-write) tier. If both sides would +otherwise qualify, the side with a BlobV2 column is preferred over the +other; if neither or both sides have one, the rewrite declines rather +than guessing which to narrow. + +Which columns actually get deferred differs by which side of the join is +narrowed: + +- **The side that builds the join's hash table:** every column beyond + the join key is deferred, regardless of size. The hash table holds + everything this side reads for the lifetime of the join, so even a + modestly-sized column adds up across every row the join holds in + memory at once. +- **The side that probes the hash table:** only columns wide enough to + cross a size heuristic are deferred; small columns stay in the initial + scan, since reading them eagerly doesn't carry the same memory risk. + +A BlobV2 column's **descriptor** (small, pointer-like) is early and +stays in the scan either way -- only the raw **bytes** of the blob are +late and deferred, so narrowing doesn't lose track of which rows have a +blob at all, just postpones reading its payload. + +## Where the deferred read actually happens {#remotetake} + +The take itself runs through the same replica-group-aware routing as any +other distributed table read (see [Horizontal Scaling](/enterprise/horizontal-scaling)) -- +it is not shipped back to the query node to be joined there directly. +Routing is resolved once per query and reused across every batch the +take processes, rather than re-resolved per batch, which is what keeps +repeated takes in the same query hitting a cache that's already warm +instead of bouncing between replica groups. Where the executing node +already holds the needed data, the take can also resolve natively +without a separate network round trip at all. + +## Confirming it happened {#explain} + +A join written this way is a **candidate** for the rewrite, not a +guarantee -- confirm it per query with +[`EXPLAIN`](/basics/sql#query-plans). A `Take` or `RemoteTake` node by +itself isn't proof either way -- it's the general operator that fetches +columns for selected rows from remote storage, and shows up in an +ordinary, join-free query just as it does here (see the +[recorded vector-search plan](/basics/sql#5-data-retrieval)); the +rewrite itself inserts a plain `Take`, which only a later, separate pass +turns into `RemoteTake`. What confirms the deferral specifically is a +`Take`/`RemoteTake` node sitting above a `HashJoinExec`, fetching a +column set that includes `__join_late_materialization_key` -- that key +column only exists when this rewrite fired. Join on a narrow, selective +key and project the wide columns only in the final select list, rather +than alongside the join condition: + + +```sql SQL icon="database" +SELECT s.frame_id, f.image, f.embedding +FROM selected AS s +JOIN frames AS f ON f.frame_id = s.frame_id +``` + + +`selected` is narrow -- just the frame IDs an earlier curation step +already kept. `frames` is wide -- a BlobV2 `image` and a vector +`embedding` alongside its key. Neither a passing query nor an `EXPLAIN` +that omits `RemoteTake` tells you how much I/O a plan did or did not +save on its own -- use [`EXPLAIN ANALYZE`](/sql/dql/explain) for the +plan's actual row and byte counts, since plain `EXPLAIN` shows the +planned shape without executing the query. + +## What to read next {#next} + + + + Join types, duplicate keys, and calling a Function across a join. + + + Join syntax and semantics in the SQL reference. + + + Reading `EXPLAIN` output in general. + + + The replica-group routing a RemoteTake's read goes through. + + diff --git a/docs/web/curation/changes.mdx b/docs/web/curation/changes.mdx index 28f98f784..266e5cf01 100644 --- a/docs/web/curation/changes.mdx +++ b/docs/web/curation/changes.mdx @@ -20,7 +20,8 @@ to what is new. `curation_batches` gets a batch of new documents appended periodically, with no updates or deletes between appends: -```sql + +```sql SQL icon="database" CREATE TABLE curation_batches (doc_id BIGINT, source VARCHAR, text VARCHAR); INSERT INTO curation_batches VALUES (1, 'web', 'A cat on a chair'), @@ -31,15 +32,18 @@ INSERT INTO curation_batches VALUES (4, 'books', 'A cat by a window'); -- the table is now at a later version, for example 7 ``` + ## Read only what is new {#read-new} `CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5)` reads the rows appended after version 5 -- documents 3 and 4 -- without rescanning 1 and 2: -```sql + +```sql SQL icon="database" SELECT * FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) ``` + Record the table's version after each curation run, then start the next run's `CHANGES` from it. See [Versioning](/management/table#versioning) for @@ -52,12 +56,14 @@ the rest of this page: chunk, dedupe, or join only the new rows, instead of the whole table. Materializing the result keeps a running, append-only table of work already done: -```sql + +```sql SQL icon="database" INSERT INTO curated_batches SELECT doc_id, source, text FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) WHERE source = 'books' ``` + A [chunker Function](/curation/chunking) or a [`dedupe`](/sql/dql/dedupe) call works the same way: put the `CHANGES` relation where the source table @@ -70,10 +76,12 @@ other than a pure append happened to the table between the starting version and the current one -- an update, a delete, a merge -- the query is refused rather than silently returning an incomplete or wrong result: -```sql + +```sql SQL icon="database" -- refused if any row in curation_batches was updated or deleted after version 5 SELECT * FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) ``` + When that happens, either re-run from a later starting version that is itself after the non-append write, or read the table in full instead of diff --git a/docs/web/curation/chunking.mdx b/docs/web/curation/chunking.mdx index f4c0197b7..cff8f4b49 100644 --- a/docs/web/curation/chunking.mdx +++ b/docs/web/curation/chunking.mdx @@ -25,7 +25,11 @@ Functions, and scalar versus batch calling, if you have not registered one before. A function that splits text into fixed-size passages turns a `documents` -table into one row per passage: +table into one row per passage. Registration details, environment and +dependency declarations, and how a version stays immutable once rows are +filled from it, are the same for a chunker as for any other Function -- +register it from Python, or the same function from SQL with +[`CREATE FUNCTION`](/sql/ddl/function#create): **Source: `documents`** @@ -36,9 +40,9 @@ table into one row per passage: ```python Python icon="python" import pyarrow as pa -from lancedb.functions import udf +from lancedb.functions import function -@udf( +@function( output_schema=pa.list_( pa.struct([ pa.field("chunk_index", pa.int64(), nullable=False), @@ -55,36 +59,37 @@ def split_into_passages(text: str) -> list[dict]: version = db.create_function_async(split_into_passages).wait() ``` - -Registration details, environment and dependency declarations, and how a -version stays immutable once rows are filled from it, are the same for a -chunker as for any other Function. The same function can be registered from -SQL with `CREATE FUNCTION`: - - -```sql SQL +```sql SQL icon="database" CREATE FUNCTION split_into_passages(text utf8) RETURNS list> LANGUAGE python -AS 'def split_into_passages(text): size = 200; return [{"chunk_index": i, "chunk_text": text[i:i+size]} for i in range(0, len(text), size)]' +AS ' +def split_into_passages(text): + size = 200 + return [ + {"chunk_index": i, "chunk_text": text[i:i+size]} + for i in range(0, len(text), size) + ] +' ``` ## Explode it in a query {#explode} -Call the function in the `FROM` clause, after the source table, with an -alias: a Function there yields one row per element of the list it returns, -with every other column repeated. Reference the function's output fields -through the alias: +Wrap the function call in `UNNEST` in the `SELECT` list, with an alias: it +yields one row per element of the list the function returns, with every +other selected column repeated. Reference the exploded struct's fields +through that alias in a query over this one: -```python Python icon="python" -reader = db.execute_query(""" - SELECT doc_id, title, p.chunk_index, p.chunk_text - FROM documents, split_into_passages(text) AS p -""") -print(reader.read_all().to_pylist()) +```sql SQL icon="database" +WITH exploded AS ( + SELECT doc_id, title, UNNEST(split_into_passages(text)) AS p + FROM documents +) +SELECT doc_id, title, p.chunk_index, p.chunk_text +FROM exploded ``` @@ -112,7 +117,7 @@ A chunker that samples one timestamp per second needs no blob access at all ```python Python icon="python" -@udf( +@function( output_schema=pa.list_( pa.struct([ pa.field("frame_index", pa.int64(), nullable=False), @@ -134,11 +139,10 @@ rather than loading the whole clip -- and returns one JPEG per call: ```python Python icon="python" -import lancedb from datetime import timedelta from lancedb import BlobReader -@udf( +@function( name="extract_frame", gpu=True, pip=["av==13.1.0", "pillow==11.0.0"], @@ -159,11 +163,13 @@ Compose both in one query: explode `videos` into one row per sampled timestamp, then call `extract_frame` on each row to produce its image: -```python Python icon="python" -reader = db.execute_query(""" - SELECT video_id, f.frame_index, f.ts, extract_frame(video, f.ts) AS jpeg - FROM videos, sample_frame_timestamps(duration_seconds) AS f -""") +```sql SQL icon="database" +WITH sampled AS ( + SELECT video_id, video, UNNEST(sample_frame_timestamps(duration_seconds)) AS f + FROM videos +) +SELECT video_id, f.frame_index, f.ts, extract_frame(video, f.ts) AS jpeg +FROM sampled ``` @@ -179,10 +185,14 @@ to keep a real table that stays current as the source changes, instead of recomputing the explosion on every query: -```sql SQL +```sql SQL icon="database" CREATE MATERIALIZED VIEW chunks AS +WITH exploded AS ( + SELECT doc_id, title, UNNEST(split_into_passages(text)) AS p + FROM documents +) SELECT doc_id, title, p.chunk_index, p.chunk_text -FROM documents, split_into_passages(text) AS p +FROM exploded ``` @@ -196,15 +206,16 @@ FROM documents, split_into_passages(text) AS p The view refreshes like any other materialized view: new source rows are chunked and inserted, deleted source rows drop their children, and an updated row's old children are replaced by freshly chunked ones on the next -[refresh](/feature-engineering/refresh-column). A single Function call or -`UNNEST(column)` is the only lateral source a materialized view can carry -- -not both, and not combined with `GROUP BY` -- so keep aggregation or further -curation in a second step over the chunked table. +[refresh](/feature-engineering/refresh-column). A single `UNNEST(...)` -- +whether unnesting a Function's list output directly, as above, or an +existing list column -- is the only lateral expansion a materialized view +can carry, and it can't be combined with `GROUP BY`, so keep aggregation or +further curation in a second step over the chunked table. ## Chunk, then curate {#next} A freshly chunked table is a normal table: [dedupe](/curation/dedupe) it to -collapse near-identical chunks, [sample](/curation/sampling) it for a quick +collapse near-identical chunks, [sample](/curation/statistical-sampling) it for a quick look, or [profile it](/curation/aggregate) to check how many chunks each source row produced. Continue with [choosing a curation task](/curation#questions). diff --git a/docs/web/curation/clustering.mdx b/docs/web/curation/clustering.mdx new file mode 100644 index 000000000..d0b6ae2a2 --- /dev/null +++ b/docs/web/curation/clustering.mdx @@ -0,0 +1,166 @@ +--- +title: "Cluster records by index partition" +sidebarTitle: "Clustering" +description: "Group records by the partition an existing IVF vector index already assigns them to, without training a new clustering model." +icon: circle-nodes +keywords: ["clustering", "ivf_partition", "ivf", "vector index", "group by", "centroid"] +availability: + embedded: unavailable + enterprise: available +--- + +`ivf_partition` groups records by the partition a vector falls into, using the +centroids of an IVF-family vector index you already built for search -- no +separate clustering model to train or maintain. Use it as a `GROUP BY` key to +aggregate per cluster, or to sample across clusters instead of across rows. + +## Example data {#example-data} + +Connect with an [Enterprise connection](/basics/catalog#enterprise). + + + +Use the same `curation_embeddings` fixture as [dedupe](/curation/dedupe#example-data) +-- eight records, where rows 10 and 20 are near-identical, 30, 40 and 50 +form one looser cluster, and 60, 70 and 80 are each distinct and +increasingly far apart -- but build the index with more partitions. +Clustering wants partitions fine-grained enough to tell the two clusters +apart; deduplication only needs a distance threshold within one: + + +```python Python icon="python" +table.create_index("embedding", config=IvfFlat(num_partitions=5, distance_type="l2")) +table.wait_for_index(["embedding_idx"]) +``` + +```typescript TypeScript icon="square-js" +await table.createIndex("embedding", { + config: lancedb.Index.ivfFlat({ numPartitions: 5, distanceType: "l2" }), +}); +await table.waitForIndex(["embedding_idx"], 300); +``` + +```rust +use std::time::Duration; + +use lancedb::index::vector::IvfFlatIndexBuilder; +use lancedb::index::Index; +use lancedb::DistanceType; + +table + .create_index( + &["embedding"], + Index::IvfFlat(IvfFlatIndexBuilder::default().num_partitions(5).distance_type(DistanceType::L2)), + ) + .execute() + .await?; +table.wait_for_index(&["embedding_idx"], Duration::from_secs(300)).await?; +``` + + +`ivf_partition` reads an existing index's trained centroids; it does not +train one. The column needs an up-to-date, single-segment IVF-family index +before the function runs, the same requirement [`dedupe`](/curation/dedupe#example-data) +has. + + + +## Group records by partition {#group} + +`ivf_partition(column)` returns the partition each row's vector falls into. +Rows closer to the same centroid than to any other land in the same +partition, so the near-identical cat photos (10, 20) group together, the +three dog photos (30, 40, 50) group together, and the three increasingly +distant photos (60, 70, 80) are more likely to each keep their own partition: + + +```sql SQL icon="database" +SELECT ivf_partition(embedding) AS cluster, array_agg(id) AS ids, count(*) AS n +FROM curation_embeddings +GROUP BY cluster +ORDER BY cluster +``` + + +The exact partition numbers depend on how the index's centroids were trained, +but rows that are close together in embedding space consistently land in the +same group. Aggregate anything per cluster this way -- `count(*)` for cluster +sizes, `avg(score)` for a per-cluster quality signal, or `array_agg(id)` to +collect candidate rows for a downstream pass. + +## Sample across clusters instead of across rows {#sample} + +Pass a selection mode to group by only a subset of the index's partitions, +instead of all of them: + + +```sql SQL icon="database" +-- The first 2 partitions, deterministically +SELECT ivf_partition(embedding, 'first', 2) AS cluster, array_agg(id) AS ids +FROM curation_embeddings +GROUP BY cluster; + +-- 2 partitions chosen at random, reproducible via the seed +SELECT ivf_partition(embedding, 'random', 2, 42) AS cluster, array_agg(id) AS ids +FROM curation_embeddings +GROUP BY cluster; +``` + + +`'first'` takes the first `count` partitions and accepts no seed, since the +result is already deterministic. `'random'` requires a seed, so the same +call reproduces the same partitions. Either way, the result is a +spatially-stratified sample across the embedding space: one that covers +each selected region of the data, rather than a plain row sample that can +easily pick many near-duplicate rows from a dense cluster and miss a sparse +one entirely. + +## Keep a clustering current with a materialized view {#materialized} + +Wrap a `GROUP BY ivf_partition(...)` query in a +[materialized view](/management/materialized-view) so the grouping stays +current as new records arrive: + + +```sql SQL icon="database" +CREATE MATERIALIZED VIEW curation_embeddings_clustered AS +SELECT ivf_partition(embedding) AS cluster, array_agg(id) AS ids +FROM curation_embeddings +GROUP BY cluster +``` + + +A refresh reassigns every row's partition from the index's current centroids, +so retraining the index with +[`replace=True`](/feature-engineering/add-computed-column) regroups the view +on the next refresh. See +[Refresh a materialized view](/feature-engineering/refresh-materialized-view) +for manual and automatic refresh options. + +## A typical use case: deduplication {#dedupe} + +Near-duplicate records are close together in embedding space, so they +consistently land in the same or a neighboring partition. Grouping by +`ivf_partition` first, then comparing distances only within each group, finds +near-duplicate candidates without a full pairwise scan across the whole +table. + +This is exactly the approach [`dedupe` and `duplicate_pairs`](/curation/dedupe) +use internally, packaged as a table function with a `distance_threshold` +instead of a `GROUP BY` clause to write yourself. Reach for those directly for +deduplication; use `ivf_partition` when the task is a different kind of +per-cluster grouping or sampling, not deduplication specifically. + +## Related guides {#next} + + + + The full function signature: arguments, sampling modes, and positional syntax. + + + The packaged table function for the deduplication use case above. + + + Row-level and fragment-level sampling, without clustering. + + diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 2d161e84b..9f6370347 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -1,5 +1,6 @@ --- title: "Create a Function" +tag: "Early access" sidebarTitle: "Create Function" description: "Register Python as a column: CPU, GPU, and remote-service Functions, called once per row or once per batch." icon: code @@ -9,12 +10,17 @@ availability: enterprise: available --- +Early access + Some curation steps cannot be written as a SQL expression: an embedding model, an image decode, a call to an external service. A Function is a Python callable registered with the database, versioned, and then applied as a column or called in a query -- the code runs where the data is, not pulled into your process first. This page covers how to shape one; later curation -tasks such as [Chunking](/curation/chunking) assume you have read it. +tasks such as [Chunking](/curation/chunking) assume you have read it. The +full registration, listing, refresh and drop lifecycle is covered on the +[Function management reference](/management/function); the examples below +focus on shaping a Function for common curation tasks. ## Scalar: once per row {#scalar} @@ -23,9 +29,9 @@ inferred from the annotations: ```python Python icon="python" -from lancedb import udf +from lancedb import function -@udf(pip=["numpy==2.2.0"]) +@function(pip=["numpy==2.2.0"]) def score(value: float) -> float: return value * 2 @@ -49,9 +55,13 @@ same doubling logic, vectorized over a whole batch at once: ```python Python icon="python" import pyarrow as pa import pyarrow.compute as pc -from lancedb import udf +from lancedb import function -@udf(pip=["numpy==2.2.0"]) +@function( + pip=["numpy==2.2.0"], + batch_size=32, + row_timeout_seconds=90, +) def score_batch(value: pa.Array) -> pa.Array: return pc.multiply(value, 2) ``` @@ -61,17 +71,25 @@ Batching amortizes per-call overhead across many rows, which matters most once a function also does something with real fixed cost per call -- loading a model, opening a connection, making a network round trip. +`batch_size` caps the number of input rows in each execution batch; actual +batches may be smaller. `row_timeout_seconds` bounds each Python call: one +row for scalar Functions or the entire batch for vectorized Functions. It +does not include the instance's `__init__`. Both settings are fixed into the +registered version and apply to direct calls, computed columns, and +materialized-view refreshes alike. Omit them to use adaptive batching and the +service's default per-call deadline. + ## Stateful Functions: load once, call many times {#stateful} -A `@udf`-decorated **class** is the same callable with state. Each remote +A `@function`-decorated **class** is the same callable with state. Each remote instance calls `__init__` once, calls `__call__` for every row or batch it processes, and calls `close()`, if defined, once when it retires: ```python Python icon="python" -from lancedb import udf +from lancedb import function -@udf +@function class scale: def __init__(self, factor: float, offset: float = 0.0): self.factor = factor @@ -92,16 +110,26 @@ and remote-API Functions both build on below. ## GPU: batch inference, loaded once {#gpu} -`gpu=True` requires a GPU-capable worker for every execution. Combined with -the batch and stateful forms above, a realistic embedding model loads once -in `__init__` and runs one forward pass per batch, not one per row: +`db.list_gpu_classes()` lists the GPU classes configured for the deployment. +Each record reports the operator's hardware description and limits; it does +not mean a GPU is currently free. Listing requires the System Usage +permission. Pass a returned class name to `gpu_class` to fix that placement +in the Function version. `gpu=True` remains required: ```python Python icon="python" import pyarrow as pa -from lancedb import udf +from lancedb import function -@udf(gpu=True, pip=["torch==2.12.0", "sentence-transformers==5.7.0"]) +gpu_class = next( + gpu.name for gpu in db.list_gpu_classes() if gpu.gpu_model == "NVIDIA A10G" +) + +@function( + gpu=True, + gpu_class=gpu_class, + pip=["torch==2.12.0", "sentence-transformers==5.7.0"], +) class embed_text: def __init__(self, model_name: str = "all-MiniLM-L6-v2"): import torch @@ -120,6 +148,12 @@ table.add_columns({"embedding": version(text=col("caption"))}) ``` +Older servers that do not implement `GET /v1/gpu/classes` raise +`NotImplementedError`. Without `gpu_class`, the deployment's default GPU +class is used. The class is immutable with the Function version; set a +per-refresh class or aggregate GPU budget through +[`refresh_column_async`](/feature-engineering/refresh-column#resources). + The model loads once per worker instance, in `__init__`; `__call__` only encodes the batch it was handed. Registering the same logic as a plain function instead would reload the model on every single row. @@ -132,56 +166,59 @@ in the function's source. A Secret is a database-scoped named credential: puts it in the environment variable the function reads, without ever returning it from any API or recording it in the function's own definition. Combine it with the stateful form so the HTTP client -- and any rate limiter -around it -- is built once, not reopened on every row: +around it -- is built once, not reopened on every row. There is no built-in +retry or per-row error-skip policy -- a function that calls a flaky service +should handle timeouts and retries itself, inside `__call__`. - -```python Python icon="python" -import os -from lancedb import EnvVarSecret, udf +See [Vend a Secret to a Function](/curation/vend-secret#specify) for the +full worked example, how the bound value actually reaches a running +evaluation, and how that differs from rotating or revoking it later. -db.create_secret("openai-prod", os.environ["OPENAI_API_KEY"]) - -@udf -class embed_remote: - def __init__(self, model: str = "text-embedding-3-small"): - import os - from openai import OpenAI - - self.client = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) - self.model = model - - def __call__(self, text: str) -> list[float]: - response = self.client.embeddings.create(input=text, model=self.model) - return response.data[0].embedding - -version = db.create_function_async( - embed_remote, - secrets=[EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")], -).wait() -``` - - -A mistyped Secret name is caught at registration; a mistyped environment -variable name only surfaces on the first rows, since nothing records which -variables a function reads. There is no built-in retry or per-row -error-skip policy -- a function that calls a flaky service should handle -timeouts and retries itself, inside `__call__`. - -## Blob v2 input and output {#blob} +## Read and produce blobs {#blobs} A Function can bind a [Blob v2 column](/management/table#managed-blobs) and -return another one, including a blob nested inside a struct field, not only -at the top level. In row mode, a blob parameter arrives as Python `bytes` -(or a `BlobReader` for incremental, seekable access, so a function never -has to materialize a payload it only partially needs): +return another blob, including a blob nested inside a struct field, not only +at the top level. In row mode, a top-level blob parameter arrives as Python +`bytes`, or `None` for a nullable input, after the worker has read the +payload. Return bytes and let the destination table store the Managed +payload and descriptor. + +This section extracts a frame from a stored video and captions it, +continuing as one example across chaining, persisting and incremental reads +below. `videos` holds raw clips in a `video` Blob v2 column; `frames` names +one timestamp per clip to extract, with a `selected` flag to skip some: ```python Python icon="python" import pyarrow as pa -import lancedb -from lancedb import BlobReader, udf -@udf( +videos = db.create_table("videos", schema=pa.schema([ + pa.field("id", pa.utf8(), nullable=False), + lancedb.blob("video", nullable=False), +])) +frames = db.create_table("frames", [ + {"frame_id": 1, "video_id": "clip-1", "ts": 0.5, "selected": True}, + {"frame_id": 2, "video_id": "clip-1", "ts": 1.5, "selected": True}, +]) +``` + + +### Produce a blob {#produce-blobs} + +Declare blob inputs and outputs explicitly. `extract_frame` reads one frame +out of a video at a timestamp and returns it as a JPEG, without loading the +whole clip first -- see [Read a blob incrementally](#incremental) below for +how the `video: BlobReader` parameter does that: + + +```python Python icon="python" +from datetime import timedelta + +from lancedb import BlobReader, col +from lancedb.functions import function + +@function( + name="extract_frame", gpu=True, pip=["av==13.1.0", "pillow==11.0.0"], input_schema=pa.schema([ @@ -192,18 +229,153 @@ from lancedb import BlobReader, udf ) def extract_frame(video: BlobReader, ts: float) -> bytes: ... # decode the frame at ts, encode as JPEG, return its bytes + +extract_frame_version = db.create_function_async(extract_frame).wait( + timeout=timedelta(minutes=15) +) ``` -`output_schema=lancedb.blob(...)` is what makes the result Blob v2 rather -than plain Arrow `binary` -- returning `bytes` with no explicit blob output -schema still holds the right bytes, but skips the Managed storage path and -`fetch_blobs`. Declare it explicitly on every function whose output should -be a blob. +An empty byte string is a filled result. A scalar output cannot be nullable, +because a physical NULL marks an unfilled computed row. To return a nullable +blob as a value, use a named-struct output schema with a nullable blob field; +the struct itself records whether the result has been filled. Read a nested +blob with `table.fetch_blobs("payload.image", hits)`. + +A list or large-list output may also contain Blob v2 elements; inputs and +fixed-size lists do not support this layout. List-nested values are queryable +as descriptors, but `fetch_blobs` and `blob_mode="bytes"` cannot fetch their +payloads. + + +`output_schema=lancedb.blob(...)` is what makes a persisted result Blob v2 +rather than plain Arrow `binary`. Returning `bytes` from a function whose +output type is inferred from a bare annotation, with no explicit +`lancedb.blob(...)` output schema, persists as ordinary `binary`: the column +still holds the right bytes, but it skips the Managed storage path, descriptor +reads, and `fetch_blobs`. Declare it explicitly on every function whose output +should be a blob, not just the first one in a chain. + + +### Chain a Function on its output {#chain} + +A second Function can bind a blob another Function produced. Register +`caption` the same way, consuming a blob instead of producing one: + + +```python Python icon="python" +@function(gpu=True, pip=["transformers==4.47.0"]) +def caption(jpeg: bytes) -> str: + ... # run a vision-language model over the JPEG, return one sentence + +caption_version = db.create_function_async(caption).wait(timeout=timedelta(minutes=15)) +``` + + +Compose both in one SQL statement over a join, instead of applying each as +its own column. The join supplies `video` and `ts` from two different +tables, and `caption` reads `extract_frame`'s result as it is computed, +before anything is written: + + +```sql SQL +SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, + caption(extract_frame(v.video, f.ts)) AS caption +FROM videos v JOIN frames f ON v.id = f.video_id +WHERE f.selected = true +``` + + +[`EXPLAIN`](/sql/dql/explain) on a query like this shows `RemoteTake`: the +blob is read once, where the worker runs, and never pulled into the query +node first. + +### Persist it as a column, or a materialized view {#persist} + +Apply the same registered version with `add_columns` to persist its output as +an ordinary table column, on a table that already has both of its inputs -- +here, a single-clip table with its own `video` and `ts`, rather than the two +tables the join above reads from: + + +```python Python icon="python" +clips = db.create_table("clips", schema=pa.schema([ + pa.field("frame_id", pa.int64(), nullable=False), + lancedb.blob("video", nullable=False), + pa.field("ts", pa.float64(), nullable=False), +])) + +clips.add_columns({"jpeg": extract_frame_version(video=col("video"), ts=col("ts"))}) +result = clips.refresh_column_async("jpeg").wait(timeout=timedelta(minutes=15)) +assert result.rows_failed == 0 + +hits = clips.search().select(["frame_id", "jpeg"]).with_row_id(True).to_arrow() +values = clips.fetch_blobs("jpeg", hits).to_pylist() +``` + + +Or wrap the join and both Functions in a +[materialized view](/sql/ddl/materialized-view) instead, so the extracted +frame and its caption stay current as new videos and frames arrive. See +[Auto Refresh](/enterprise/auto-refresh) for +keeping either one fresh without calling refresh yourself. + +On deployments that support computed-column inputs, another Function can +bind to `col("jpeg")` directly, the same as the SQL join above does through +its own expression. Refresh the producer first, then the consumer. Once +outputs are current, a later refresh fills appended rows. A filtered +refresh preserves payload references for unselected Managed outputs. An +unfiltered refresh can recompute a whole fragment when it cannot establish +that the fragment's outputs are current. + +Function output blobs follow the same compaction and cleanup lifecycle as +ingested Managed blobs. Retained versions continue to own their payloads; +cleanup reclaims an object only after its retained references are gone. + +### Read a blob incrementally {#incremental} + +Annotate a row Function parameter with `BlobReader` to read a Blob v2 input +incrementally, the way `extract_frame` above does, instead of materializing +the whole payload first. The signature selects the access mode without +another registration option. A minimal example, reading only the first MP4 +box type without loading the rest of the video: + + +```python Python icon="python" +from lancedb import BlobReader, function + + +@function +def first_box_type(video: BlobReader) -> bytes: + video.seek(4) + return video.read(4) +``` + + +The worker passes a seekable reader backed by the stored blob -- +`video.seekable()` is `True`. `read(size)` reads from the current cursor; +`read_range(offset, length)` reads a byte range without moving it, the same +bytes a `seek(offset)` followed by `read(length)` would read. `size()` +returns the payload size without reading it. Each row call receives its own +reader, which closes when the call returns or raises. Do not retain it for +another invocation. + +Use `video: bytes` when the Function needs the complete payload. Bytes inputs +materialize before invocation and remain subject to eager input limits. +Reader inputs keep the unread payload out of the input batch, but calling +`video.read()` without a size loads all remaining bytes in Python. Reader +inputs are supported in row mode. Return values remain ordinary values such +as `bytes`; this feature does not add streamed outputs. ## What to read next {#next} + + List, describe and drop registered Function versions. + + + Bind a credential by reference instead of putting it in the function's source. + A Function whose output is a list, exploded into one row per element. diff --git a/docs/web/curation/dedupe.mdx b/docs/web/curation/dedupe.mdx index bdcf0b4b2..470e170c2 100644 --- a/docs/web/curation/dedupe.mdx +++ b/docs/web/curation/dedupe.mdx @@ -9,7 +9,7 @@ availability: enterprise: available --- -[Ranking and deduplication](/curation/windowing#dedup) removes records by an +[Ranking](/curation/windowing#dedup) removes records by an explicit rule, such as keeping the latest version of a known key. This page covers the other kind of duplicate: records with no shared key that are still nearly identical, judged by distance between their embeddings -- a stopped @@ -57,23 +57,27 @@ table.wait_for_index(["embedding_idx"]) before either function runs; a query against unindexed fragments is rejected rather than silently returning stale or wrong results. +For an `l2` index, `distance_threshold` and the `distance` column below are +both **squared** L2, not the plain L2 a plain SQL `distance()` call returns. + ## Collapse near-duplicates {#dedupe} `dedupe` returns one representative row per cluster of records within `distance_threshold` of each other -- rows 10/20 collapse to one, 30/40/50 -collapse to one, and the four distinct rows pass through unchanged: +collapse to one, and the four distinct rows pass through unchanged, leaving +ids 10, 30, 60, 70 and 80: -```python Python icon="python" -reader = db.execute_query(""" - SELECT id, caption FROM dedupe('curation_embeddings', 'embedding', distance_threshold => 0.06) - ORDER BY id -""") -print(reader.read_all().to_pylist()) -# [{'id': 10, 'caption': 'a cat on a chair'}, {'id': 30, 'caption': 'a dog in a field'}, -# {'id': 60, ...}, {'id': 70, ...}, {'id': 80, ...}] +```sql SQL icon="database" +SELECT id, caption +FROM dedupe( + 'curation_embeddings', + 'embedding', + distance_threshold => 0.003 +) +ORDER BY id ``` @@ -96,18 +100,20 @@ id as a stable identifier for its cluster. anything -- useful for review, or for a threshold that is still being tuned: -```python Python icon="python" -db.execute_query(""" - SELECT id_a, id_b, distance FROM duplicate_pairs( - 'curation_embeddings', 'embedding', distance_threshold => 0.06, id_column => 'id' - ) - ORDER BY id_a -""") +```sql SQL icon="database" +SELECT id_a, id_b, distance +FROM duplicate_pairs( + 'curation_embeddings', + 'embedding', + distance_threshold => 0.003, + id_column => 'id' +) +ORDER BY id_a ``` This returns the pairs `(10, 20)`, `(30, 40)` and `(40, 50)` -- note 30 and 50 -are not a direct pair here (they sit `0.10` apart, outside the threshold), +are not a direct pair here (their squared L2 distance is `0.01`, outside the threshold), even though `dedupe` merges all three transitively above. ## Keep it current with a materialized view {#materialized} @@ -117,11 +123,13 @@ the deduplicated set stays current as new records arrive, instead of recomputing it from scratch on every curation pass: -```python Python icon="python" -db.execute_query(""" - CREATE MATERIALIZED VIEW curation_embeddings_deduped AS - SELECT * FROM dedupe('curation_embeddings', 'embedding', distance_threshold => 0.06) -""") +```sql SQL icon="database" +CREATE MATERIALIZED VIEW curation_embeddings_deduped AS +SELECT * FROM dedupe( + 'curation_embeddings', + 'embedding', + distance_threshold => 0.003 +) ``` diff --git a/docs/web/curation/distributed-shuffle.mdx b/docs/web/curation/distributed-shuffle.mdx new file mode 100644 index 000000000..6b73cb778 --- /dev/null +++ b/docs/web/curation/distributed-shuffle.mdx @@ -0,0 +1,111 @@ +--- +title: "Distributed Shuffle" +sidebarTitle: "Distributed Shuffle" +description: "How a SQL query's intermediate results move between plan executors for a join, aggregate or sort." +icon: shuffle +availability: + embedded: unavailable + enterprise: available +--- + +A distributed SQL query plans as a sequence of **stages**, each with its +own set of partitions, connected by an **exchange**: a streaming gRPC +service that carries one stage's output to the next stage's plan +executors. [Distributed Search](/enterprise/distributed-search) covers +how a query gets placed on the fleet in the first place; this page covers +what happens between placement and the final result, for a query whose +plan needs data repartitioned across machines -- a hash join or a grouped +aggregate, for example, where rows with the same key must land on the +same worker regardless of which plan executor originally read them. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + subgraph Stage1["Stage: scan"] + direction TB + PE1["Plan executor
reads its partition"] + PE2["Plan executor
reads its partition"] + end + + EX["Exchange
streaming gRPC,
repartitions by join/group key,
backpressure via a byte budget"] + + subgraph Stage2["Stage: join / aggregate"] + direction TB + PE3["Plan executor
probes its share of keys"] + PE4["Plan executor
probes its share of keys"] + end + + PE1 --> EX + PE2 --> EX + EX --> PE3 + EX --> PE4 + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class EX accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + subgraph Stage1["Stage: scan"] + direction TB + PE1["Plan executor
reads its partition"] + PE2["Plan executor
reads its partition"] + end + + EX["Exchange
streaming gRPC,
repartitions by join/group key,
backpressure via a byte budget"] + + subgraph Stage2["Stage: join / aggregate"] + direction TB + PE3["Plan executor
probes its share of keys"] + PE4["Plan executor
probes its share of keys"] + end + + PE1 --> EX + PE2 --> EX + EX --> PE3 + EX --> PE4 + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class EX accent +``` + +
+ +## Pipelined, not batched {#pipelined} + +The exchange moves data as a gRPC stream of row batches, not a file a +later stage waits for: a consuming plan executor pulls batches as they +become available, and a slow consumer throttles its producer through a +byte budget on unread messages rather than letting memory grow without +bound. A partition that stops being read -- for example the probe side of +a hash join whose build side turned out empty -- is drained rather than +left to stall the budget for every other partition sharing the same +connection. + +## What to read next {#next} + + + + How a query gets placed on the query-serving fleet in the first place. + + + Inspect a specific query's plan and its actual execution metrics. + + diff --git a/docs/web/curation/index.mdx b/docs/web/curation/index.mdx index c4d6a48e5..59b993100 100644 --- a/docs/web/curation/index.mdx +++ b/docs/web/curation/index.mdx @@ -18,17 +18,21 @@ records belong, and save the selected data or the rules used to produce it. | Task | What it helps you decide | | --- | --- | | [Create a Function](/curation/create-function) | How to run your own Python -- on CPU, on GPU, or against a remote service -- as part of SQL. | +| [Vend a Secret to a Function](/curation/vend-secret) | How a bound Secret's value actually reaches a running Function. | +| [Inspect Datasets](/curation/inspect-datasets) | How to query a table, a HuggingFace dataset, or an object-storage dataset the same way, and import without a separate download step. | | [Chunk records](/curation/chunking) | How to split one record into several -- passages, clips, or tiles. | | [Scope to what changed](/curation/changes) | How to process only the rows added since your last run. | | [Profile a dataset](/curation/aggregate) | Whether coverage, missing values and class balance suit the task. | -| [Sample records](/curation/sampling) | Which subset to inspect or use for an experiment. | +| [Statistical Sampling](/curation/statistical-sampling) | Which random fraction to inspect or use for an experiment. | +| [Selective Sampling](/curation/selective-sampling) | How to re-fetch specific rows by ID, address or offset. | | [Join datasets](/curation/join) | How to attach labels, metadata or scores stored elsewhere. | | [Rank and deduplicate](/curation/windowing) | Which records to keep when several share an explicit key. | +| [Cluster by index partition](/curation/clustering) | How to group records by vector proximity without training a new clustering model. | | [Deduplicate near-duplicates](/curation/dedupe) | Which records to collapse when they only look alike, with no shared key. | The analytical examples in this section use **Enterprise SQL**. Connect with -the [SQL guide](/basics/sql). For sampling through the Python SDK in LanceDB Embedded or -LanceDB Enterprise, see [Sample without SQL](/curation/sampling#training). +the [SQL guide](/basics/sql). For a random subset through the Python SDK in +LanceDB Embedded or LanceDB Enterprise, see [Permutation](/training/permutation). ## Prepare a labeled document dataset {#shape} @@ -50,7 +54,8 @@ a record; `doc_id` identifies the document it describes. Run each statement separately in a scratch database or namespace. Create these tables once for the whole section, using fresh names if they already exist. -```sql + +```sql SQL icon="database" CREATE TABLE curation_documents ( row_id BIGINT, doc_id BIGINT, version BIGINT, source VARCHAR, caption VARCHAR, score DOUBLE @@ -67,6 +72,7 @@ CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); INSERT INTO curation_labels VALUES (10, 'cat'), (20, 'dog'), (30, 'cat'); ``` + `score` is a sample quality score, not a search result score. Document 10 has two versions. Document 30 has two records at the same version. Document 40 @@ -77,7 +83,8 @@ has no label. These cases let you check the effect of each operation. The following query chooses the latest record for each document, then keeps only documents with a label: -```sql + +```sql SQL icon="database" WITH ranked AS ( SELECT *, row_number() OVER ( PARTITION BY doc_id ORDER BY version DESC, row_id DESC @@ -90,6 +97,7 @@ JOIN curation_labels AS l ON l.doc_id = d.doc_id WHERE d.rn = 1 ORDER BY d.doc_id; ``` + The result contains documents **10, 20 and 30**, with labels **cat, dog and cat**. Document 40 is excluded because this particular task requires a label. @@ -108,7 +116,7 @@ This example has two cats and one dog. That distribution may be appropriate for exploration, but it does not establish a representative evaluation set. [Profiling](/curation/aggregate) provides the counts to inspect. -[Sampling](/curation/sampling) and [ranking](/curation/windowing) help you +[Statistical Sampling](/curation/statistical-sampling) and [ranking](/curation/windowing) help you adjust the selection without changing the original records. ## Save and reuse the result {#next} diff --git a/docs/web/curation/inspect-datasets.mdx b/docs/web/curation/inspect-datasets.mdx new file mode 100644 index 000000000..845fa3a4c --- /dev/null +++ b/docs/web/curation/inspect-datasets.mdx @@ -0,0 +1,241 @@ +--- +title: "Inspect Datasets" +sidebarTitle: "Inspect Datasets" +description: "Query a table, a HuggingFace dataset, or a dataset in object storage the same way, with plain SELECT, WHERE, projection and LIMIT." +icon: database +keywords: ["select", "where", "filter", "projection", "limit", "huggingface", "storage integration", "sql", "inspect"] +availability: + embedded: unavailable + enterprise: available +--- + +The same `SELECT` statement inspects three kinds of source: a table +already in your database, a HuggingFace dataset, or a dataset in object +storage -- once a [storage integration](/management/storage-integration) +covers the latter two. Nothing is downloaded or imported until you choose +to import it. + +## The basics: project, filter, limit {#basics} + +A table name, a HuggingFace URI, and an object-storage URI all work the +same way after `FROM`: + + +```sql SQL icon="database" +SELECT id, text +FROM documents +WHERE text IS NOT NULL +LIMIT 100 +``` + + +- **Project** -- name the columns you need (`id, text`) instead of + `SELECT *`, especially for a source with large or many columns. +- **Filter** -- `WHERE` narrows rows before they come back; combine + predicates with `AND`/`OR` the same as any other table. +- **Limit** -- `LIMIT n` caps how many rows return. It bounds the result, + not the read: a remote source is still fetched at file or row-group + granularity, so a small `LIMIT` on a source with large files or row + groups can still touch more data than the row count suggests. + +The rest of this page swaps `documents` for a HuggingFace or +object-storage source -- the `SELECT`/`WHERE`/`LIMIT` syntax above doesn't +change. + +## Inspect a HuggingFace dataset {#huggingface} + +A single-quoted HuggingFace dataset URI works directly in a SQL `FROM` +clause, the same as a table name -- no separate download, no intermediate +file on disk: + + +```sql SQL icon="database" +SELECT id, text +FROM 'hf://datasets/owner/repo/data/train-*.parquet' +WHERE text IS NOT NULL +LIMIT 100 +``` + + + +```python Python icon="python" +reader = db.execute_query(""" + SELECT id, text + FROM 'hf://datasets/owner/repo/data/train-*.parquet' + WHERE text IS NOT NULL + LIMIT 100 +""") +sample = reader.read_all().to_pylist() +``` + + +The URI is `hf://datasets//[@]/`. `` can +be one Parquet file, a directory, or a glob: `*` matches within one +directory, `**` matches across directories, and a repository root selects +every Parquet file beneath it. Select a dataset configuration or split by +including it in the path. The default revision is `main`; each statement +resolves the revision to a commit once, so every worker reads the same +snapshot. This source reads Parquet files -- it does not run a dataset's +own generation scripts, and it does not compute embeddings or build +indexes, so [chunk](/curation/chunking), embed, or index the result as a +separate step, the same as data from any other source. + + +Files matched by one statement must have compatible schemas, and an +unmatched path is an error rather than a silent fallback to a different +split. Nested Parquet values come through as-is; a floating-point list is +not automatically converted into a fixed-size vector column. + + +## Inspect a dataset in object storage {#object-storage} + +An `s3://`, `gs://` or `az://` prefix covered by a storage integration +reads an existing **Lance** dataset at that prefix, the same way as a +managed table: + + +```sql SQL icon="database" +SELECT id, text +FROM 's3://customer-data/raw/documents.lance' +WHERE text IS NOT NULL +LIMIT 100 +``` + + +This reads a dataset another process already wrote in Lance format, not +an arbitrary file format -- there is no Parquet-style reader for cloud +storage the way there is for `hf://`. See +[Storage Integration](/sql/ddl/storage-integration#read-import) for every +provider's setup. + +## Access a private repository or bucket {#access} + +A private HuggingFace repository, one subject to HuggingFace's +authenticated rate limits, or any non-public bucket needs a +[storage integration](/management/storage-integration) covering it. For +HuggingFace that integration is bound to a token +[Secret](/management/secret); for a non-public S3 bucket it can instead be +an IAM role integration, which needs no Secret at all -- see +[AWS S3](/ingestion/define-storage-integration#aws). + + +```python Python icon="python" +db.create_secret("hf_token", "") + +# create_storage_integration is not in a released SDK yet; use the SQL +# form below until it ships. +db.execute_query(""" + CREATE STORAGE INTEGRATION private_hub + STORAGE_PROVIDER = 'HUGGINGFACE' + STORAGE_PREFIX = 'hf://datasets/owner/private/data/' + HUGGINGFACE_TOKEN_SECRET = hf_token +""").read_all() + +reader = db.execute_query( + "SELECT * FROM 'hf://datasets/owner/private/data/*.parquet' LIMIT 10" +) +``` + +```sql SQL icon="database" +CREATE SECRET hf_token TYPE = GENERIC_STRING SECRET_STRING = '' + +CREATE STORAGE INTEGRATION private_hub + STORAGE_PROVIDER = 'HUGGINGFACE' + STORAGE_PREFIX = 'hf://datasets/owner/private/data/' + HUGGINGFACE_TOKEN_SECRET = hf_token + +SELECT * FROM 'hf://datasets/owner/private/data/*.parquet' LIMIT 10 +``` + + +{/* +Draft for the storage-integration SDK release (#4618, #4775). Keep this +section unpublished until create_storage_integration ships in a release; it +is not in v0.41.0. + + +```python Python icon="python" +db.create_secret("hf_token", "") + +db.create_storage_integration( + "private_hub", "hf://datasets/owner/private/data/", + storage_provider="HUGGINGFACE", + huggingface_token_secret="hf_token", +) + +reader = db.execute_query( + "SELECT * FROM 'hf://datasets/owner/private/data/*.parquet' LIMIT 10" +) +``` + +*/} + +A query never names the integration: the planner matches the most specific +`STORAGE_PREFIX` that covers the URI being read, across every integration +the caller has `USAGE` on. A HuggingFace integration always needs +`HUGGINGFACE_TOKEN_SECRET`; creating one without it is rejected. For public +access, register no integration for that prefix at all -- an `hf://` read +that matches no integration is anonymous, with no environment-variable +fallback. See +[Storage Integration](/management/storage-integration) for every provider +and the full credential model. + +## Import into a table {#import} + +Once you've inspected a source and it looks right, `CREATE TABLE ... AS +SELECT` imports it: + + +```sql SQL icon="database" +CREATE TABLE imported AS +SELECT * +FROM 'hf://datasets/owner/repo/data/train-*.parquet' +``` + + + +```python Python icon="python" +db.execute_query(""" + CREATE TABLE imported AS + SELECT * FROM 'hf://datasets/owner/repo/data/train-*.parquet' +""").read_all() +table = db.open_table("imported") +``` + + +This `CREATE TABLE AS SELECT` runs as a distributed import when the +deployment has an available plan-executor fleet: the planner assigns +disjoint file and row-group ranges to workers, each worker writes +uncommitted Lance files directly to the destination, and a coordinator +commits the completed table from their transaction metadata once every +worker finishes. A query with a global limit, aggregation or join keeps +its usual coordination; a small import can run as one local task without a +fleet. The table becomes queryable only after that final commit -- +nothing partial is ever visible, and a failed or cancelled import can +resume the same durable job from its retained attempt rather than +restarting from nothing. To start over after a failed one-off import +instead, drop the partial table and rerun the statement. + + +Importing requires a native database with `database_manifest_enabled`. +Combining a HuggingFace source with a WAL-backed destination table in one +CTAS is rejected, since the import cannot publish a base-only read that +omits the destination's unflushed data. + + +## What to read next {#next} + + + + The credential object behind private repository access. + + + Add embeddings or derived columns to the imported data. + + + Split long text or media fields after importing. + + + `CREATE TABLE AS SELECT` syntax and options in full. + + diff --git a/docs/web/curation/join.mdx b/docs/web/curation/join.mdx index 3306ca511..476bbbfed 100644 --- a/docs/web/curation/join.mdx +++ b/docs/web/curation/join.mdx @@ -27,7 +27,8 @@ a record; `doc_id` identifies the document it describes. Run each statement separately in a scratch database or namespace. Create these tables once for the whole section, using fresh names if they already exist. -```sql + +```sql SQL icon="database" CREATE TABLE curation_documents ( row_id BIGINT, doc_id BIGINT, version BIGINT, source VARCHAR, caption VARCHAR, score DOUBLE @@ -44,6 +45,7 @@ CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); INSERT INTO curation_labels VALUES (10, 'cat'), (20, 'dog'), (30, 'cat'); ``` + `score` is a sample quality score, not a search result score. Document 10 has two versions. Document 30 has two records at the same version. Document 40 @@ -55,12 +57,14 @@ has no label. These cases let you check the effect of each operation. An inner join keeps matching records: -```sql + +```sql SQL icon="database" SELECT d.row_id, d.doc_id, l.label FROM curation_documents AS d JOIN curation_labels AS l ON l.doc_id = d.doc_id ORDER BY d.row_id; ``` + This returns **5 rows**: both records for document 10, one for document 20, and both records for document 30. To produce one row per document, @@ -71,13 +75,15 @@ and both records for document 30. To produce one row per document, A left join keeps every record from the left table and fills missing right-side values with `NULL`. Add `WHERE l.doc_id IS NULL` to return only unlabeled documents: -```sql + +```sql SQL icon="database" SELECT DISTINCT d.doc_id FROM curation_documents AS d LEFT JOIN curation_labels AS l ON l.doc_id = d.doc_id WHERE l.doc_id IS NULL ORDER BY d.doc_id; ``` + The result is **document 40**. You might send it for annotation, retain it for an unlabeled-data workflow, or exclude it from a task that requires labels. @@ -87,17 +93,49 @@ an unlabeled-data workflow, or exclude it from a task that requires labels. This example joins `curation_documents.doc_id` to `curation_labels.doc_id`. First check whether the label table contains more than one row per document: -```sql + +```sql SQL icon="database" SELECT doc_id, count(*) AS labels FROM curation_labels GROUP BY doc_id HAVING count(*) > 1; ``` + The example returns no rows. If your data returns duplicates, decide whether they represent valid multiple labels or records that need consolidation. A join does not enforce one-to-one matching. +## Call a Function across the join {#functions} + +A [Function](/curation/create-function) can read columns from either side +of a join, the same as any other expression -- it runs once the join has +matched rows, not before. Register `caption_quality` first: + + +```python Python icon="python" +from lancedb import udf + +@udf +def caption_quality(caption: str) -> float: + ... # score the caption, e.g. with a lightweight heuristic or model + +db.create_function_async(caption_quality).wait() +``` + +```sql SQL icon="database" +SELECT d.row_id, l.label, caption_quality(d.caption) AS quality +FROM curation_documents AS d +JOIN curation_labels AS l ON l.doc_id = d.doc_id +WHERE d.caption IS NOT NULL +ORDER BY d.row_id; +``` + + +Scoring after the join, rather than before, means `caption_quality` only +runs on rows that actually matched a label -- a document with no label +never pays for the Function call. + ## Join tables across namespaces {#namespaces} Use a table's qualified path to address it in another @@ -121,41 +159,18 @@ Check the row count, unmatched keys and duplicate matches before using a joined dataset. Select only the columns needed for the next step, especially when source records include large media or embedding columns. -Use [Explain a query plan](/search/explain) to see how the query reads and +Use [Query plans](/basics/sql#query-plans) to see how the query reads and combines data. Check the plan to see whether the query uses indexes and how it performs the join. An index on a key does not guarantee that the join will use it. ### Defer wide columns until after the join {#late-materialization} -When one side of a join carries a BlobV2 column, an embedding, or both, join -on a narrow key first -- `row_id`, `_rowid`, or another selective column -- -and project the wide columns only in the final select list, rather than -selecting them alongside the join condition. The planner can then defer -reading those columns until after the join has already narrowed down which -rows survive, instead of reading them for every candidate row. - -`frames` is wide: a BlobV2 `image` and a vector `embedding` alongside its -key. `selected` is narrow: the frame IDs an earlier curation step already -kept, such as a sample or a dedupe result. Join on the key, project the wide -columns last: - -```sql -SELECT s.frame_id, f.image, f.embedding -FROM selected AS s -JOIN frames AS f ON f.frame_id = s.frame_id -``` - -`selected` narrows the row set before `image` or `embedding` is ever touched -on the `frames` side, rather than reading every row's blob and vector just -to discard most of them after the join. - -This is query planning the optimizer may or may not apply to a given query, -not a guarantee from writing the join this way. Confirm it per query with -[`EXPLAIN`](/search/explain): a plan containing `RemoteTake` deferred the -wide read; a plan without it read the wide columns eagerly, even for a query -shaped exactly like the one above. See -[Late materialization for wide columns](/sql/dql/join#late-materialization) -in the SQL reference for the underlying mechanism. +When one side of a join carries a BlobV2 column, an embedding, or both, +join on a narrow key first and project the wide columns only in the +final select list, so the planner can defer reading them until after the +join has already narrowed down which rows survive. See +[Blob Late Materialization](/curation/blob-late-materialization) for the +mechanism, eligibility, and how to confirm it happened. ## Save the result or continue curating {#reference} diff --git a/docs/web/curation/selective-sampling.mdx b/docs/web/curation/selective-sampling.mdx new file mode 100644 index 000000000..f284abd22 --- /dev/null +++ b/docs/web/curation/selective-sampling.mdx @@ -0,0 +1,128 @@ +--- +title: "Selective Sampling" +sidebarTitle: "Selective Sampling" +description: "Fetch specific rows by row ID, row address or offset instead of drawing a random fraction." +icon: crosshairs +keywords: ["sampling", "row id", "row address", "offset", "take", "rowid", "rowaddr", "rowoffset"] +availability: + embedded: available + enterprise: available +--- + +Selective sampling fetches specific, already-known rows -- by row ID, row +address or offset -- rather than drawing a random fraction of the table. +Use it to re-fetch rows a previous query identified, resume from a saved +position, or pull a batch by index for a data loader. For a random subset +instead, see [Statistical Sampling](/curation/statistical-sampling). + +LanceDB exposes three ways to address a row: + +| Identifier | Stability | Typical source | +| --- | --- | --- | +| Row ID (`_rowid`) | Stable across compaction, with [stable row IDs](/basics/guarantees) enabled | A previous query's result, or `function_errors()` | +| Row address (`_rowaddr`) | Changes on compaction; encodes `(fragment_id << 32) \| row_offset` | A previous query's result, when you need the physical location | +| Offset | Table-wide position; **not** stable -- a row's offset shifts when an earlier row is deleted | `range(len(table))`, since every valid offset is known in advance | + +## From Python {#python} + +The SDK takes a list of row IDs or offsets directly, without going through +SQL: + + +```python Python icon="python" +# By row ID -- from a previous search or scan that selected "_rowid" +rows = tbl.take_row_ids([1001, 1002, 1005]).to_arrow() + +# By offset -- the full range is always [0, len(tbl)) +rows = tbl.take_offsets([0, 1, 2]).to_arrow() +``` + +```typescript TypeScript icon="square-js" +// By row ID -- from a previous search or scan that selected "_rowid" +const rowsById = await tbl.takeRowIds([1001n, 1002n, 1005n]).toArray(); + +// By offset -- the full range is always [0, tbl.countRows()) +const rowsByOffset = await tbl.takeOffsets([0, 1, 2]).toArray(); +``` + +```rust +use lancedb::query::ExecutableQuery; + +// By row ID -- from a previous search or scan that selected "_rowid" +let rows_by_id = tbl.take_row_ids(vec![1001, 1002, 1005]).execute().await?; + +// By offset -- the full range is always [0, tbl.count_rows().await?) +let rows_by_offset = tbl.take_offsets(vec![0, 1, 2]).execute().await?; +``` + + +Both methods return a query builder; call `.to_arrow()`, `.to_list()` or +similar to execute it. + + +The guarantees for row IDs below apply to SDK releases containing +[the ordering fix in #4826](https://github.com/lancedb/lancedb/pull/4826). +Earlier releases may collapse repeated IDs and return rows in a different +order. + + +`take_row_ids` returns matching rows in the order of the input IDs and +preserves repeated IDs in both LanceDB Embedded and LanceDB Enterprise. For example, +`take_row_ids([1005, 1001, 1005])` returns row 1005, row 1001, then row 1005 +again if both IDs exist. Missing or deleted IDs are omitted. This supports +sampling with replacement. In Rust, an explicit nonempty +`QueryBase::order_by` list overrides the requested order; limits and offsets +apply after restoring repeated rows. + +`take_offsets` also preserves repeated offsets, but does not guarantee +input order. It tracks `_rowoffset` internally to restore repeated rows +and drops that column from the output unless you explicitly `select` it. +Add `_rowoffset` to your selection when you need to align a `take_offsets` +result with the input offsets. + + +Ordered takes by row ID collect all matching batches, combine them into one +batch and reorder the rows before returning output batches. Even +`to_batches(max_batch_length=1)` only limits the returned batch size; it +does not bound working memory. For large requests or rows with large +column values, split the input IDs into smaller requests and use +`.select(...)` to fetch only the columns you need. + + +Offsets are mostly useful for sampling: the valid range is always +`[0, len(table))`, so you can draw a random sample of offsets without +reading the table first. Row IDs require you to already have them, from an +earlier query's `_rowid` column -- but unlike offsets, a row ID keeps +addressing the same logical row even after compaction, as long as the +table has stable row IDs enabled. + +## From SQL {#sql} + +The same three identifiers are available as +[pseudo-columns](/sql/data-types#pseudo-columns) -- select or filter on +them like any other column: + + +```sql SQL icon="database" +-- By row ID +SELECT * FROM documents WHERE _rowid IN (1001, 1002, 1005); + +-- By row address +SELECT * FROM documents WHERE _rowaddr IN (4294967296, 4294967297); + +-- Including the identifier in the result, to save for a later take +SELECT _rowid, * FROM documents WHERE score > 0.9; +``` + + +There is no dedicated Python method for taking by row address -- use +`.where("_rowaddr IN (...)")` on the SDK query builder, or the SQL form +above, since the expression language is the same either way. + +## Related guides {#reference} + +[Query plans](/basics/sql#query-plans) show whether a row-ID or offset +filter reads the whole table or seeks directly to the requested rows. See +[Statistical Sampling](/curation/statistical-sampling) for a random +fraction instead of specific rows, and [Permutation](/training/permutation) +for shuffled, batched reads through the Python SDK. diff --git a/docs/web/curation/sampling.mdx b/docs/web/curation/statistical-sampling.mdx similarity index 69% rename from docs/web/curation/sampling.mdx rename to docs/web/curation/statistical-sampling.mdx index 82f1c1ecb..fc43bff12 100644 --- a/docs/web/curation/sampling.mdx +++ b/docs/web/curation/statistical-sampling.mdx @@ -1,22 +1,21 @@ --- -title: "Sampling" -sidebarTitle: "Sampling" -description: "Choose a sample for exploration or evaluation and preserve the selected records when reproducibility matters." +title: "Statistical Sampling" +sidebarTitle: "Statistical Sampling" +description: "Draw a random subset of a table with SQL TABLESAMPLE, by rows or by fragments." icon: dice -keywords: ["sampling", "tablesample", "subset", "eval set", "reproducible", "shuffle"] +keywords: ["sampling", "tablesample", "bernoulli", "system", "repeatable", "random", "eval set"] availability: embedded: unavailable enterprise: available --- -import { PySampleDataset } from '/snippets/curation_sampling.mdx'; - -Sampling selects records from a larger table. Use it to explore unfamiliar -data, run a smaller experiment, or prepare an evaluation dataset. Enterprise -SQL provides `TABLESAMPLE` for selecting a percentage or number of rows. - -This page covers Enterprise SQL sampling and a complete -[Python SDK example](#training) that runs locally. +Statistical sampling draws a random subset of a table's rows using SQL's +`TABLESAMPLE` clause, attached directly to a table in `FROM`. Use it to +explore unfamiliar data, run a smaller experiment, or estimate aggregate +statistics without reading every row. For a random subset through the +Python SDK instead -- in Embedded or Enterprise -- see +[Permutation](/training/permutation). To select specific, known rows +rather than a random fraction, see [Selective Sampling](/curation/selective-sampling). ## Example data {#example-data} @@ -32,7 +31,8 @@ a record; `doc_id` identifies the document it describes. Run each statement separately in a scratch database or namespace. Create these tables once for the whole section, using fresh names if they already exist. -```sql + +```sql SQL icon="database" CREATE TABLE curation_documents ( row_id BIGINT, doc_id BIGINT, version BIGINT, source VARCHAR, caption VARCHAR, score DOUBLE @@ -49,6 +49,7 @@ CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); INSERT INTO curation_labels VALUES (10, 'cat'), (20, 'dog'), (30, 'cat'); ``` + `score` is a sample quality score, not a search result score. Document 10 has two versions. Document 30 has two records at the same version. Document 40 @@ -60,10 +61,12 @@ has no label. These cases let you check the effect of each operation. A percentage selects a fraction of the source; `ROWS` requests a row count: -```sql + +```sql SQL icon="database" SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (50); SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (3 ROWS); ``` + A percentage sample does not guarantee an exact number of rows. Use a count when the desired sample size is the main constraint, and inspect the result @@ -82,13 +85,15 @@ Choose a method according to how records should be selected: | `BERNOULLI` (default) | Select individual rows | When records should be sampled independently of their storage fragments | | `SYSTEM` | Select whole Lance fragments | When reducing reads matters and grouping by fragment is acceptable | -```sql + +```sql SQL icon="database" SELECT row_id, doc_id FROM curation_documents TABLESAMPLE BERNOULLI (50); SELECT row_id, doc_id FROM curation_documents TABLESAMPLE SYSTEM (50); ``` + If write order groups records by label, date or source, a fragment sample can reflect that grouping. On a tiny table stored in one fragment, it may include @@ -99,19 +104,23 @@ represent rare groups; check that the resulting sample covers the groups you nee A seed requests a repeatable draw: -```sql + +```sql SQL icon="database" SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (50) REPEATABLE (42); ``` + Keep the source data and sampling configuration fixed when comparing draws. For a lasting evaluation set, save the selected records rather than relying on a seed to preserve membership as the source changes: -```sql + +```sql SQL icon="database" CREATE TABLE curation_eval AS SELECT * FROM curation_documents TABLESAMPLE (50) REPEATABLE (42); ``` + Create this output once with a fresh name and keep it unchanged. Record the source version and selection policy. Sampling records independently can place @@ -128,43 +137,50 @@ about 1% probability, not 10%. To sample documents while retaining their available labels, sample only the document table: -```sql + +```sql SQL icon="database" SELECT curation_documents.row_id, curation_documents.doc_id, l.label FROM curation_documents TABLESAMPLE (50) JOIN curation_labels AS l ON l.doc_id = curation_documents.doc_id; ``` + This samples source records, not distinct documents. If you need to sample the result of a join or deduplication, first save that result as a table suitable for sampling. `TABLESAMPLE` cannot be applied directly to a subquery result. -## Sample without SQL {#training} +## Apply a Function to a sample {#functions} -The Python SDK provides a permutation builder for selecting and ordering rows -in LanceDB Embedded and LanceDB Enterprise. A split selects a subset; a shuffle changes the order -in which records are read. `Permutation.identity(table)` retains stored order. +Sample first, then call a [Function](/curation/create-function) only on +the rows you drew -- useful for trying an expensive Function on a subset +before running it over the whole table. Register `caption_quality` first: - + +```python Python icon="python" +from lancedb import udf -Install the Python SDK with `pip install lancedb`, save the program as -`sample_dataset.py`, and run `python sample_dataset.py`. It creates a temporary -local database with ten rows and reads a random split containing three rows. -The temporary database is removed when the program finishes. +@udf +def caption_quality(caption: str) -> float: + ... # score the caption, e.g. with a lightweight heuristic or model - -{PySampleDataset} - +db.create_function_async(caption_quality).wait() +``` -The program prints three distinct IDs. It uses a fixed seed, but does not -promise the same IDs across SDK versions or changes to the source dataset. +```sql SQL icon="database" +SELECT row_id, caption, caption_quality(caption) AS quality +FROM curation_documents TABLESAMPLE (50) +WHERE caption IS NOT NULL; +``` + - - -For shuffled training reads, worker configuration and data loaders, see -[PyTorch Data Loader](/training/data-loading). +The Function runs only on the sampled rows, not the whole table -- a quick +way to check a Function's output, cost or latency before committing to a +full [column refresh](/feature-engineering/refresh-column). ## Related guides {#reference} Count the sampled rows and [inspect their distribution](/curation/aggregate) before using them. Preserve the selected data when the exact membership matters. -See [SQL sampling](/sql/dql/sampling) for syntax and restrictions. +See [SQL sampling](/sql/dql/sampling) for the complete syntax and restrictions, +and [Permutation](/training/permutation) for a random subset through the +Python SDK. diff --git a/docs/web/curation/vend-secret.mdx b/docs/web/curation/vend-secret.mdx new file mode 100644 index 000000000..cdebc0b8d --- /dev/null +++ b/docs/web/curation/vend-secret.mdx @@ -0,0 +1,227 @@ +--- +title: "Vend a Secret to a Function" +tag: "Early access" +sidebarTitle: "Vend Secret" +description: "Bind a Secret to a Function by reference, and how its value reaches running code during SQL evaluation and refresh." +icon: key +keywords: ["secret", "udf", "function", "credential", "api key", "env_variable", "refresh"] +availability: + embedded: unavailable + enterprise: available +--- + +Early access + +A Function that calls an external service needs a credential without +putting it in the function's source -- see +[Create a Function](/curation/create-function#remote) for how to register +one. A [Secret](/management/secret) is a database-scoped named credential: +you create it once, then bind it *by reference* -- by name, not by value -- +when you register the Function that needs it. + +## Specify the Secret when you register the Function {#specify} + +Store the credential, then bind it to an environment variable the function's +code already reads: + + +```python Python icon="python" +import os +from lancedb import EnvVarSecret, udf + +db.create_secret("embedding-api-key", os.environ["EMBEDDING_API_KEY"]) + +@udf +class embed_remote: + def __init__(self, model: str = "text-embedding-3-small"): + import os + from openai import OpenAI + + self.client = OpenAI(api_key=os.environ["EMBEDDING_API_KEY"]) + self.model = model + + def __call__(self, text: str) -> list[float]: + response = self.client.embeddings.create(input=text, model=self.model) + return response.data[0].embedding + +version = db.create_function_async( + embed_remote, + secrets=[ + EnvVarSecret(secret_name="embedding-api-key", env_variable="EMBEDDING_API_KEY") + ], +).wait() +``` + + +The function's own code never names the Secret -- it reads +`EMBEDDING_API_KEY` the same way it would outside LanceDB. The binding, in +`secrets=[...]`, is what connects that variable to the stored credential. +It is checked for shape at registration (valid variable name, not reserved, +not repeated) but not resolved yet: the Secret does not have to exist until +a column actually uses this Function version, so you can create the +Function and its Secret in either order. + +## Hugging Face models {#hugging-face} + +For a model loaded from the Hugging Face Hub, store the token as a Secret +and bind it to the variable the Hub client reads. Use a class Function so +the model is loaded once per remote instance rather than once per row: + +```python +import os + +from lancedb import EnvVarSecret, col, udf + +db.create_secret("hf-token", os.environ["HF_TOKEN"]) + + +@udf( + name="embed_text", + pip=["sentence-transformers==3.3.1"], +) +class EmbedText: + def __init__(self, revision: str): + from sentence_transformers import SentenceTransformer + + self.model = SentenceTransformer( + "sentence-transformers/all-MiniLM-L6-v2", + revision=revision, + ) + + def __call__(self, text: str) -> list[float]: + return self.model.encode(text).tolist() + + +embed_fn = db.create_function( + EmbedText, + secrets=[EnvVarSecret(secret_name="hf-token", env_variable="HF_TOKEN")], +) + +table = db.open_table("documents") +table.add_columns( + { + "embedding": embed_fn( + text=col("text"), + revision="", + ) + } +) +table.refresh_column("embedding") +``` + +A decorated class calls `__init__` once per remote instance and `__call__` +for each row or batch. The class's `__init__` parameters are binding +initialization values, so `revision` is fixed for this binding and the +model is reused for all rows handled by that instance. Instances are not +shared across workers. + +Use a full 40-character commit SHA for `revision`. A branch or tag can +move; a commit pins the model version. See the official Hugging Face +documentation for +[`HF_TOKEN`](https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hftoken) +and +[downloading a specific revision](https://huggingface.co/docs/huggingface_hub/guides/download#revision). + +`HF_TOKEN` authenticates Hub requests, but a cached model and a pinned +revision are not a guarantee of offline execution. The Hub client may +still request metadata or missing files, and authentication does not +guarantee that requests will avoid rate limits. + +## How the value reaches a running evaluation {#delivery} + +The Secret's value is resolved fresh for each job, never read once and +cached in the Function's definition: + +| Step | What happens | +| --- | --- | +| `add_columns` with this Function version | Every bound Secret must now exist. The column pins this exact version, not a value. | +| A refresh starts -- `refresh_column`, or a materialized view's refresh | Every bound Secret must still exist, checked before any row is computed. | +| The job captures each bound Secret's current value | LanceDB looks up the value once, when the job starts, and sets it as that environment variable for every row the job evaluates, including its retries. No other environment variable carries over. | + +This is why rotating a Secret needs no new Function version and no column +change: `alter_secret` changes the value a *future* lookup returns. The +agent captures that value once, when a job starts, and reuses its own +captured copy for that job's full run and any of its retries -- a refresh +already running keeps the value it started with for every row, and only a +job that starts *after* the rotation sees the new one. + +### Rotate and revoke {#rotation} + +`alter_secret` and `drop_secret` never interrupt work in progress, so a +routine rotation cannot fail a backfill halfway through: + +| Action | Running jobs | Next job | New Function version? | +| --- | --- | --- | --- | +| `alter_secret` | A running job and its retries keep the value captured at start; only a new job gets the latest value | Uses the latest value | No | +| `drop_secret` | Run to completion on the last value | Refused, naming the Secret | No | +| Revoke the key at its provider | Fails on their next call to the provider | Fails until a new value is set | No | +| Re-create a dropped name | Keeps the dropped Secret's last value | Picks up the new Secret | No | + +Because a rotation creates no new Function version, it also reaches columns +pinned to a version registered before it. Binding a Function to a +*different* Secret or variable does register a new version, and existing +columns keep the binding they were declared with. + + +To stop a credential from being used **now**, revoke it at its provider, +for example by deleting the key in the OpenAI console. A value already +handed to a running job cannot be recalled. + + +`drop_secret` cannot be undone, and it does not check for Functions still +bound to the Secret. + + +Reading a column this Function already filled needs only `SELECT` on the +table. No Function runs on the read path, so a reader needs no grant on the +Function or its Secrets -- only someone triggering a refresh does. + + +## Vending during SQL evaluation specifically {#sql} + +A computed column's expression and a `CREATE MATERIALIZED VIEW` query both +plan and execute as SQL, so a Function called from either one is vended its +Secrets the same way: at the evaluation that fills the column or refreshes +the view, not at declaration time. + + +```sql SQL icon="database" +CREATE MATERIALIZED VIEW frames_captioned AS +SELECT f.frame_id, caption(f.jpeg) AS caption +FROM frames f +``` + + +`caption` here is a Function bound to a Secret through the Python SDK when +it was registered -- SQL has no syntax for the binding itself, only for +calling the already-registered Function. The `CREATE MATERIALIZED VIEW` +statement's initial population, and every `REFRESH MATERIALIZED VIEW` +after it, each look up the bound Secret's current value independently. + +## Troubleshooting {#troubleshooting} + +**403 when adding or refreshing a Function column**: you need `USAGE` on +the Function *and* on every Secret it binds, in addition to the table +privilege. The error names the object you are missing. + +**The Function runs but its provider rejects the key**: a misspelled +*environment variable* cannot be caught at registration, because nothing +knows which variables a Function reads. Check that `env_variable` matches +what the Function's code reads, such as `EMBEDDING_API_KEY` above. + +## Related guides {#next} + + + + Write the function that reads the credential. + + + Create, rotate, list and drop the credential itself. + + + Grant and revoke privileges on a Secret. + + + Running the evaluation that vends the Secret. + + diff --git a/docs/web/curation/windowing.mdx b/docs/web/curation/windowing.mdx index 6cb5322d6..f467937da 100644 --- a/docs/web/curation/windowing.mdx +++ b/docs/web/curation/windowing.mdx @@ -1,6 +1,6 @@ --- -title: "Ranking and deduplication" -sidebarTitle: "Windowing" +title: "Ranking" +sidebarTitle: "Ranking" description: "Choose records with explicit ranking rules and deterministic tie handling." icon: chart-simple keywords: ["window", "deduplication", "row_number", "rank", "train test split", "per class"] @@ -27,7 +27,8 @@ a record; `doc_id` identifies the document it describes. Run each statement separately in a scratch database or namespace. Create these tables once for the whole section, using fresh names if they already exist. -```sql + +```sql SQL icon="database" CREATE TABLE curation_documents ( row_id BIGINT, doc_id BIGINT, version BIGINT, source VARCHAR, caption VARCHAR, score DOUBLE @@ -44,6 +45,7 @@ CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR); INSERT INTO curation_labels VALUES (10, 'cat'), (20, 'dog'), (30, 'cat'); ``` + `score` is a sample quality score, not a search result score. Document 10 has two versions. Document 30 has two records at the same version. Document 40 @@ -57,7 +59,8 @@ has no label. These cases let you check the effect of each operation. and `ORDER BY` determines which record comes first. This query selects the latest version of each document, using `row_id` to break ties: -```sql + +```sql SQL icon="database" WITH ranked AS ( SELECT *, row_number() OVER ( PARTITION BY doc_id ORDER BY version DESC, row_id DESC @@ -69,6 +72,7 @@ FROM ranked WHERE rn = 1 ORDER BY doc_id; ``` + This returns row IDs **2, 3, 5 and 6**. For document 30, rows 4 and 5 have the same version; the example deliberately chooses the larger `row_id`. @@ -84,7 +88,8 @@ because window functions are evaluated after the inner query's `WHERE` clause. Deduplicate first, then rank the labeled documents within each class: -```sql + +```sql SQL icon="database" WITH latest AS ( SELECT *, row_number() OVER ( PARTITION BY doc_id ORDER BY version DESC, row_id DESC @@ -104,13 +109,14 @@ FROM ranked WHERE class_rank <= 1 ORDER BY label; ``` + The result is **document 10 for cat and document 20 for dog**. Change the cap from `1` to the maximum number you want per class. A class with fewer records cannot supply the full cap. This selects by score, not at random. For a random subset, use -[sampling](/curation/sampling) instead of ordering by score or ID. +[sampling](/curation/statistical-sampling) instead of ordering by score or ID. ## Training and evaluation splits {#splits} @@ -130,7 +136,8 @@ evaluation population. `lag()` and `lead()` read neighboring rows in the specified order. For example, inspect how scores change across a document's records: -```sql + +```sql SQL icon="database" SELECT doc_id, row_id, score, lag(score) OVER ( PARTITION BY doc_id ORDER BY version, row_id @@ -138,6 +145,7 @@ SELECT doc_id, row_id, score, FROM curation_documents ORDER BY doc_id, version, row_id; ``` + The first record in each document has no previous score. In this dataset, row 2 follows a score of 0.80 and row 5 follows a score of 0.70. @@ -147,7 +155,7 @@ row 2 follows a score of 0.80 and row 5 follows a score of 0.70. Window operations can require sorting. Filter out records you do not need before ranking, and inspect the -[query plan](/search/explain) when cost matters. +[query plan](/basics/sql#query-plans) when cost matters. For cumulative counts, sums and other running summaries, use an aggregate with an explicit window order and frame. The diff --git a/docs/web/deployment/multicloud.mdx b/docs/web/deployment/multicloud.mdx new file mode 100644 index 000000000..5ce4e309e --- /dev/null +++ b/docs/web/deployment/multicloud.mdx @@ -0,0 +1,111 @@ +--- +title: "Multicloud" +sidebarTitle: "Multicloud" +description: "Keep deployment orchestration in your cloud while dispatching compute-heavy work, like GPU UDF execution, to run in a different cloud." +icon: "cloud" +keywords: ["multicloud", "cross-cloud", "gpu", "deployment"] +availability: + embedded: unavailable + enterprise: available +--- + +A LanceDB Enterprise deployment doesn't have to keep all of its compute in +one cloud. Orchestration -- query nodes, job coordination, the catalog -- +stays with your deployment in its own cloud account and region. Specific, +compute-heavy work, such as a GPU-bound Function's execution during a +refresh, can instead dispatch to run in a **different** cloud account, +region, or provider entirely, and send its results back to complete the job. + +## How it fits together {#architecture} + +Your deployment's job orchestration plans the work and tracks it to +completion the same way it would locally. The part that actually needs the +remote capacity -- a GPU UDF call, for example -- runs across a network +boundary instead of on a worker in your own cloud, and reports its result +back the same way a local worker would. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + subgraph P["Your cloud"] + direction TB + QN["Query node"] + Job["Job orchestration"] + end + + subgraph R["Remote cloud"] + direction TB + Exec["Compute execution
(e.g. GPU UDFs)"] + end + + QN --> Job + Job -- "dispatches work" --> Exec + Exec -- "results" --> Job + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Exec accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + subgraph P["Your cloud"] + direction TB + QN["Query node"] + Job["Job orchestration"] + end + + subgraph R["Remote cloud"] + direction TB + Exec["Compute execution
(e.g. GPU UDFs)"] + end + + QN --> Job + Job -- "dispatches work" --> Exec + Exec -- "results" --> Job + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Exec accent +``` + +
+ +## Why it matters {#why-it-matters} + +The cloud that's right for your primary deployment -- where your data and +other infrastructure already live -- isn't always the cloud with the best +GPU availability or pricing. Splitting orchestration from execution means +you don't have to choose: keep your deployment where it already makes +sense, and reach compute capacity elsewhere only for the work that +actually needs it, without migrating the deployment or operating that +remote capacity yourself. + +[Contact us](https://www.lancedb.com/contact) to learn more about setting +up cross-cloud execution for your deployment. + +## What to read next {#next} + + + + A common way the remote cloud's compute gets scheduled: as Slurm jobs. + + + How a refresh's resource class, part size and worker count adjust themselves. + + diff --git a/docs/web/deployment/monitoring.mdx b/docs/web/deployment/opentelemetry.mdx similarity index 96% rename from docs/web/deployment/monitoring.mdx rename to docs/web/deployment/opentelemetry.mdx index 7d19fc1a5..6391c72c6 100644 --- a/docs/web/deployment/monitoring.mdx +++ b/docs/web/deployment/opentelemetry.mdx @@ -1,6 +1,6 @@ --- title: "Monitor LanceDB with OpenTelemetry" -sidebarTitle: "Monitoring" +sidebarTitle: "OpenTelemetry" description: "Export LanceDB object store request counts, bytes, latency, errors, and throttles to any OpenTelemetry backend." icon: "chart-line" keywords: ["monitoring", "observability", "opentelemetry", "otel", "metrics", "prometheus", "object store"] @@ -38,14 +38,16 @@ The recorder is process-global and pull-based: your configured `MetricReader` co Install LanceDB with the `otel` extra to pull in the OpenTelemetry API, plus an OpenTelemetry SDK of your choice. The SDK is intentionally not bundled, so you configure it and its readers and exporters however your platform expects. -```bash + +```bash Bash icon="terminal" pip install "lancedb[otel]" opentelemetry-sdk opentelemetry-exporter-otlp-proto-grpc ``` + Call `instrument_lancedb_metrics()` once at startup, before opening any tables. It returns `True` when the recorder is installed and instruments are registered. + ```python Python icon="python" -import lancedb from lancedb.otel import instrument_lancedb_metrics from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import ( @@ -63,6 +65,7 @@ instrument_lancedb_metrics(provider) # Any object store activity from this point on is now recorded. db = lancedb.connect("s3://my-bucket/lancedb") ``` + If you omit `meter_provider`, LanceDB uses the global provider returned by `opentelemetry.metrics.get_meter_provider()`. @@ -74,10 +77,13 @@ If you omit `meter_provider`, LanceDB uses the global provider returned by `open Install the OpenTelemetry SDK and exporter in your application: -```bash + +```bash Bash icon="terminal" npm install @opentelemetry/sdk-metrics @opentelemetry/exporter-metrics-otlp-grpc ``` + + ```typescript TypeScript icon="square-js" import { connect, instrumentLanceDbMetrics } from "@lancedb/lancedb"; import { MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics"; @@ -92,6 +98,7 @@ instrumentLanceDbMetrics(provider); const db = await connect("s3://my-bucket/lancedb"); ``` + `instrumentLanceDbMetrics()` also accepts no arguments, in which case it uses the global provider from `@opentelemetry/api`. Calling it more than once is safe: instruments are created only on the first successful call. @@ -124,7 +131,7 @@ help integrating them with your monitoring dashboard. Tune ingestion, indexing, and query patterns once metrics highlight a hot spot. - + Configure the object store backends whose requests these metrics measure. diff --git a/docs/web/deployment/slurm.mdx b/docs/web/deployment/slurm.mdx new file mode 100644 index 000000000..87204d9b2 --- /dev/null +++ b/docs/web/deployment/slurm.mdx @@ -0,0 +1,131 @@ +--- +title: "Slurm" +sidebarTitle: "Slurm" +description: "Run LanceDB Enterprise's own pods as Slurm-scheduled jobs, and reach a Neocloud's GPU capacity through Slurm in the multicloud case." +icon: "server" +keywords: ["slurm", "scheduling", "gpu", "neocloud", "preemption", "multicloud"] +availability: + embedded: unavailable + enterprise: available +--- + +[Slurm](https://slurm.schedmd.com/) is the workload manager most GPU +clusters run to schedule and account for jobs -- queueing work across +shared nodes, enforcing fair-share and priority policies between teams, +and tracking GPU-hour usage per job. That makes it the de facto standard +in AI training infrastructure, where expensive GPU nodes are shared +across many training and data jobs instead of dedicated to one team. +GPU-focused cloud providers ("Neoclouds") such as CoreWeave and Nebius run +Slurm-based scheduling across their Kubernetes clusters for exactly this +reason. + +Slurm shows up for LanceDB Enterprise in two related ways. Its own pods -- +query nodes, plan executors, and background job workers alike -- can run +as Slurm-scheduled jobs rather than plain Kubernetes pods, under the same +scheduling and accounting as everything else on the cluster. And in the +[multicloud](/deployment/multicloud) case, when the remote cloud is a +Neocloud, Slurm is commonly how the dispatched GPU work actually gets +scheduled there. + +## How it fits together {#architecture} + +Scheduling LanceDB's pods through Slurm puts them under the same +scheduler as GPU training jobs, so the cluster's capacity is accounted +for consistently regardless of which one is using it -- Slurm's +fair-share and priority policies apply to LanceDB the same way they +apply to a training job, including preemption when training needs the +capacity back. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + subgraph P["Your cloud"] + direction TB + Job["Job orchestration"] + end + + subgraph N["Neocloud (e.g. CoreWeave, Nebius)"] + direction TB + Slurm["Slurm scheduler"] + Train["GPU training jobs"] + LDB["LanceDB Enterprise pods"] + Slurm --> Train + Slurm --> LDB + Train -.->|"can preempt"| LDB + end + + Job -- "dispatches GPU work" --> Slurm + LDB -- "results" --> Job + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Slurm accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + subgraph P["Your cloud"] + direction TB + Job["Job orchestration"] + end + + subgraph N["Neocloud (e.g. CoreWeave, Nebius)"] + direction TB + Slurm["Slurm scheduler"] + Train["GPU training jobs"] + LDB["LanceDB Enterprise pods"] + Slurm --> Train + Slurm --> LDB + Train -.->|"can preempt"| LDB + end + + Job -- "dispatches GPU work" --> Slurm + LDB -- "results" --> Job + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Slurm accent +``` + +
+ +## Why it matters {#why-it-matters} + +Most GPU infrastructure already runs Slurm for training. Deploying LanceDB +Enterprise into that same infrastructure, under the same scheduler, means +it can share capacity with training workloads safely -- queued, accounted, +and preemptible like everything else -- instead of requiring a separate, +dedicated pool of nodes carved out just for LanceDB. Combined with +[multicloud](/deployment/multicloud) dispatch, that makes it practical to +keep your primary deployment wherever it already lives and still reach +GPU capacity on a Neocloud built around Slurm, only for the work that +needs it. + +[Contact us](https://www.lancedb.com/contact) to learn more about running +LanceDB Enterprise on a Slurm-scheduled cluster. + +## What to read next {#next} + + + + The cross-cloud dispatch model this page's Neocloud case builds on. + + + The query, executor, cache and jobs fleets this scheduling applies to. + + diff --git a/docs/web/deployment/storage.mdx b/docs/web/deployment/storage.mdx deleted file mode 100644 index 50746d778..000000000 --- a/docs/web/deployment/storage.mdx +++ /dev/null @@ -1,418 +0,0 @@ ---- -title: "Storage configuration" -sidebarTitle: "Storage Configuration" -description: "Choose and configure local disk or object storage for your tables." -icon: database -keywords: ["storage", "s3", "gcs", "azure", "object store", "configuration", "deploy"] ---- - -This page is about LanceDB Embedded, where your connection chooses and -configures the storage backend. A LanceDB Enterprise deployment sets up its own -storage when it is deployed, so a `db://` connection passes none of these -options except an Azure storage account name. See -[LanceDB Enterprise](/enterprise) for how a deployment is set up. - -LanceDB's storage layer is built on modular, disk-first components. That design makes it flexible enough to run across local NVMe, EBS, EFS, and any object store that exposes an S3-compatible API. It also supports region-specific backends such as [Tencent COS](/storage/configuration#tencent-cos) and cache-acceleration layers such as [GooseFS](/storage/configuration#goosefs). - -Choosing a backend is a balance between latency, scalability, cost, and operational complexity. Use this guide to pick the right fit for your workload. - -## Choosing a backend {#choosing} - -![](/static/assets/images/storage/lancedb_storage_tradeoffs.png) - -When architecting your system, ask yourself: - -- **Latency**: How fast do I need results? What do the p50 and p95 look like? -- **Scalability**: Can I scale data volume and QPS easily? -- **Cost**: What is the all-in cost of storage plus serving? -- **Reliability/Availability**: How will replication and disaster recovery work? - -### Comparison {#comparison} - -Below is a high-level comparison ordered from lowest cost to lowest latency. - -### 1\. Object storage (S3, GCS, Azure Blob) {#1-object-storage-s3-gcs-azure-blob} -- **Latency**: Highest; expect hundreds of milliseconds and higher p95. -- **Scalability**: Effectively unlimited storage; QPS bound by concurrency limits. -- **Cost**: Lowest overall. -- **Reliability/Availability**: Highly available, backed by cloud SLAs. - -LanceDB separates storage and compute and writes immutable fragments, making it a strong fit for stateless, horizontally scalable deployments. - - -**Concurrent writers on S3** - -S3 and S3 Express now support atomic writes natively, so LanceDB handles concurrent writers against the same table out-of-the-box: no external commit coordinator is required. Bucket-level [server-side encryption with KMS](/storage/configuration#server-side-encryption-with-kms) and [S3 Express One Zone](/storage/configuration#s3-express) are also supported on this tier. - - -### 2\. File storage (EFS, GCS Filestore, Azure File) {#2-file-storage-efs-gcs-filestore-azure-file} -- **Latency**: Better than object storage; p95 under ~<100ms is typical. -- **Scalability**: High, but limited by provisioned IOPS per volume. -- **Cost**: More than object storage but cheaper than in-memory options; cold data can tier down automatically. -- **Reliability/Availability**: Highly available; replication/backup must be managed separately. - -Keep a copy of data in object storage for disaster recovery. If zero downtime is required, provision a second network file system with replicated data. - -### 3\. Third-party storage (e.g., MinIO, WekaFS) {#3-third-party-storage-e-g--minio-wekafs} - -- **Latency**: Similar to EFS; typically under <100ms. -- **Scalability**: Determined by the chosen vendor’s cluster sizing. -- **Cost**: Higher than S3; may edge above EFS at larger scales. -- **Reliability/Availability**: Shareable across many nodes; replication depends on vendor capabilities. - -### 4\. Block storage (EBS, GCP Persistent Disk, Azure Managed Disk) {#4-block-storage-ebs-gcp-persistent-disk-azure-managed-disk} -- **Latency**: Near-local performance; often <30ms. -- **Scalability**: Not shareable across instances; shard or copy data when scaling. -- **Cost**: Higher than networked file systems, plus potential I/O charges. -- **Reliability/Availability**: Persists through instance restarts; backups and sharding must be managed. - -### 5\. Local storage (SSD, NVMe) {#5-local-storage-ssd-nvme} -- **Latency**: Fastest; p95 often under <10ms. -- **Scalability**: Hard to scale in cloud environments; requires sharding or additional copies for higher QPS. -- **Cost**: Highest; tightly coupling compute and storage makes horizontal scaling difficult. -- **Reliability/Availability**: Data is tied to the instance; backups must be rigorous. - -Use local disk only when you need extremely low latency and are comfortable owning the operational overhead. - -### File-format choices that interact with the backend {#file-format-choices} - -A few `storage_options` keys shape new tables in ways that depend on the backend you picked above. They are documented in full on [below](#new-table-configuration); the architecture-level summary is: - -- `new_table_enable_v2_manifest_paths` matters most on object stores, where opening a table with many versions is dominated by listing cost. Leave it off for backward compatibility with clients older than LanceDB 0.10.0. -- `new_table_enable_stable_row_ids` keeps row IDs stable across compaction, delete, and merge. The choice is independent of the backend but affects any system that joins on row ID. -- `new_table_data_storage_version` selects the on-disk format. The default `stable` is recommended for all new tables; pick `legacy` only when older readers must keep working. - -import { - PyStorageAzureAccount, - PyStorageAzureSas, - PyStorageConnectAzure, - PyStorageConnectGcs, - PyStorageConnectS3, - PyStorageConnectTimeout, - PyStorageGcsServiceAccount, - PyStorageS3Express, - PyStorageS3Minio, - PyStorageS3SseKms, - PyStorageTableTimeout, - PyStorageTigrisConnect, - PyStorageCosConnect, - PyStorageGoosefsConnect, - TsStorageAzureAccount, - TsStorageAzureSas, - TsStorageConnectAzure, - TsStorageConnectGcs, - TsStorageConnectS3, - TsStorageConnectTimeout, - TsStorageGcsServiceAccount, - TsStorageS3Express, - TsStorageS3Minio, - TsStorageS3SseKms, - TsStorageTableTimeout, - TsStorageTigrisConnect, - TsStorageGoosefsConnect, -} from '/snippets/storage.mdx'; - -### Configuring a backend {#configuring} - - -**LanceDB Enterprise storage configuration** - -In LanceDB Enterprise, you connect with `db://...` and the cluster owns the storage credentials, so `storage_options` are not passed at runtime. Cloud auth is set at deployment time. For federated databases, the namespace service vends per-request credentials automatically. See the [quickstart](/quickstart), [Enterprise overview](/enterprise/), and [Kubernetes deployment guide](/enterprise/deployment/kubernetes) for the Enterprise flow. - - -### Object stores {#object-stores} - -LanceDB supports AWS S3 (and compatible stores), Azure Blob Storage, and Google Cloud Storage. The URI scheme in your `connect` call selects the backend. - - - - {PyStorageConnectS3} - - - {TsStorageConnectS3} - - - - - - {PyStorageConnectGcs} - - - {TsStorageConnectGcs} - - - - - - {PyStorageConnectAzure} - - - {TsStorageConnectAzure} - - - -### Configuration options {#configuration-options} - -When running inside the target cloud with correct IAM bindings, LanceDB often needs no extra configuration. When running elsewhere, provide credentials via environment variables or `storage_options`. - - - - {PyStorageConnectTimeout} - - - {TsStorageConnectTimeout} - - - - -**Storage option casing** - -Keys are case-insensitive. Use lowercase in `storage_options` and uppercase in environment variables. - - -Table-level `storage_options` inherit every key from the connection and override on a per-key basis. Pass them to `create_table` or `open_table` for options that should apply to a single table: - - - - {PyStorageTableTimeout} - - - {TsStorageTableTimeout} - - - - -**Inspect a table's own options** - -On `AsyncTable`, `await table.initial_storage_options()` returns the options passed when the table was opened, and `await table.latest_storage_options()` returns them after any provider-driven refresh. Neither includes what the table inherits from its connection's `storage_options`, which still apply. The deprecated `table.storage_options()` method will be removed in a future release. - - -#### General object store options {#general-object-store-options} - -| Key | Description | -| :-- | :-- | -| `allow_http` | Allow non-TLS connections. | -| `allow_invalid_certificates` | Skip certificate validation for TLS connections. | -| `connect_timeout` | Timeout for the connect phase. | -| `timeout` | Timeout for the full request. | -| `user_agent` | User agent string sent with requests. | -| `proxy_url` | Proxy URL to route requests through. | -| `proxy_ca_certificate` | PEM-formatted CA certificate for proxy connections. | -| `proxy_excludes` | Comma-separated hosts that bypass the proxy (domains or CIDR). | -| `download_retry_count` | Number of retries when downloading objects. | -| `client_max_retries` | Maximum retries for object-store client requests. | -| `client_retry_timeout` | Total retry timeout (seconds) for object-store client requests. | - - -**Option support varies by backend** - -These are commonly used options. Cloud-specific keys (for example `region`, `endpoint`, `service_account`, and Azure credential keys) are backend-dependent and can be provided in `storage_options` as needed. - - -#### New table configuration {#new-table-configuration} - -These options control the Lance file format and features used when creating new tables. Pass them via `storage_options` at connection or table level. They are evaluated only at table creation; setting them on an existing connection does not rewrite or alter tables that already exist. - -| Key | Values | Default | Description | -| :-- | :-- | :-- | :-- | -| `new_table_data_storage_version` | `legacy`, `stable` | `stable` | Lance file format version for new tables. Use `legacy` for backward compatibility with older clients, or `stable` for the current format with better performance. | -| `new_table_enable_v2_manifest_paths` | `true`, `false` | `false` | Use v2 manifest path naming. Requires LanceDB >= 0.10.0 to read. | -| `new_table_enable_stable_row_ids` | `true`, `false` | `false` | Keep row IDs stable across compaction, delete, and merge operations. | - -```mermaid -flowchart TD - A[Creating a new table] --> B{Need backward compatibility\nwith older LanceDB clients?} - B -->|Yes| C[new_table_data_storage_version: legacy] - B -->|No| D[new_table_data_storage_version: stable\nDefault — recommended] - D --> E{Need stable row IDs\nacross compaction and deletes?} - E -->|Yes| F[new_table_enable_stable_row_ids: true] - E -->|No| G[Default: false] - D --> H{All clients on LanceDB >= 0.10.0?} - H -->|Yes| I[new_table_enable_v2_manifest_paths: true] - H -->|No| J[Default: false] -``` - - -```python Python icon="python" -import lancedb - -# Set the Lance file format version at connection level -db = lancedb.connect( - "s3://bucket/path", - storage_options={ - "new_table_data_storage_version": "stable", - }, -) -``` - -```typescript TypeScript icon="square-js" -import * as lancedb from "@lancedb/lancedb"; - -// Set the Lance file format version at connection level -const db = await lancedb.connect("s3://bucket/path", { - storageOptions: { - newTableDataStorageVersion: "stable", - }, -}); -``` - - - -**Deprecated parameter** - -The `data_storage_version` parameter on `create_table()` is deprecated. Use `new_table_data_storage_version` in `storage_options` instead. - - -### AWS S3 {#aws-s3} - -![](/static/assets/images/storage/aws.jpg) - -Set `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and optionally `AWS_SESSION_TOKEN` as environment variables or pass them in `storage_options`. Region is optional for AWS but required for most S3-compatible stores. - -Minimum permissions usually include `s3:PutObject`, `s3:GetObject`, `s3:DeleteObject`, `s3:ListBucket`, and `s3:GetBucketLocation` scoped to the relevant bucket/prefix. - -### S3-compatible stores {#s3-compatible-stores} - - - - {PyStorageS3Minio} - - - {TsStorageS3Minio} - - - -If the endpoint is `http://` (common in local development), also set `ALLOW_HTTP=true` or pass `allow_http=True` in `storage_options`. - -### S3 Express {#s3-express} - - - - {PyStorageS3Express} - - - {TsStorageS3Express} - - - -Consult AWS networking requirements for S3 Express before enabling. - - -**Clean up failed multipart uploads** - -LanceDB aborts multipart uploads on graceful shutdown, but crashes can leave incomplete uploads. Add an S3 lifecycle rule to delete in-progress uploads after a few days. - - -### Server-side encryption with KMS {#server-side-encryption-with-kms} - -To encrypt at rest with an AWS KMS key, set `aws_server_side_encryption` to `aws:kms` and `aws_sse_kms_key_id` to the key ID or ARN. The same options apply at connection or table level and combine with bucket-level default encryption. - - - - {PyStorageS3SseKms} - - - {TsStorageS3SseKms} - - - -The IAM principal needs `kms:Encrypt`, `kms:Decrypt`, and `kms:GenerateDataKey` on the configured KMS key. - -### Google Cloud Storage {#google-cloud-storage} - -![](/static/assets/images/storage/gcp.jpg) - -Provide credentials via `GOOGLE_SERVICE_ACCOUNT` (path to JSON) or include the path in `storage_options`. GCS defaults to HTTP/1; set `HTTP1_ONLY=false` if you need HTTP/2. - - - - {PyStorageGcsServiceAccount} - - - {TsStorageGcsServiceAccount} - - - -### Azure Blob Storage {#azure-blob-storage} - -![](/static/assets/images/storage/azure.jpg) - -Set `AZURE_STORAGE_ACCOUNT_NAME` and `AZURE_STORAGE_ACCOUNT_KEY` as environment variables, or pass them via `storage_options`. - - - - {PyStorageAzureAccount} - - - {TsStorageAzureAccount} - - - -For SAS-token auth, set `azure_storage_account_name` and `azure_storage_sas_token`: - - - - {PyStorageAzureSas} - - - {TsStorageAzureSas} - - - -Other supported keys include service principal credentials (`azure_client_id`, `azure_client_secret`, `azure_tenant_id`), managed identities, and custom endpoints. - -### Tigris Object Storage {#tigris-object-storage} - -![](/static/assets/images/storage/tigris.jpg) - -Tigris exposes an S3-compatible API. Configure the endpoint and region: - - - - {PyStorageTigrisConnect} - - - {TsStorageTigrisConnect} - - - -Environment variables `AWS_ENDPOINT=https://t3.storage.dev` and `AWS_DEFAULT_REGION=auto` achieve the same configuration. - -### Tencent COS {#tencent-cos} - -[Tencent Cloud Object Storage (COS)](https://www.tencentcloud.com/products/cos) is the primary object store for workloads running in the China region. Use the `cos://` URI scheme to connect directly to a COS bucket. - - - - {PyStorageCosConnect} - - - -Supported keys include `secret_id`, `secret_key`, `region`, and `endpoint`. You can also authenticate via the `TENCENTCLOUD_SECRET_ID` and `TENCENTCLOUD_SECRET_KEY` environment variables. - - -**Availability** - -COS is bundled in the Python wheel by default. To use it from Rust or the Node binding, build with the `cos` Cargo feature enabled. - - -### GooseFS {#goosefs} - -[GooseFS](https://www.tencentcloud.com/document/product/1424) is Tencent Cloud's distributed cache acceleration layer for COS and S3. It is a common choice when the same hot dataset is read repeatedly, such as vector search and AI training workloads. Connect using the `goosefs://` URI scheme. - - - - {PyStorageGoosefsConnect} - - - {TsStorageGoosefsConnect} - - - -GooseFS reads credentials and endpoint configuration from the GooseFS client environment. See the [GooseFS documentation](https://www.tencentcloud.com/document/product/1424) for cluster setup. - - -**Availability** - -GooseFS is bundled by default in the Python wheel and the Node binding. To use it from Rust, build with the `goosefs` Cargo feature enabled. - diff --git a/docs/web/deployment/support.mdx b/docs/web/deployment/support.mdx index 148e71648..09b2892c3 100644 --- a/docs/web/deployment/support.mdx +++ b/docs/web/deployment/support.mdx @@ -1,12 +1,12 @@ --- title: "Support" sidebarTitle: "Support" -description: "Where to get help: community Discord for LanceDB Embedded (open source), dedicated support for LanceDB Enterprise." +description: "Where to get help: community Discord and email for LanceDB Embedded, dedicated support for LanceDB Enterprise." icon: circle-question keywords: ["support", "help", "discord", "community"] --- -## LanceDB Embedded (open source) {#oss} +## LanceDB Embedded {#oss} For a quick question, the [Discord community](https://discord.gg/AUEWnJ7Txb) has channels for @@ -19,14 +19,13 @@ Use GitHub for discussions and issues that others can search and follow: | [GitHub Discussions](https://github.com/lancedb/lancedb/discussions) | Open-ended questions, design questions, "what's the right way to do X" | | [GitHub Issues](https://github.com/lancedb/lancedb/issues) | A specific bug, or a feature request | -## LanceDB Enterprise {#enterprise} +For anything the community can't resolve, email +[support@lancedb.com](mailto:support@lancedb.com). -Enterprise Contact your support team directly at -[support@lancedb.com](mailto:support@lancedb.com) for dedicated assistance. +### What to include {#what-to-include} -## What to include {#what-to-include} - -A faster answer usually depends on the same handful of details: +A faster answer usually depends on the same handful of details, whether you +post in Discord or email: | | | | --- | --- | @@ -34,3 +33,8 @@ A faster answer usually depends on the same handful of details: | Connection type | embedded path, or a `db://` deployment | | The exact error | full traceback or error message, not a paraphrase | | A minimal repro | the smallest table schema and call that reproduces it | + +## LanceDB Enterprise {#enterprise} + +Talk to your account executive, file a support ticket, or reach the LanceDB +support and engineering team directly for dedicated assistance. diff --git a/docs/web/docs.json b/docs/web/docs.json index 871e375f8..c20341793 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -27,6 +27,42 @@ }, "favicon": "/static/favicon.ico", "redirects": [ + { + "source": "/enterprise/expected-performance", + "destination": "/search/vector-search#expected-performance" + }, + { + "source": "/enterprise/distributed-sql", + "destination": "/enterprise/distributed-search" + }, + { + "source": "/deployment/monitoring", + "destination": "/deployment/opentelemetry" + }, + { + "source": "/enterprise/intelligent-scheduling", + "destination": "/enterprise/intelligent-auto-maintenance" + }, + { + "source": "/enterprise/intelligent-maintenance", + "destination": "/enterprise/intelligent-auto-maintenance" + }, + { + "source": "/enterprise/intelligent-planning", + "destination": "/enterprise/intelligent-auto-maintenance" + }, + { + "source": "/enterprise/automated-cleanup", + "destination": "/enterprise/intelligent-auto-maintenance#cleanup" + }, + { + "source": "/indexing/reindexing", + "destination": "/indexing/incremental-indexing" + }, + { + "source": "/maintenance/background-jobs", + "destination": "/basics/jobs" + }, { "source": "/architecture", "destination": "/#architecture" @@ -45,11 +81,11 @@ }, { "source": "/basics/offerings", - "destination": "/#embedded-and-enterprise" + "destination": "/#architecture" }, { "source": "/enterprise/deployment", - "destination": "/enterprise#deployment" + "destination": "/basics/embedded-vs-enterprise" }, { "source": "/feature-engineering/data-evolution", @@ -71,9 +107,33 @@ "source": "/search/fts-examples", "destination": "/search/full-text-search" }, + { + "source": "/enterprise/benchmarks", + "destination": "/search/vector-search#expected-performance" + }, + { + "source": "/curation/huggingface", + "destination": "/curation/inspect-datasets" + }, + { + "source": "/curation/sunk-integration", + "destination": "/deployment/slurm" + }, + { + "source": "/curation/slurm-integration", + "destination": "/deployment/slurm" + }, + { + "source": "/curation/sampling", + "destination": "/curation/statistical-sampling" + }, { "source": "/search/optimize-queries", - "destination": "/search/explain" + "destination": "/basics/sql#query-plans" + }, + { + "source": "/search/explain", + "destination": "/basics/sql#query-plans" }, { "source": "/lance", @@ -153,7 +213,7 @@ }, { "source": "/search/explain-analyze", - "destination": "/search/explain" + "destination": "/basics/sql#query-plans" }, { "source": "/indexing/quantization", @@ -185,15 +245,19 @@ }, { "source": "/storage", - "destination": "/deployment/storage" + "destination": "/basics/catalog#object-storage" }, { "source": "/storage/configuration", - "destination": "/deployment/storage" + "destination": "/basics/catalog#object-storage" + }, + { + "source": "/deployment/storage", + "destination": "/basics/catalog#object-storage" }, { "source": "/storage/monitoring", - "destination": "/deployment/monitoring" + "destination": "/deployment/opentelemetry" }, { "source": "/search/sql", @@ -235,6 +299,26 @@ "source": "/sql/explain", "destination": "/sql/dql/explain" }, + { + "source": "/sql/operators", + "destination": "/sql/dql/operators" + }, + { + "source": "/sql/functions", + "destination": "/sql/dql/functions" + }, + { + "source": "/sql/scalar-functions", + "destination": "/sql/dql/scalar-functions" + }, + { + "source": "/feature-engineering/functions", + "destination": "/management/function" + }, + { + "source": "/sql/prepared-statements", + "destination": "/basics/sql#prepared-statements" + }, { "source": "/sql/ddl", "destination": "/sql/ddl/table" @@ -270,6 +354,18 @@ { "source": "/basics/apis", "destination": "/basics/sdk" + }, + { + "source": "/enterprise/distributed-column-refresh", + "destination": "/enterprise/adaptive-execution" + }, + { + "source": "/curation/slurm-scheduling", + "destination": "/deployment/slurm" + }, + { + "source": "/enterprise/slurm-refresh-scheduling", + "destination": "/deployment/slurm" } ], "navigation": { @@ -278,9 +374,16 @@ "tab": "Documentation", "groups": [ { - "group": "Getting Started", + "group": "Introduction", "pages": [ "index", + "basics/lancedb-embedded", + "basics/embedded-vs-enterprise" + ] + }, + { + "group": "Getting Started", + "pages": [ "quickstart", "basics/sdk", "basics/sql", @@ -288,12 +391,6 @@ "deployment/support" ] }, - { - "group": "Tools", - "pages": [ - "tools/cli" - ] - }, { "group": "Concepts", "pages": [ @@ -313,14 +410,18 @@ "ingestion/index", "ingestion/create-table", "ingestion/insert", - "ingestion/merge-insert", "ingestion/update", "ingestion/delete", - "ingestion/realtime-write" + "ingestion/realtime-write", + "ingestion/define-storage-integration", + "ingestion/migrate-from-embedded", + "ingestion/import", + "enterprise/distributed-write", + "enterprise/distributed-real-time-write" ] }, { - "group": "Semantic Search", + "group": "Search", "pages": [ "search/index", "search/vector-search", @@ -328,23 +429,33 @@ "search/hybrid-search", "search/filtering", "reranking/index", - "search/explain", "search/realtime-read", - "enterprise/distributed-search" + "enterprise/distributed-real-time-read", + "enterprise/distributed-search", + "enterprise/data-page-cache", + "enterprise/tiered-index-cache", + "enterprise/cache-prewarm" ] }, { "group": "Data Curation", "pages": [ "curation/index", + "curation/inspect-datasets", "curation/create-function", "curation/chunking", - "curation/changes", + "curation/statistical-sampling", + "curation/selective-sampling", "curation/aggregate", - "curation/sampling", "curation/join", + "curation/blob-late-materialization", + "curation/distributed-shuffle", "curation/windowing", - "curation/dedupe" + "curation/clustering", + "curation/dedupe", + "curation/changes", + "feature-engineering/view", + "curation/vend-secret" ] }, { @@ -353,58 +464,57 @@ "feature-engineering/index", "feature-engineering/add-computed-column", "feature-engineering/refresh-column", - "feature-engineering/view", "feature-engineering/materialized-views", - "feature-engineering/refresh-materialized-view" + "feature-engineering/refresh-materialized-view", + "enterprise/incremental-refresh", + "enterprise/auto-refresh", + "enterprise/checkpointing", + "enterprise/adaptive-execution" ] }, { "group": "Training", "pages": [ - "training/permutation", "training/data-loading", - "training/distributed-training" + "training/training-cache", + "training/permutation", + "training/observability", + "training/distributed-training", + "training/checkpointing", + "training/resuming" ] }, { "group": "Management", "pages": [ "management/index", + "management/catalog", "management/database", "management/namespace", "management/table", - "tables/branching", "management/view", - "management/materialized-view" + "management/materialized-view", + "management/secret", + "management/function", + "management/storage-integration" ] }, { "group": "Maintenance", "pages": [ - { - "group": "Indexing", - "icon": "layer-group", - "pages": [ - "indexing/index", - "indexing/vector-index", - "indexing/fts-index", - "indexing/scalar-index", - "indexing/reindexing" - ] - }, + "indexing/index", + "enterprise/intelligent-auto-maintenance", + "indexing/vector-index", + "indexing/fts-index", + "indexing/scalar-index", + "indexing/incremental-indexing", + "enterprise/distributed-indexing", + "indexing/gpu-indexing", "maintenance/compaction", - "maintenance/cleanup", - "maintenance/background-jobs" - ] - }, - { - "group": "Deployment", - "pages": [ - "enterprise/index", - "deployment/storage", - "deployment/monitoring", - "enterprise/deployment/kubernetes", - "enterprise/benchmarks" + "enterprise/realtime-engine-compaction", + "enterprise/distributed-compaction", + "enterprise/advanced-conflict-resolution", + "maintenance/cleanup" ] }, { @@ -412,9 +522,22 @@ "pages": [ "enterprise/authentication", "governance/authorization", + "governance/principals", + "governance/privileges", + "governance/audit-log", "enterprise/security" ] }, + { + "group": "Deployment", + "pages": [ + "enterprise/horizontal-scaling", + "deployment/opentelemetry", + "enterprise/deployment/kubernetes", + "deployment/multicloud", + "deployment/slurm" + ] + }, { "group": "SQL Reference", "pages": [ @@ -428,8 +551,12 @@ "sql/ddl/table", "sql/ddl/view", "sql/ddl/materialized-view", + "sql/ddl/secret", + "sql/ddl/function", + "sql/ddl/storage-integration", "sql/ddl/index", - "sql/ddl/job" + "sql/ddl/job", + "sql/ddl/grant" ], "icon": "sitemap" }, @@ -451,26 +578,24 @@ "sql/dql/select", "sql/dql/subqueries", "sql/dql/join", + "sql/dql/operators", + "sql/dql/functions", + "sql/dql/scalar-functions", "sql/dql/aggregation", "sql/dql/window", "sql/dql/sampling", "sql/dql/changes", "sql/dql/fts", + "sql/dql/contains-tokens", + "sql/dql/ivf-partition", "sql/dql/dedupe", "sql/dql/duplicate-pairs", + "sql/dql/vector-distance", + "sql/dql/blob-descriptor", + "sql/dql/generate-series", "sql/dql/explain" ], "icon": "filter" - }, - { - "group": "Expressions", - "pages": [ - "sql/operators", - "sql/functions", - "sql/scalar-functions", - "sql/prepared-statements" - ], - "icon": "code" } ] } @@ -583,8 +708,7 @@ "group": "Feature Engineering", "pages": [ "tutorials/feature-engineering/feature-engineering-101", - "tutorials/feature-engineering/materialized-views", - "agent-branch-experiments" + "tutorials/feature-engineering/materialized-views" ] }, { diff --git a/docs/web/embedding/index.mdx b/docs/web/embedding/index.mdx index 91efcc566..30fbc5aa4 100644 --- a/docs/web/embedding/index.mdx +++ b/docs/web/embedding/index.mdx @@ -136,13 +136,14 @@ In Python, the embedding definition is stored in the table, so anyone who can wr To keep a table from running code or sending data where you didn't intend, two kinds of settings are only honored when this process has approved them: -- `trust_remote_code=True`, which runs code from the model's Hugging Face repository. +- `trust_remote_code=True`, which runs code from the model's HuggingFace repository. - Custom endpoints such as OpenAI `base_url`, Ollama `host`, or watsonx `url`, which receive your data and API keys. Embedding functions you create in the current process are approved automatically. When you open a table in a new process, approve these settings explicitly before computing embeddings: -```python + +```python Python icon="python" from lancedb.embeddings import get_registry registry = get_registry() @@ -150,6 +151,7 @@ registry = get_registry() registry.allow_remote_code("nomic-ai/nomic-embed-text-v1.5", revision="") registry.allow_endpoint("http://my-ollama-host:11434") ``` + Until then, computing embeddings raises `UntrustedEmbeddingConfigError`. Other operations on the table still work. @@ -176,7 +178,7 @@ LanceDB supports most popular embedding providers. |----------|----------|---------------| | OpenAI | `openai` | `text-embedding-ada-002` | | Sentence Transformers | `sentence-transformers` | `all-MiniLM-L6-v2` | -| Hugging Face | `huggingface` | `colbert-ir/colbertv2.0` | +| HuggingFace | `huggingface` | `colbert-ir/colbertv2.0` | | Cohere | `cohere` | `embed-multilingual-v3.0` | | ... | ... | ... | @@ -212,16 +214,20 @@ When the Python SDK connects to Enterprise, `table.search("hello")` can take two The client uses the same local LanceDB embedding registry used by LanceDB Embedded tables to reconstruct the embedding function from schema metadata, compute the query vector in the client process, and send that vector to Enterprise for search. - ```python + + ```python Python icon="python" result = table.search("hello").limit(1).to_list() # The Python client computes the query embedding locally, then sends a vector search. ``` + - If the table does not have embedding metadata for that search, `table.search("hello")` in `auto` mode is treated as an FTS query instead. - ```python + + ```python Python icon="python" result = table.search("hello").limit(5).to_list() # In auto mode this is treated as an FTS query, not a vector query. ``` + If you want explicit vector or hybrid behavior and the client cannot resolve an embedding function from the table metadata, generate the query embedding yourself and pass the vector directly. diff --git a/docs/web/embedding/quickstart.mdx b/docs/web/embedding/quickstart.mdx index 1111743da..509df8f59 100644 --- a/docs/web/embedding/quickstart.mdx +++ b/docs/web/embedding/quickstart.mdx @@ -15,7 +15,7 @@ import { } from '/snippets/sentence-transformers.mdx'; LanceDB will automatically vectorize the data both at ingestion and query time. All you need to do is specify which model to use. -Popular embedding models like OpenAI, Hugging Face, Sentence Transformers, CLIP, and more, are supported. +Popular embedding models like OpenAI, HuggingFace, Sentence Transformers, CLIP, and more, are supported. ## Step 1: Import Required Libraries {#step-1-import-required-libraries} @@ -23,7 +23,6 @@ First, import the necessary LanceDB components: ```python Python icon="python" -import lancedb from lancedb.pydantic import LanceModel, Vector from lancedb.embeddings import get_registry ``` diff --git a/docs/web/enterprise/adaptive-execution.mdx b/docs/web/enterprise/adaptive-execution.mdx new file mode 100644 index 000000000..97ab71e67 --- /dev/null +++ b/docs/web/enterprise/adaptive-execution.mdx @@ -0,0 +1,139 @@ +--- +title: "Adaptive Execution" +tag: "Early access" +sidebarTitle: "Adaptive Execution" +description: "How a Function refresh's part size, resource class, worker count and checkpoint frequency adjust themselves to observed behavior." +icon: "gauge-high" +availability: + embedded: unavailable + enterprise: available +--- + +Early access + +When a [computed column](/feature-engineering/add-computed-column) or +[materialized view](/feature-engineering/materialized-views) is filled by +a registered [Function](/curation/create-function), LanceDB Enterprise +adapts the refresh to the Function's actual behavior along several axes -- +how many rows go in one unit of work, how much CPU, memory and GPU one +invocation gets, how many worker processes run inside one worker, and how +many workers run at all -- rather than running it at one fixed shape +regardless of how slow, fast, or resource-hungry that Function turns out +to be. See [Architecture](/index#architecture). + +## Part size follows observed throughput {#part-size} + +A Function refresh starts with a small probe part -- 10 rows -- and grows +it based on an exponentially-weighted average of rows processed per +millisecond, aiming each next part at roughly 45 seconds of work. A part +can grow or shrink by at most 16x from the previous one, so one unusually +slow or fast part doesn't swing sizing to an extreme; the ceiling is +1,000,000 rows per part regardless of how fast the Function appears to +run. A consistently slow Function converges on small parts that finish +reliably; a fast one converges on large parts that keep worker overhead +-- a fresh scanner and registry round trip per part -- small relative to +the work done. + +## Resource class follows observed consumption {#resource-consumption} + +Each invocation is measured -- wall time, CPU time and utilization, peak +memory, out-of-memory events, and for a GPU Function, compute and memory +utilization per GPU -- and that measurement decides whether the *next* +invocation runs with more resources, fewer, or the same: + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + I["Invocation runs
wall time, CPU, memory, GPU measured"] --> D{"Saturated?"} + D -->|"OOM, or memory/CPU/GPU
over target utilization"| P["Promote:
next size up"] + D -->|"fast task, low CPU,
known memory"| Dm["Demote:
one size down,
never past a floor"] + D -->|neither| S["Stay:
same class"] + P --> N["Next invocation"] + Dm --> N + S --> N + N --> I + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + I["Invocation runs
wall time, CPU, memory, GPU measured"] --> D{"Saturated?"} + D -->|"OOM, or memory/CPU/GPU
over target utilization"| P["Promote:
next size up"] + D -->|"fast task, low CPU,
known memory"| Dm["Demote:
one size down,
never past a floor"] + D -->|neither| S["Stay:
same class"] + P --> N["Next invocation"] + Dm --> N + S --> N + N --> I + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 +``` + +
+ +**Promotion** happens on an out-of-memory event, memory utilization above +70% of the class's limit, or CPU pegged at 85%+ for a sample long enough +(5 seconds) that one fast spike isn't mistaken for sustained saturation. A +GPU Function promotes the same way on GPU compute or GPU memory +saturation. **Demotion** is more conservative: only a task that both +finished fast (under 30 seconds) and used 25% or less of its CPU budget +demotes, one size down at a time rather than jumping straight to the +smallest class, and never below a configured floor. Either way, the class +actually chosen is the smallest one whose memory and CPU both cover the +observed peak with roughly 40% headroom, so sizing tracks what the +Function actually consumes rather than a static guess made once at +registration. + +## Process and worker count follow the resource budget {#sizing} + +Within one worker, the number of executor processes is chosen to be the +largest count that still fits the worker's memory budget, since memory +per process shrinks as the count grows. Across workers, the fleet claims +as many additional workers as the configured CPU, memory and GPU budget +has room for, given what's already running -- the worker count grows to +use available budget rather than running at a single fixed count +regardless of how much of the budget sits idle. + +## Checkpoint granularity follows part size {#checkpointing} + +A refresh checkpoints once per part, not on a separately-tuned interval -- +so checkpoint frequency is a direct consequence of the same EWMA-driven +part sizing described above, not a second knob. A Function that converges +on small parts checkpoints often, losing little work if a worker dies +mid-refresh; one that converges on large parts checkpoints less often, +trading that for lower per-part overhead. See +[Checkpointing](/enterprise/checkpointing) for the mechanism itself. + +## Overriding the defaults {#override} + +A refresh can request a GPU class and count, or cap the maximum rows per +Function call directly, instead of relying on this adaptive behavior -- +see [Configure workers and resources](/feature-engineering/refresh-column#resources) +for the full set of overrides, SQL and SDK alike. Setting `batch_size` +caps the rows passed to each Function call for that refresh; the adaptive +part sizing described above still decides how many rows each part covers. + +## What to read next {#next} + + + + How the rows a Function refresh works on are chosen in the first place. + + + How a part's progress survives a failure or restart. + + diff --git a/docs/web/enterprise/advanced-conflict-resolution.mdx b/docs/web/enterprise/advanced-conflict-resolution.mdx new file mode 100644 index 000000000..3826de8a5 --- /dev/null +++ b/docs/web/enterprise/advanced-conflict-resolution.mdx @@ -0,0 +1,199 @@ +--- +title: "Advanced Conflict Resolution" +sidebarTitle: "Advanced Conflict Resolution" +description: "How compaction and indexing stay safe to run concurrently, using Lance's fragment reuse index." +icon: shuffle +keywords: ["fragment reuse index", "FRI", "compaction", "indexing", "remap", "conflict resolution"] +availability: + embedded: unavailable + enterprise: available +--- + +[Compaction](/maintenance/compaction) rewrites fragments into fewer, larger +files, which changes the physical row address -- file and offset -- of every +row it moves. An index built against the old layout stores exactly those +addresses, so a naive compaction would leave any index covering the rewritten +fragments pointing at rows that have moved or no longer exist there. + +LanceDB Embedded avoids this by default by never letting the two run +independently: `optimize()` compacts and remaps affected indexes in the +same call, before returning. Compaction's `defer_index_remap` option opts +out of that -- the call returns once compaction itself commits, leaving +the remap for later -- which is what lets a custom remapper or a +stable-row-ID table skip the synchronous step. LanceDB Enterprise runs +compaction and indexing as separate, independently scheduled +background jobs -- a table can compact while an index build is still +catching up from an earlier compaction -- so it needs a way to keep an index +correct without forcing every compaction to wait for a synchronous remap. + +## The fragment reuse index {#fri} + +The **fragment reuse index** (FRI) is a Lance format-level mechanism, not an +Enterprise add-on: a system index that records every fragment rewrite as a +**transition** -- the source fragments' digests, the destination fragments' +digests, and a row-address mapping between them (`Transition` and `Mapping` +in `lance-table`'s `system_index::frag_reuse::ledger`). An index that covers +a rewritten fragment does not need to be rebuilt before the rewrite commits; +it can instead translate the row addresses it already stores forward through +the chain of recorded transitions at read time. + +Only a compaction run with `defer_index_remap` ever touches the FRI; a +synchronous-remap rewrite -- the Embedded default -- never tags a table or +appends anything. Every `defer_index_remap` commit is classified before +it is admitted; that classifier is Lance's own commit protocol +(`lance-table`'s `frag_reuse::gate::classify`), the same one every write +funnels through -- not a lock or a sequencing rule Enterprise imposes from +outside. A table starts **untagged**: its deferred rewrites are admitted +as ordinary business with nothing appended, unless the rewrite has +stable row IDs to translate or touches a fragment an index covers -- either +one makes that commit record a legacy, untagged ("v0") FRI entry, which +does **not** tag the table. Tagging is a separate, one-way transition (a +sticky manifest flag that a later trim never clears) that publishes the +FRI's first real transition; this page does not cover what triggers it. +Once a table is tagged, its commits are classified against which indexes +cover the rewritten fragments the way the rest of this page describes, and +every entry it records from then on is a tagged transition, never v0 +again. A table with stable row IDs is permanently confined to the +untagged, v0 form -- Lance refuses to tag it at all -- so its deferred +compactions keep recording v0 entries indefinitely, for every rewrite that +moves row addresses, not only ones that touch an indexed fragment: the +address translation itself depends on that record, independent of +indexing. + +Once a table is tagged, Lance refuses a compaction that does not set +`defer_index_remap`, including a plain Embedded `optimize()` call: an +Enterprise-tagged table has to keep deferring the remap, or be compacted +by a writer that can remap the tagged history eagerly. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TD + Commit["Compaction commit
(defer_index_remap only)"] --> Tagged{"Table already
tagged with an FRI?"} + Tagged -->|no| First{"Stable row IDs, or does
any index cover the
rewritten fragments?"} + First -->|no| Admit["Admitted as
ordinary business --
nothing appended"] + First -->|yes| V0["Records a legacy v0 entry --
table stays untagged"] + Tagged -->|yes| Classify{"Does any index
cover the rewritten
fragments?"} + Classify -->|no| Admit + Classify -->|yes| Append["Must append a tagged
transition before the
commit is admitted"] + V0 --> FRI[("Fragment reuse index")] + Append --> FRI + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class FRI accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TD + Commit["Compaction commit
(defer_index_remap only)"] --> Tagged{"Table already
tagged with an FRI?"} + Tagged -->|no| First{"Stable row IDs, or does
any index cover the
rewritten fragments?"} + First -->|no| Admit["Admitted as
ordinary business --
nothing appended"] + First -->|yes| V0["Records a legacy v0 entry --
table stays untagged"] + Tagged -->|yes| Classify{"Does any index
cover the rewritten
fragments?"} + Classify -->|no| Admit + Classify -->|yes| Append["Must append a tagged
transition before the
commit is admitted"] + V0 --> FRI[("Fragment reuse index")] + Append --> FRI + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class FRI accent +``` + +
+ +## Enterprise defers and batches the catch-up {#catch-up} + +Translating addresses through a long chain of transitions at every read adds +up, so Enterprise does not let the FRI grow without bound. Its job planner +tracks how many transitions have accumulated for a table and schedules a +dedicated **remap catch-up** job -- which applies the accumulated transitions +to the indexes that need them, physically, in one pass -- once either: + +- the FRI reaches **5 pending transitions** (`remap_fri_version_threshold`, + tunable), or +- the oldest pending transition is **1 day old** + (`remap_fri_max_age_secs`, tunable), whichever comes first. + +The version count only climbs while a table keeps compacting, so the age +threshold exists to clear a lingering FRI -- and the per-read remap cost that +comes with it -- on a table that stops compacting before reaching the count +threshold, without scheduling a catch-up job on every table that is still +actively compacting. This is what lets compaction and index maintenance run +as separate background jobs (see +[Index maintenance jobs](/indexing/incremental-indexing#index)) +rather than one blocking on the other: a handful of compactions can land +before their indexes are physically remapped, and the catch-up job amortizes +that remap across all of them in one job instead of one per compaction. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TD + C1["Compaction job"] -->|appends transition| FRI["Fragment reuse index
(ledger of transitions)"] + C2["Compaction job"] -->|appends transition| FRI + C3["Compaction job"] -->|appends transition| FRI + FRI -->|5 transitions or
1 day old| R["Remap catch-up job"] + R -->|applies accumulated
transitions| IDX["Affected indexes,
physically remapped"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class FRI,R accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TD + C1["Compaction job"] -->|appends transition| FRI["Fragment reuse index
(ledger of transitions)"] + C2["Compaction job"] -->|appends transition| FRI + C3["Compaction job"] -->|appends transition| FRI + FRI -->|5 transitions or
1 day old| R["Remap catch-up job"] + R -->|applies accumulated
transitions| IDX["Affected indexes,
physically remapped"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class FRI,R accent +``` + +
+ +## What to read next {#next} + + + + What compaction merges, and how the embedded library runs it in one call. + + + The `index_remap` job type, and keeping an index current as the table changes. + + + How compaction itself scales across the jobs fleet. + + + How an index build scales across the jobs fleet. + + diff --git a/docs/web/enterprise/authentication.mdx b/docs/web/enterprise/authentication.mdx index 920275d16..ecca6ed0e 100644 --- a/docs/web/enterprise/authentication.mdx +++ b/docs/web/enterprise/authentication.mdx @@ -29,8 +29,6 @@ and Rust. Load the key from an environment variable or secret manager. ```python Python icon="python" import os -import lancedb - db = lancedb.connect( uri="db://your-database-uri", api_key=os.environ["LANCEDB_API_KEY"], @@ -98,7 +96,7 @@ client acquires tokens: | --- | --- | --- | --- | --- | | Client Credentials | `OAuthFlowType.CLIENT_CREDENTIALS` | `OAuthFlowType.ClientCredentials` | `OAuthFlow::ClientCredentials` | Service-to-service / machine-to-machine. Requires a client ID and client secret registered with your identity provider. | | Authorization Code | `OAuthFlowType.AUTHORIZATION_CODE` | `OAuthFlowType.AuthorizationCode` | `OAuthFlow::AuthorizationCode(AuthorizationCodeOptions::new())` | Interactive user sign-in through a browser and local callback server. Uses S256 PKCE by default. | -| Device Code | `OAuthFlowType.DEVICE_CODE` | `OAuthFlowType.DeviceCode` | `OAuthFlow::DeviceCode` | CLI or headless sign-in. The client displays a verification URL and user code for the user to enter on another device. | +| Device Code | `OAuthFlowType.DEVICE_CODE` | `OAuthFlowType.DeviceCode` | `OAuthFlow::DeviceCode(DeviceCodeOptions::new())` | CLI or headless sign-in. The client displays a verification URL and user code for the user to enter on another device. | | Azure Managed Identity | `OAuthFlowType.AZURE_MANAGED_IDENTITY` | `OAuthFlowType.AzureManagedIdentity` | `OAuthFlow::AzureManagedIdentity { client_id: None }` | Azure workloads with access to the IMDS endpoint. Tokens are fetched from IMDS, so no client secret is stored on the client. | ### Configure OAuth {#configure-oauth} @@ -109,7 +107,6 @@ Rust, and `oauthConfig` in TypeScript. ```python Python icon="python" import os -import lancedb from lancedb.remote import OAuthConfig, OAuthFlowType # Client Credentials (service-to-service) @@ -247,7 +244,6 @@ request a refresh token from your provider (often by including ```python Python icon="python" -import lancedb from lancedb.remote import OAuthConfig, OAuthFlowType, TokenCacheOptions # Use DEVICE_CODE for a CLI without a local browser or callback server. @@ -290,7 +286,7 @@ const db = await lancedb.connect("db://your-database-uri", { ```rust Rust icon="rust" use lancedb::remote::{AuthorizationCodeOptions, OAuthConfig, OAuthFlow, TokenCacheOptions}; -// Use OAuthFlow::DeviceCode for a CLI without a local browser or callback server. +// Use OAuthFlow::DeviceCode(Default::default()) for a CLI without a local browser or callback server. let oauth_config = OAuthConfig { issuer_url: "https://your-issuer.example.com".into(), client_id: "your-public-client-id".into(), @@ -317,9 +313,16 @@ let db = lancedb::connect("db://your-database-uri") ``` -With `DEVICE_CODE` / `DeviceCode` / `OAuthFlow::DeviceCode`, the same +With `DEVICE_CODE` / `DeviceCode` / `OAuthFlow::DeviceCode(DeviceCodeOptions::new())`, the same configuration and connection calls apply; only the `flow` value changes. +Device Code sends no PKCE parameters by default. For a provider that requires +S256 PKCE on device grants, Rust callers can select +`OAuthFlow::DeviceCode(DeviceCodeOptions::new().use_pkce(true))` (import +`DeviceCodeOptions` from `lancedb::remote`). This option is currently Rust-only. +Enable it only when the provider supports the extension; a failed PKCE request +is not retried without PKCE. + ### Reuse an interactive session {#reuse-an-interactive-session} By default, tokens stay in process memory. Set `token_cache` / `tokenCache` @@ -379,7 +382,8 @@ Credentials and rejected for Azure Managed Identity. ### Configuration reference {#configuration-reference} -The same configuration is available in all three SDKs. Python and Rust use +The shared configuration below is available in all three SDKs; device-code PKCE +is a Rust-only option through `DeviceCodeOptions`. Python and Rust use `snake_case` field names; TypeScript uses `camelCase`. In Rust, set optional `OAuthConfig` fields to `Some(value)` or `None`. Configure `redirect_uri`, `callback_port`, and `use_pkce` through the builder methods on diff --git a/docs/web/enterprise/auto-refresh.mdx b/docs/web/enterprise/auto-refresh.mdx new file mode 100644 index 000000000..452d543e8 --- /dev/null +++ b/docs/web/enterprise/auto-refresh.mdx @@ -0,0 +1,96 @@ +--- +title: "Auto Refresh" +sidebarTitle: "Auto Refresh" +description: "Let a computed column or materialized view refresh itself on a schedule, instead of calling refresh explicitly." +icon: "clock-rotate-left" +availability: + embedded: unavailable + enterprise: available +--- + +Both a [computed column](/feature-engineering/add-computed-column) and a +[materialized view](/feature-engineering/materialized-views) can refresh +themselves on a schedule instead of waiting for an explicit +`refresh_column()`, `view.refresh()`, or `REFRESH` statement. Either way, +`auto_refresh_enabled` turns it on and `auto_refresh_interval_seconds` sets +a minimum delay before the next automatic refresh is eligible -- omit the +interval to let the server decide. What that delay is measured from differs +between the two; see [Pacing follows different state for +each](#history) below. See [Architecture](/index#architecture) for the +scheduler's place among the jobs fleet. + +## Where the two differ {#granularity} + +A computed column's auto-refresh setting is per output: each column +declared in the same `add_columns` call gets its own independent +interval, set when you declare it or changed later. Automatic execution +additionally needs the deployment's `column_refresh.enabled` switch, +which is off in the base configuration. + +```sql +ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_enabled = false; +ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_enabled = true; +ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_interval_seconds = 300; +``` + +A materialized view's setting is whole-view -- there is no per-column +granularity the way a computed column has one setting per output. The +view's *initial* population always happens regardless of this setting; +only the refreshes after that are gated. Unlike a computed column, a view's +setting is declared at `CREATE` time, but it can still be changed +afterward with `ALTER`: + +```sql +CREATE MATERIALIZED VIEW my_view +WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300) +AS SELECT * FROM source_table; + +ALTER MATERIALIZED VIEW my_view SET auto_refresh_enabled = false; +ALTER MATERIALIZED VIEW my_view SET auto_refresh_enabled = true; +ALTER MATERIALIZED VIEW my_view SET auto_refresh_interval_seconds = 300; +``` + +Each `SET` above changes the scheduling setting immediately and +synchronously; it does not itself run a refresh. Whether and when a +refresh actually runs next is a separate, asynchronous decision the +scheduler makes against the pacing rules below. If values stop appearing +after a `SET`, check the column's Job Registry history rather than assuming +the setting itself failed to apply. + +## Pacing follows different state for each {#history} + +A computed column's pacing is measured from the last successful refresh +recorded in the Job Registry's live history, not from a separate +timestamp LanceDB keeps elsewhere. If completed jobs are archived before +the column's configured interval has elapsed, the scheduler can lose that +last-success record and refresh earlier than the interval implies. Leave +archival disabled, or retain live history for at least the longest +configured interval you rely on. A deployment archives completed jobs by +default, after a default seven-day retention threshold; check with your +deployment operator if you rely on a different setting. + +A materialized view's pacing instead reads a timestamp the view itself +persists for when it was last checked, not Job Registry history -- so +archival doesn't affect it. Once the interval has elapsed, the scheduler +also skips the refresh outright if the source table's version is +unchanged since the view's last check, rather than re-running a refresh +that would produce the same rows. + +## Catching up {#catch-up} + +Re-enabling a column's auto-refresh after it was off catches up the +entire accumulated backlog in one pass, not just rows written from that +point on -- "catch up," not "resume cadence." Disabling never skips or +drops writes either: rows written while disabled simply commit with no +computed value yet, the same as a row written before the column existed. + +## What to read next {#next} + + + + Manual refresh, partial refreshes, and what happens on failure. + + + Manual refresh and what happens on failure, for a view. + + diff --git a/docs/web/enterprise/benchmarks.mdx b/docs/web/enterprise/benchmarks.mdx deleted file mode 100644 index 402dfd56a..000000000 --- a/docs/web/enterprise/benchmarks.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: "Benchmarks" -sidebarTitle: "Benchmarks" -description: "Published performance results for LanceDB Enterprise." -icon: chart-line -keywords: ["benchmarks", "performance", "throughput", "latency"] ---- - -Enterprise - -This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it. See -[Architecture](/index#architecture) for what differs between the two. - -Benchmark results are specific to a deployment's shape (cluster size, storage -class, dataset), so they are published with LanceDB Enterprise. - -For tuning your own workload rather than comparing published numbers, see -[Query plans](/search/explain) and the performance notes on -[Search](/search#performance) and [Insert](/ingestion/insert#performance). diff --git a/docs/web/enterprise/cache-prewarm.mdx b/docs/web/enterprise/cache-prewarm.mdx new file mode 100644 index 000000000..3ce773d73 --- /dev/null +++ b/docs/web/enterprise/cache-prewarm.mdx @@ -0,0 +1,87 @@ +--- +title: "Cache Prewarm" +sidebarTitle: "Cache Prewarm" +description: "Populate the tiered index cache ahead of a request, instead of filling it lazily on first read." +icon: "fire" +keywords: ["prewarm", "cache", "index cache", "startup"] +availability: + embedded: unavailable + enterprise: available +--- + +Cache Prewarm loads the [tiered index cache](/enterprise/tiered-index-cache) +a plan executor keeps as part of Enterprise's serving layer, instead of +leaving it to fill lazily on first read. You configure which tables to +prewarm; on startup, each plan executor loads those tables' indexes into +cache before it joins the fleet. The executor does not accept queries until +prewarming finishes, so it never serves a request against a cold cache. + +LanceDB Embedded has no such cache, so there is nothing for it to warm +there. Embedded does have its own, separate `prewarm_index()` on a table -- +an idempotent hint that loads a built index into memory ahead of a query. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + List[("Configured list
of tables to prewarm")] + Start["Plan executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] + List -.-> Warm + Warm --> Ready["Ready — joins the fleet,
starts serving queries"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Warm,List accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + List[("Configured list
of tables to prewarm")] + Start["Plan executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] + List -.-> Warm + Warm --> Ready["Ready — joins the fleet,
starts serving queries"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Warm,List accent +``` + +
+ +## Why it matters {#why-it-matters} + +Without prewarming, a fresh or restarted executor would fill its indexes +lazily, so the first queries it serves pay the cost of loading and +deserializing them from object storage. Holding the executor out of the +fleet until its configured tables are warm means every query it ever +serves gets a warm cache, so performance stays consistent through restarts +and rollouts instead of dipping right after each one. + +[Contact us](https://www.lancedb.com/contact) to learn more about how +prewarming is configured for your deployment. + +## What to read next {#next} + + + + The raw-data-page cache -- a separate cache from the one prewarm fills. + + + The deserialized-index cache prewarm fills. + + + Where plan executors and query nodes sit in the serving fleet. + + diff --git a/docs/web/enterprise/checkpointing.mdx b/docs/web/enterprise/checkpointing.mdx new file mode 100644 index 000000000..ca6eab814 --- /dev/null +++ b/docs/web/enterprise/checkpointing.mdx @@ -0,0 +1,122 @@ +--- +title: "Function Refresh Checkpointing" +tag: "Early access" +sidebarTitle: "Checkpointing" +description: "How a Function refresh's progress survives a worker failure or restart, part by part." +icon: "floppy-disk" +keywords: ["checkpoint", "recovery", "function refresh", "blob v2", "parts", "resume"] +availability: + embedded: unavailable + enterprise: available +--- + +Early access + +This page is about checkpointing a [Function refresh](/enterprise/adaptive-execution) +specifically -- not [PyTorch training checkpointing](/training/checkpointing), +a different, unrelated mechanism covered elsewhere. + +A Function refresh fills a column in [parts](/enterprise/adaptive-execution#part-size), +each one a bounded range of rows. Every part's lifecycle is recorded as a +durable, append-only event -- started, then completed -- in a log scoped +to the data file that part belongs to. A worker failure or restart does +not require redoing the refresh from scratch: the next attempt reads that +log, finds which parts already completed, and only works on what's left. +Retrying is at-least-once at the part level, not exactly-once: a part +that started but never recorded completion is redone in full on the next +attempt, so a Function with external side effects (a remote API call, for +example) can have those side effects repeated for that part's rows. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + S["Part started
event recorded"] --> E["Function executes"] + E --> C["Part completed
event recorded"] + C --> M{"More parts?"} + M -->|yes| S + M -->|no| F["Finalized:
digest-verified assembly
into the real data file"] + + S -. "worker dies here" .-> R["Next attempt reads the log,
sees no completion,
redoes only this part"] + C -. "worker dies here" .-> R2["Next attempt reads the log,
sees this part done,
inherits it, moves on"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class R,R2 accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + S["Part started
event recorded"] --> E["Function executes"] + E --> C["Part completed
event recorded"] + C --> M{"More parts?"} + M -->|yes| S + M -->|no| F["Finalized:
digest-verified assembly
into the real data file"] + + S -. "worker dies here" .-> R["Next attempt reads the log,
sees no completion,
redoes only this part"] + C -. "worker dies here" .-> R2["Next attempt reads the log,
sees this part done,
inherits it, moves on"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class R,R2 accent +``` + +
+ +## What gets recorded, and when {#events} + +Each part contributes two events to its data file's log: one when a +worker starts it, one when it completes with the rows it filled, the rows +it skipped, and how long it took. A completed part additionally carries +enough identity that a *different* job -- one that took over after the +part's original job died -- can verify the part is really done and adopt +it rather than redo it. Once every part for a data file has completed, +one last event finalizes it: the assembled file's checksum is verified +against what the parts actually wrote before it's accepted as the real +data file, not just assumed correct because every part reported success. + +Writes to this log are batched, not one durable write per event, so +checkpointing a fast-finishing part costs a fraction of a write rather +than a full one. + +## The Blob v2 optimization {#blob-v2} + +A Function whose output includes a [Blob v2](/management/table#managed-blobs) +column needs an identifier for every blob it writes. Allocating those +IDs piggybacks on the same durable event that already records a part +starting: the event log itself hands out the next unclaimed range, +computed from the highest range any earlier part in this log has already +claimed. This means: + +- **No separate allocation round trip.** The ID range arrives for free + inside a write the part was already going to make durably. +- **A retried part can't collide with itself or with other parts.** Each + attempt at a part writes a new part-started event and gets a fresh range + past the highest range already claimed in this log, so no two attempts -- + of the same part or of different parts -- ever hold overlapping ranges. + Re-sending the *same* event, for example after a lost acknowledgement, is + idempotent and returns the range it was already given. A range left + behind by a failed attempt is not reclaimed. + +## What to read next {#next} + + + + Part sizing, and why checkpoint frequency follows it. + + + Shaping a Function, including ones that return Blob v2 output. + + diff --git a/docs/web/enterprise/data-page-cache.mdx b/docs/web/enterprise/data-page-cache.mdx new file mode 100644 index 000000000..11eee89d2 --- /dev/null +++ b/docs/web/enterprise/data-page-cache.mdx @@ -0,0 +1,79 @@ +--- +title: "Data Page Cache" +sidebarTitle: "Data Page Cache" +description: "How LanceDB Enterprise caches table data pages to avoid re-reading object storage." +icon: "database" +availability: + embedded: unavailable + enterprise: available +--- + +The data page cache holds fixed-size pages of raw table data read from +object storage, keyed by their location, so a later read of the same range +is served from memory or local disk instead of round-tripping to the +backing store. Plan executors and query nodes each keep their own cache for +the pages they serve. A background prewarm job can populate a cache ahead +of a request that needs it, rather than filling it lazily on first read. +See [Architecture](/index#architecture). + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + R["Read request
for a data page"] --> M{"In memory?"} + M -->|hit| Return["Served from memory"] + M -->|miss| D{"In local disk cache?"} + D -->|hit| Promote["Loaded into memory,
served"] + D -->|miss| O[("Object storage")] + O --> Fill["Fills memory and disk,
served"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + R["Read request
for a data page"] --> M{"In memory?"} + M -->|hit| Return["Served from memory"] + M -->|miss| D{"In local disk cache?"} + D -->|hit| Promote["Loaded into memory,
served"] + D -->|miss| O[("Object storage")] + O --> Fill["Fills memory and disk,
served"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 +``` + +
+ +A table's local disk cache shares one configurable budget with the +[tiered index cache](/enterprise/tiered-index-cache#disk-budget)'s disk +tier where both are enabled on the same executor. + +## Why it matters {#why-it-matters} + +Object storage is durable and cheap, but every round trip to it adds +latency and egress cost. For workloads that read the same ranges +repeatedly -- a hot subset of embeddings, a frequently-filtered column -- +the data page cache turns most of those reads into local memory or disk +hits instead, so performance stays predictable as traffic grows and you +pay object storage once per page, not once per read. + +[Contact us](https://www.lancedb.com/contact) to learn more about how +caching is sized and tuned for your workload. + +## Cache interfaces {#interfaces} + +- [Tiered Index Cache](/enterprise/tiered-index-cache) for the related + cache that holds deserialized index structures instead of raw data pages. +- [Query plans](/basics/sql#query-plans) for inspecting what a query actually read. diff --git a/docs/web/enterprise/distributed-compaction.mdx b/docs/web/enterprise/distributed-compaction.mdx new file mode 100644 index 000000000..8d1fb4191 --- /dev/null +++ b/docs/web/enterprise/distributed-compaction.mdx @@ -0,0 +1,83 @@ +--- +title: "Distributed Compaction" +sidebarTitle: "Distributed Compaction" +description: "How LanceDB Enterprise distributes compaction across a fleet of job workers." +icon: "compress" +availability: + embedded: unavailable + enterprise: available +--- + +Distributed compaction splits a table's fragments into independent, +fragment-disjoint tasks and fans them out across job workers in LanceDB +Enterprise. Unlike an index build, a compaction plan needs no bin-packing: +Lance's own planner already produces disjoint tasks, so workers claim and +execute them directly, with no coordination needed to decide who does +what. See [Architecture](/index#architecture). + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + L["Lance's planner
splits fragments into
disjoint tasks"] + L --> W1["Worker
claims fragments 1-2"] + L --> W2["Worker
claims fragments 3-4"] + L --> W3["Worker
claims fragments 5-6"] + W1 --> C["Fleet-wide eligibility gate:
one worker claims the commit"] + W2 --> C + W3 --> C + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class C accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + L["Lance's planner
splits fragments into
disjoint tasks"] + L --> W1["Worker
claims fragments 1-2"] + L --> W2["Worker
claims fragments 3-4"] + L --> W3["Worker
claims fragments 5-6"] + W1 --> C["Fleet-wide eligibility gate:
one worker claims the commit"] + W2 --> C + W3 --> C + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class C accent +``` + +
+ +No task depends on another's result, so a worker that finishes early +simply claims another task rather than waiting on its peers. Committing is +where the fleet does coordinate: finished tasks go through a shared +eligibility gate, and only the one worker that claims the commit actually +writes it, rather than each worker committing its own task independently. + +Whether a failed task can still let the rest commit depends on the remap +mode. Inline remap is all-or-nothing: one failed task fails the whole job, +since the commit updates every affected index inline and can't skip a +task's share of that. Deferred remap can commit a subset -- a failed +task's fragments are abandoned and replanned in a later round, while the +rest of the job's tasks commit without waiting on it. See +[Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution) +for when compaction defers a remap at all. + +## Compaction interfaces {#compaction-interfaces} + +- [Compaction](/maintenance/compaction) for triggering and configuring a compaction. +- [Garbage Collection](/maintenance/cleanup) for removing files compaction and other operations leave behind. +- [Job Framework](/basics/jobs) for the job types a deployment runs on its own schedule. diff --git a/docs/web/enterprise/distributed-indexing.mdx b/docs/web/enterprise/distributed-indexing.mdx new file mode 100644 index 000000000..afbfe30c3 --- /dev/null +++ b/docs/web/enterprise/distributed-indexing.mdx @@ -0,0 +1,88 @@ +--- +title: "Distributed Indexing" +sidebarTitle: "Distributed Indexing" +description: "How LanceDB Enterprise distributes a vector index build across a fleet of workers, stage by stage." +icon: "layer-group" +availability: + embedded: unavailable + enterprise: available +--- + +A vector index build splits into stages, and the data in scope narrows at +each one: training works from a small sample, shuffling touches every row +once, and merging works entirely within one partition at a time. Full-text +and scalar index builds skip training and shuffling -- they bin-pack +directly into independent tasks workers claim and build in parallel, +closer to how [distributed compaction](/enterprise/distributed-compaction) +splits work. See [Architecture](/index#architecture). + +## Stages of a vector index build {#stages} + +1. **Train.** A sample of the table's vectors -- not the full dataset -- + trains the shared model every worker will use: IVF partition centroids, + and for IVF-PQ, a PQ codebook on top of them. +2. **Shuffle.** Every row in the table gets assigned to its nearest + trained partition and regrouped so that all of one partition's rows end + up together, wherever in the table they originally lived. +3. **Merge.** Each partition is now self-contained, so workers build and + merge partitions in parallel with no cross-partition coordination -- + one worker's output never depends on another's. +4. **Commit.** The finished index is committed to the table. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + S["Sample"] --> T["Train IVF centroids
+ PQ codebook"] + T --> Sh["Shuffle: assign every row
to its nearest partition"] + Sh --> M1["Merge
partition A"] + Sh --> M2["Merge
partition B"] + Sh --> M3["Merge
partition C"] + M1 --> C["Commit the
finished index"] + M2 --> C + M3 --> C + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Sh accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + S["Sample"] --> T["Train IVF centroids
+ PQ codebook"] + T --> Sh["Shuffle: assign every row
to its nearest partition"] + Sh --> M1["Merge
partition A"] + Sh --> M2["Merge
partition B"] + Sh --> M3["Merge
partition C"] + M1 --> C["Commit the
finished index"] + M2 --> C + M3 --> C + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Sh accent +``` + +
+ +## Indexing interfaces {#indexing-interfaces} + +The shared indexing guides describe how to build and maintain each index +type: + +- [Vector indexes](/indexing/vector-index) and [vector search](/search/vector-search). +- [Full-text indexes](/indexing/fts-index) and [full-text search](/search/full-text-search). +- [Scalar indexes](/indexing/scalar-index) and [filtering](/search/filtering). +- [Incremental Indexing](/indexing/incremental-indexing) for triggering and tracking a build. diff --git a/docs/web/enterprise/distributed-real-time-read.mdx b/docs/web/enterprise/distributed-real-time-read.mdx new file mode 100644 index 000000000..1b6a582c4 --- /dev/null +++ b/docs/web/enterprise/distributed-real-time-read.mdx @@ -0,0 +1,211 @@ +--- +title: "Distributed RTE Read" +sidebarTitle: "Distributed RTE Read" +description: "How a query combines the real time engine's fresh tier with the ordinary distributed query-serving path, machine to machine." +icon: "network-wired" +availability: + embedded: unavailable + enterprise: available +--- + +[RTE Read](/search/realtime-read) covers what a query against an +RTE-enabled table returns: base-table rows merged with the fresh tier, +fresh rows superseding base rows with the same primary key. On a single +Embedded process that merge is one function call against one Lance +dataset. In LanceDB Enterprise, the base table and the fresh tier are +usually served by different machines -- plan executors for the base table, +an [RTE node](/tables/realtime-engine#wal-nodes) for the table's shards -- +so a query has to combine their results across the network instead. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + Q["Query node
plans the query"] + + subgraph PE["Plan executors"] + direction TB + B1["Base-table arm
index-covered scan or ANN search"] + end + + subgraph WN["RTE node (owns this table's shards)"] + direction TB + W1["SSTable arm
index-covered"] + W2["Active memtable arm
vector: in-memory HNSW*
FTS/scalar: indexed"] + end + + U["Union exec
PK-keyed last-write-wins dedup,
top-K cut on distance"] + + Q --> B1 + Q --> W1 + Q --> W2 + B1 --> U + W1 --> U + W2 --> U + U --> R["Merged result"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class U accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + Q["Query node
plans the query"] + + subgraph PE["Plan executors"] + direction TB + B1["Base-table arm
index-covered scan or ANN search"] + end + + subgraph WN["RTE node (owns this table's shards)"] + direction TB + W1["SSTable arm
index-covered"] + W2["Active memtable arm
vector: in-memory HNSW*
FTS/scalar: indexed"] + end + + U["Union exec
PK-keyed last-write-wins dedup,
top-K cut on distance"] + + Q --> B1 + Q --> W1 + Q --> W2 + B1 --> U + W1 --> U + W2 --> U + U --> R["Merged result"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class U accent +``` + +
+ +## An extra exec node, not a parallel system {#union-exec} + +The distributed plan for an RTE-enabled table is an ordinary plan executor +query plan with one additional node spliced in: a union exec that queries +the owning RTE node's shard and merges its rows into the base arm's stream +by primary key, keeping the newest generation on a collision and cutting +back to the requested top-K once both sides have contributed. An optimizer +pass inserts this node only when the query actually touches an RTE-enabled +table; a query that touches none produces a plan identical to one with no +RTE tables involved at all, so RTE adds no overhead to queries that never +use it. + +Because the base arm already read through the plan-executor fleet's ordinary +caches and index structures, the only new network hop this adds is the one +to the RTE node that owns the table's shards -- the same RTE node [Real Time +writes](/ingestion/realtime-write) land on, found by the query node through +the same consistent hash of database and table name. + +## Search stays index-covered {#index-coverage} + +Every tier the union exec reads from -- the base table, the RTE node's +SSTables, and its currently-active memtable -- is covered by a maintained +index, for vector, full-text, and scalar search alike: + +| Layer | Vector search | Full-text / scalar search | +| --- | --- | --- | +| Base table | ANN index | Maintained index | +| SSTables | ANN index | Maintained index | +| Active memtable | In-memory HNSW graph\* | Maintained index | + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + B["Base table"] --> I1["Vector, full-text, and
scalar index coverage"] + S["SSTables"] --> I1 + M["Active memtable"] --> I2["Full-text and scalar index
coverage; vector via
in-memory HNSW*"] + I1 --> R["No unindexed data
left to scan in full"] + I2 --> R + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class R accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + B["Base table"] --> I1["Vector, full-text, and
scalar index coverage"] + S["SSTables"] --> I1 + M["Active memtable"] --> I2["Full-text and scalar index
coverage; vector via
in-memory HNSW*"] + I1 --> R["No unindexed data
left to scan in full"] + I2 --> R + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class R accent +``` + +
+ +For full-text and scalar search, a maintained index covers every tier the +union exec reads from -- the base table, the RTE node's SSTables, and its +currently-active memtable -- so a row written a moment ago is just as +index-searchable as one written yesterday. If a resident memtable predates +an index being added to the maintained set, the query is rejected outright +rather than silently missing that memtable's rows; there is no code path +that quietly returns an incomplete result. + +Vector (ANN) search follows the same rule for the base table and SSTables. +The active memtable's rows are ANN-searchable too: it builds its own +in-memory HNSW graph as rows land, so writes stay vector-searchable within +milliseconds without waiting for a freeze into an SSTable. \* That graph +search steps aside for a full scan of the memtable only when it can't +honor the query correctly through a graph: a prefilter predicate (graph +traversal can't apply an arbitrary filter first), a primary-key override +that could let a stale near vector occupy a top-K slot a newer row should +have, a distance lower bound (only a full scan can exclude the nearest +rows before the top-K cut), or before the memtable has any index yet on a +cold start. Outside those cases, every committed row -- base table, +SSTables, and the active memtable alike -- is covered by a real index, +with no sliver of unindexed data left to scan in full. + +Both guarantees depend on the table's RTE write spec actually maintaining +the index in question -- by default every index is maintained, but a +deployment that pins a smaller set with `with_maintained_indexes` loses the +guarantee for whatever it leaves out, and a query against an unmaintained +index is rejected the same way, rather than silently searching the base +table alone. + +## What to read next {#next} + + + + What a query returns, and how Embedded does this same merge in-process. + + + How writes reach the RTE node this page's queries read from. + + + The ordinary plan-executor path this layers on top of. + + diff --git a/docs/web/enterprise/distributed-real-time-write.mdx b/docs/web/enterprise/distributed-real-time-write.mdx new file mode 100644 index 000000000..ac91e2d0d --- /dev/null +++ b/docs/web/enterprise/distributed-real-time-write.mdx @@ -0,0 +1,137 @@ +--- +title: "Distributed RTE Write" +sidebarTitle: "Distributed RTE Write" +description: "How Enterprise scales RTE writes horizontally across a dedicated serving tier, and the throughput limits that come with it." +icon: "bolt" +keywords: ["rte", "real time engine", "shard", "sharding", "horizontal scaling", "write throughput"] +availability: + embedded: unavailable + enterprise: available +--- + +[RTE writes](/ingestion/realtime-write) describes `table.enable_rte(spec)` +as one call that works the same way on either connection. On Enterprise, that +call does not run locally -- it posts to the server, which installs the write +path on a dedicated, horizontally scalable serving tier instead of running it +in your process. This page covers that tier: how it shards a table's writes, +the one real limit sharding does not remove, and the throughput you can expect. + +## How writes are routed {#routing} + +Enabling RTE on a remote table sends the spec to the server, which installs +the write path on the dataset instead of running it in your process. From +then on, the query node routes every request for that table -- reads and +writes alike -- to a single owning **RTE node**, a stateful component +separate from the query nodes and plan executors that serve ordinary +queries. A query node routes different tables to different RTE nodes, and +a single RTE node can host shards from many different tables at once. RTE +nodes share nothing but the underlying object storage; no node talks to +another one directly. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + Q["Query node
routes each table's shards to an RTE node"] + + subgraph W0["RTE node A"] + direction TB + S0["Shard 0 — table 'frames'"] + S1["Shard 0 — table 'events'"] + end + + subgraph W1["RTE node B"] + direction TB + S2["Shard 0 — table 'metrics'"] + S3["Shard 1 — table 'metrics'"] + end + + Q -- "'frames'" --> W0 + Q -- "'events'" --> W0 + Q -- "'metrics'" --> W1 + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + Q["Query node
routes each table's shards to an RTE node"] + + subgraph W0["RTE node A"] + direction TB + S0["Shard 0 — table 'frames'"] + S1["Shard 0 — table 'events'"] + end + + subgraph W1["RTE node B"] + direction TB + S2["Shard 0 — table 'metrics'"] + S3["Shard 1 — table 'metrics'"] + end + + Q -- "'frames'" --> W0 + Q -- "'events'" --> W0 + Q -- "'metrics'" --> W1 + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 +``` + +
+ +## Shards scale one table, replicas scale the cluster {#shards-vs-replicas} + +`RTEWriteSpec::bucket(column, num_buckets)` splits a table into `num_buckets` +**table shards**, each a separate, independently-appending stream, giving the +table that many parallel write paths instead of one. A shard's identity is +derived from the table itself, not assigned by an operator, so a shard +survives the table being claimed by a different RTE node later. + +This is where the horizontal scaling actually happens: splitting `frames` +into 8 shards gives it 8 independent append streams instead of 1, raising +that table's own write ceiling. Adding RTE node replicas spreads shard +ownership across more nodes, so the cluster can host more tables -- and more +shards -- without any one node becoming a bottleneck for everything it serves. + +`RTEWriteSpec::identity(column)` and `RTEWriteSpec::unsharded()` both resolve +to a single table shard -- `bucket` is the sharding mode that actually +parallelizes write throughput; the other two are about routing semantics, not +scaling. + +## Throughput {#throughput} + +A table shard is the unit of capacity: measured runs show it sustaining +roughly 85-90 MB/s of durable append before acknowledgement, and throughput +scaling nearly linearly with shard count up to at least 8 shards on one +node -- the bottleneck is the durable write itself, not CPU or memory. This +is observed capacity, not an enforced quota; nothing in the deployment caps +a shard's or a table's throughput below it. [Contact +support](https://www.lancedb.com/contact) if your workload needs more write +throughput than this provides. + +## What to read next {#next} + + + + Enable RTE and write to a table; the same call on Embedded or Enterprise. + + + MemWAL, shards, memtables and SSTables -- the shared architecture. + + + How reads combine the WAL tier's fresh rows with the base table across the fleet. + + diff --git a/docs/web/enterprise/distributed-search.mdx b/docs/web/enterprise/distributed-search.mdx index 8b4e9b233..617c24508 100644 --- a/docs/web/enterprise/distributed-search.mdx +++ b/docs/web/enterprise/distributed-search.mdx @@ -1,6 +1,6 @@ --- -title: "Distributed search" -sidebarTitle: "Distributed search" +title: "Distributed Search" +sidebarTitle: "Distributed Search" description: "How LanceDB Enterprise distributes index execution and table-data reads." icon: "network-wired" availability: @@ -11,15 +11,14 @@ availability: Distributed search spreads index execution, table-data reads, and caching across multiple serving machines in LanceDB Enterprise. Query nodes plan queries and combine results. Plan executors cache index structures and table data and execute -the remote work. See [Architecture](/index#architecture). - -## Embedded search {#embedded-search} - -LanceDB Embedded runs inside your application process. It searches indexes and reads -table data using that process's resources, including its index cache. Reading a -table from object storage does not by itself distribute query execution across -machines. +the remote work -- see [Data Page Cache](/enterprise/data-page-cache) and +[Tiered Index Cache](/enterprise/tiered-index-cache) for how each cache works. +See [Architecture](/index#architecture). + + + + ## Search interfaces {#search-interfaces} The shared search guides describe the query APIs and index settings: @@ -27,4 +26,6 @@ The shared search guides describe the query APIs and index settings: - [Vector search](/search/vector-search) and [vector indexes](/indexing/vector-index). - [Full-text search](/search/full-text-search) and [FTS indexes](/indexing/fts-index). - [Filtering](/search/filtering) and [scalar indexes](/indexing/scalar-index). -- [Query plans](/search/explain) for inspecting execution and runtime measurements. +- [Query plans](/basics/sql#query-plans) for inspecting execution and runtime measurements. +- Expected latency at scale: [vector search](/search/vector-search#expected-performance) + and [full-text search](/search/full-text-search#expected-performance). diff --git a/docs/web/enterprise/distributed-write.mdx b/docs/web/enterprise/distributed-write.mdx new file mode 100644 index 000000000..73df91cf1 --- /dev/null +++ b/docs/web/enterprise/distributed-write.mdx @@ -0,0 +1,90 @@ +--- +title: "Distributed Write" +sidebarTitle: "Distributed Write" +description: "How LanceDB Enterprise distributes a CTAS import's writes across plan executors." +icon: upload +availability: + embedded: unavailable + enterprise: available +--- + +Distributed write applies specifically to importing data with `CREATE +TABLE ... AS SELECT`: the query node that planned the statement partitions +the source -- Parquet files from a HuggingFace dataset, or row-group +ranges of an existing Lance dataset in object storage -- across plan +executors, each of which writes its own uncommitted Lance data files and +reports back. The query node collects those results and commits them +together as the new table's first version; no separate coordinator +service is involved. See [Architecture](/index#architecture). + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + S["Source
HuggingFace Parquet, or an
existing Lance dataset in
S3 / GCS / Azure"] + Q["Query node
plans the CTAS,
commits the result"] + PE1["Plan executor
writes uncommitted files"] + PE2["Plan executor
writes uncommitted files"] + PE3["Plan executor
writes uncommitted files"] + + S --> Q + Q --> PE1 + Q --> PE2 + Q --> PE3 + PE1 --> Q + PE2 --> Q + PE3 --> Q + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Q accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + S["Source
HuggingFace Parquet, or an
existing Lance dataset in
S3 / GCS / Azure"] + Q["Query node
plans the CTAS,
commits the result"] + PE1["Plan executor
writes uncommitted files"] + PE2["Plan executor
writes uncommitted files"] + PE3["Plan executor
writes uncommitted files"] + + S --> Q + Q --> PE1 + Q --> PE2 + Q --> PE3 + PE1 --> Q + PE2 --> Q + PE3 --> Q + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Q accent +``` + +
+ +An ordinary `INSERT` or `merge_insert`, from SQL or the SDK, does not +distribute this way -- it runs as a single write, on whichever node or +process executes it. Only a CTAS import fans the write itself out across +machines. + +## Write interfaces {#write-interfaces} + +- [Import Datasets](/ingestion/import) for the CTAS syntax this + distributes. +- [Insert data](/ingestion/insert) and [Merge](/ingestion/merge-insert) + for the ordinary, non-distributed write paths. +- [Storage Integration](/sql/ddl/storage-integration) for configuring + the source a CTAS import reads from. diff --git a/docs/web/enterprise/horizontal-scaling.mdx b/docs/web/enterprise/horizontal-scaling.mdx new file mode 100644 index 000000000..8b8f5c6fa --- /dev/null +++ b/docs/web/enterprise/horizontal-scaling.mdx @@ -0,0 +1,217 @@ +--- +title: "Horizontal Scaling" +sidebarTitle: "Horizontal Scaling" +description: "How LanceDB Enterprise spreads serving capacity for a table across replica groups, and replicates it within each one." +icon: "arrows-left-right" +availability: + embedded: unavailable + enterprise: available +--- + +LanceDB Enterprise scales serving capacity by assigning a table to one or +more **replica groups** -- numbered subsets of the plan-executor fleet -- +and, within each group, by **replication factor** (RF): how many copies of +the table's data that group holds. A table is served only from the groups +it is explicitly assigned to; adding plan executors to the fleet, or adding +a new group, never auto-includes existing tables. A pristine table that was +never explicitly placed stays on one default group at the cluster's default +RF. See [Architecture](/index#architecture). + +Placement is stored in the table's own manifest, not a separate +configuration store, and takes effect for a table within its readers' +read-consistency refresh interval after a change. An index can carry its +own RF override within each of the table's groups instead of inheriting +the table's RF. Reassigning a table's groups or RF is an operator action +(through the admin API, not SQL); [contact support](https://www.lancedb.com/contact) +to change a table's placement. + +Replica groups are numbered subsets of the fleet, not per-table resources -- +different tables can share a group, use entirely different groups, or +overlap partially, and each picks its own RF independently within every +group it uses: + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TB + subgraph G0["Replica group 0"] + direction LR + G0A["Plan executor"] + G0B["Plan executor"] + end + + subgraph G1["Replica group 1"] + direction LR + G1A["Plan executor"] + end + + subgraph G2["Replica group 2"] + direction LR + G2A["Plan executor"] + G2B["Plan executor"] + G2C["Plan executor"] + end + + TA["Table A
groups 0, 1 · RF 2 in group 0, RF 1 in group 1"] -.-> G0 + TA -.-> G1 + TB["Table B
group 2 only · RF 3"] -.-> G2 + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class TA,TB accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TB + subgraph G0["Replica group 0"] + direction LR + G0A["Plan executor"] + G0B["Plan executor"] + end + + subgraph G1["Replica group 1"] + direction LR + G1A["Plan executor"] + end + + subgraph G2["Replica group 2"] + direction LR + G2A["Plan executor"] + G2B["Plan executor"] + G2C["Plan executor"] + end + + TA["Table A
groups 0, 1 · RF 2 in group 0, RF 1 in group 1"] -.-> G0 + TA -.-> G1 + TB["Table B
group 2 only · RF 3"] -.-> G2 + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class TA,TB accent +``` + +
+ +Table A is assigned to groups 0 and 1, at RF 2 and RF 1 respectively -- +three plan executors total hold a copy of Table A. Table B never touches +groups 0 or 1 at all; it is assigned only to group 2, at RF 3. Group 2's +plan executors serve no part of Table A, and group 0's plan executors +serve no part of Table B. Raising Table B's RF to 3 did not add a single +plan executor to Table A's serving path, and vice versa -- each table's +placement decision only changes which plan executors hold *that* table's +data. + +## Why this scales serving {#why} + +More replicas of a hot table's data, across more plan executors, means +more of the fleet can serve that table's queries in parallel -- the same +reasoning as adding query-serving capacity generally (see +[Architecture](/index#architecture)), applied per table rather than +cluster-wide. Replication also gives a table fault tolerance: losing one +plan executor does not take its data offline if another replica still +holds it. + +A single query that reads several tables routes every read to the same +replica group -- the intersection of the tables' assigned groups, trying a +lead group first and falling back through the rest of the order if it has +no healthy plan executor. Keeping one query's reads co-located protects the +locality of whichever group's cache is already warm for it, rather than +letting each table's read drift to a different group. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + Q["Query node
routes to the lead group"] + + subgraph G0["Replica group 0 (lead)"] + direction LR + A0["Plan executor
copy 1"] + A1["Plan executor
copy 2"] + end + + subgraph G1["Replica group 1 (fallback)"] + direction LR + B0["Plan executor
copy 1"] + B1["Plan executor
copy 2"] + end + + Q --> A0 + Q --> A1 + Q -. "only if group 0 has no healthy PE" .-> B0 + Q -. "only if group 0 has no healthy PE" .-> B1 + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Q accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + Q["Query node
routes to the lead group"] + + subgraph G0["Replica group 0 (lead)"] + direction LR + A0["Plan executor
copy 1"] + A1["Plan executor
copy 2"] + end + + subgraph G1["Replica group 1 (fallback)"] + direction LR + B0["Plan executor
copy 1"] + B1["Plan executor
copy 2"] + end + + Q --> A0 + Q --> A1 + Q -. "only if group 0 has no healthy PE" .-> B0 + Q -. "only if group 0 has no healthy PE" .-> B1 + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Q accent +``` + +
+ +This table is assigned to two replica groups, each at replication factor +2: four plan executors in total, each holding a full copy of the table's +data. Adding a third group, or raising RF within a group, adds more +plan executors that can serve this table's reads in parallel -- scaling +throughput for this one table without touching any other table's +placement. + +## Scaling interfaces {#scaling-interfaces} + +- [Distributed Search](/enterprise/distributed-search) for how a query + divides across query nodes and plan executors generally. +- [Architecture](/index#architecture) for the components a replica group + is made of. diff --git a/docs/web/enterprise/incremental-refresh.mdx b/docs/web/enterprise/incremental-refresh.mdx new file mode 100644 index 000000000..395df3a25 --- /dev/null +++ b/docs/web/enterprise/incremental-refresh.mdx @@ -0,0 +1,51 @@ +--- +title: "Incremental Refresh" +sidebarTitle: "Incremental Refresh" +description: "Why refreshing a computed column only recomputes fragments that hold a row whose inputs actually changed." +icon: "arrow-rotate-right" +availability: + embedded: unavailable + enterprise: available +--- + +Refreshing a [computed column](/feature-engineering/add-computed-column) +is incremental: it fills rows that have no value yet and recomputes the +fragments that hold a row whose input changed since it was last computed, +leaving every other fragment alone. A second refresh with nothing changed +does nothing. The +planner finds the rows that actually need work by checking which +fragments still carry stale or empty values for the column, then groups +them into claimable units a fleet of job workers can pick up in parallel +-- see [Architecture](/index#architecture). + + +A **materialized view** doesn't track stale rows the way a computed +column does -- there's no smaller unit than the whole view to recompute +from a saved query. In LanceDB Embedded, every refresh rebuilds the view +completely with no incremental step; LanceDB Enterprise's server chooses +the refresh mode instead, unless the caller forces a full rebuild. See +[Refresh a materialized view](/feature-engineering/refresh-materialized-view). + + +## Why this matters {#why} + +Appending rows is cheap: the next refresh only fills what's new, not what +it already computed. Updating an input row is also cheap in the same +way -- the derived column keeps its old value until the next refresh +notices the input changed. Staleness is tracked per fragment, not per +row: the refresh recomputes every row in a fragment where at least one +input moved, which can re-evaluate rows whose own value didn't actually +need it, not strictly only the row that changed. Nothing is recomputed +between refreshes, so a derived column can be stale right up until you +call for one. + +## What to read next {#next} + + + + The exact fill/recompute/leave-alone rules, with examples. + + + How the units this planner produces get sized and run. + + diff --git a/docs/web/enterprise/index.mdx b/docs/web/enterprise/index.mdx deleted file mode 100644 index 1c3a893a2..000000000 --- a/docs/web/enterprise/index.mdx +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: "LanceDB Enterprise" -sidebarTitle: "Overview" -description: "What a deployment adds over LanceDB Embedded." -icon: building -keywords: ["enterprise", "deployment", "cluster"] ---- - -Enterprise - -This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it. See -[Architecture](/index#architecture) for what differs between the two. - -LanceDB Enterprise runs the lakehouse as a service: a control plane for -configuration, identity and policy; a data plane serving reads and writes; and -indexers building indexes and compacting outside the request path. - -What it adds over the embedded form: - -| | | -| --- | --- | -| [SQL](/sql) | an Arrow Flight SQL endpoint | -| [Jobs](/basics/jobs) | server-side work with ids, status and events | -| [Authorization](/governance/authorization) | per-object grants | -| Scale | a cluster rather than your process | - -{/* -Draft for the Functions release. Add this row to the table above, after SQL: -| [Functions](/management/function) | Python running on workers | -*/} - -See [Architecture](/index#architecture) for the two shapes side by side. - -## Getting a deployment {#deployment} - -Deployment is specific to your cloud and account, so the procedure is -published with LanceDB Enterprise rather than here. -[Contact us](https://www.lancedb.com/contact) to get started; see the -[Kubernetes deployment guide](/enterprise/deployment/kubernetes) for a worked example. -Embedded LanceDB has nothing to deploy: it is a library your process links -against. See [LanceDB Embedded](/index#1-lancedb-oss). diff --git a/docs/web/enterprise/intelligent-auto-maintenance.mdx b/docs/web/enterprise/intelligent-auto-maintenance.mdx new file mode 100644 index 000000000..38cbdd2a5 --- /dev/null +++ b/docs/web/enterprise/intelligent-auto-maintenance.mdx @@ -0,0 +1,178 @@ +--- +title: "Intelligent Auto-Maintenance" +sidebarTitle: "Intelligent Auto-Maintenance" +description: "How Enterprise continuously tracks table activity in the background and decides what maintenance -- compaction, cleanup, indexing, remap catch-up -- a table needs next." +icon: "brain" +keywords: ["agent", "planning", "scheduling", "maintenance", "planner", "table events", "coverage", "cleanup", "automated", "retention", "gc", "version_interval", "min_age_seconds"] +availability: + embedded: unavailable + enterprise: available +--- + +Keeping a table in good condition takes several different kinds of work -- +compacting files, catching indexes up, cleaning old versions, folding a +RTE write tier into the base table -- each with its own trigger. In +LanceDB Enterprise, a fleet of agent processes decides when each of these +needs to run, continuously, per table, in the background across your +cluster -- nothing to schedule, trigger, or monitor by hand unless you want +to. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + E["Table event notifications"] --> P + S["Periodic sweep
every table, on a timer"] --> P + P["Planner
evaluates one table"] + P --> W["Possible next step:
WAL index catch-up"] + P --> I["Possible next step:
Index operations"] + P --> C["Possible next step:
Compaction"] + P --> CL["Possible next step:
Cleanup"] + P --> R["Possible next step:
Remap catch-up"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class P accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + E["Table event notifications"] --> P + S["Periodic sweep
every table, on a timer"] --> P + P["Planner
evaluates one table"] + P --> W["Possible next step:
WAL index catch-up"] + P --> I["Possible next step:
Index operations"] + P --> C["Possible next step:
Compaction"] + P --> CL["Possible next step:
Cleanup"] + P --> R["Possible next step:
Remap catch-up"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class P accent +``` + +
+ +## Tracking activity {#tracking} + +An agent's long-running process watches two independent sources for a +table: **table events** (Job Registry notifications, so it learns about a +write, a schema change, or a new index almost immediately) and a +**periodic sweep** that revisits every table it owns on a timer -- 600 +seconds by default -- so a table that stops producing events still gets +re-evaluated rather than going stale. A hot table producing a flood of +events does not get to monopolize evaluation: notifications and the +periodic sweep share a bounded per-tick budget, and reads for a given table +run at most once at a time. + +Each evaluation reopens the table and reads its manifest, indexes and +in-flight jobs fresh, rather than deciding from a cached guess. Those are +separate reads rather than one atomic snapshot, so a concurrent write +between them is possible; the next evaluation -- triggered by that same +write's own event notification -- is what catches anything the current +one missed. + +## Deciding what to run {#deciding} + +A table is not reduced to one "next best action" -- each evaluation walks a +fixed, priority-ordered sequence of independent decisions, launching +whichever ones are due: + +1. **WAL index catch-up.** Checked first and gated by nothing else, because + it is correctness-driven rather than discretionary: while an index lags + behind the compacted generation, the RTE write tier cannot trim its + log. See [RTE Compaction](/enterprise/realtime-engine-compaction). +2. **Index operations.** Reindexing a column, unless a compaction that + cannot defer its remap is about to run this same tick -- deferred-remap + compaction lets index work proceed alongside it instead of waiting. See + [Incremental Indexing](/indexing/incremental-indexing). +3. **Compaction.** Whether enough small fragments or deleted rows have + accumulated to merge. See [Compaction](/maintenance/compaction) and + [Distributed Compaction](/enterprise/distributed-compaction). +4. **Cleanup.** Independent of the other four -- it can always run in + parallel with them. [See below](#cleanup) for exactly when it's due. +5. **Deferred-remap catch-up.** The batched, amortized follow-up for index + entries a deferred compaction didn't remap synchronously. See + [Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution). + +More than one of these can fire for the same table in the same evaluation -- +a compaction and a cleanup are unrelated and can both launch together -- but +some gate each other where running them at the same time would be unsafe, +like index operations waiting on a compaction that can't defer its remap. + +### When cleanup is due {#cleanup} + +[Cleanup](/maintenance/cleanup) prunes old table versions and the files only +they referenced. In LanceDB Embedded, that always happens because you asked +for it -- a call to `optimize()`. LanceDB Enterprise does not support a +manual `optimize()` call at all; cleanup there is entirely this planner's own +decision, off by default unless the deployment sets a minimum version age -- +with no minimum age configured, nothing is ever old enough to clean up +automatically, and old versions simply accumulate until an operator enables +it. A table can also disable it individually even when the deployment allows +it, overriding the deployment-wide setting for just that table. + +Once enabled, a table becomes due for cleanup when any one of these is true: + +| Trigger | Condition | +| --- | --- | +| Enough new versions | The current version has advanced far enough past the version the last successful cleanup started from | +| Enough time has passed | The last successful cleanup finished long enough ago -- the default is 24 hours -- so an idle table whose versions simply age past the retention window still gets revisited | +| Version went backward | The current version is lower than the version the last successful cleanup recorded, which re-triggers a run immediately | + +A table that has never had a successful cleanup run is held to its own +initial version threshold first, so a brand-new table is not claimed for +cleanup before it has accumulated enough versions to be worth the pass. A +failed attempt is retried, but not immediately -- a minimum delay (60 +seconds by default) must pass after the failure before the table becomes +eligible again, even if one of the triggers above would otherwise fire. + +## Confirming it's actually running {#observability} + +Rather than asking you to trust that evaluation is happening, the agent +exposes coverage metrics scoped to *successful* evaluations specifically -- +a failed or timed-out attempt does not count: + +| Metric (`lance_agent_` prefix) | What it tells you | +| --- | --- | +| `coverage_never_evaluated` | Tables this agent owns that have never completed an evaluation | +| `coverage_oldest_success_age_seconds` | How long it's been since the longest-overdue table was last successfully evaluated | +| `coverage_cycle_target` / `coverage_cycle_pending` | How much work the current full sweep has left | +| `coverage_cycles_completed_total` | How many full sweeps have finished | + +A cycle freezes its target set of tables up front; new tables join the +*next* cycle rather than resetting progress on the current one, and a table +that disappears or changes ownership is dropped from the target rather than +counted as covered. + +## What to read next {#next} + + + + What a cleanup pass actually removes, and the retention window it respects. + + + Why compaction and index maintenance need the deferred-remap decision at all. + + + The WAL-tier compaction this page's Decision 1 depends on. + + + What an index operation actually does once scheduled. + + + Viewing the `lance_agent_*` coverage metrics above. + + diff --git a/docs/web/enterprise/realtime-engine-compaction.mdx b/docs/web/enterprise/realtime-engine-compaction.mdx new file mode 100644 index 000000000..e04429ab8 --- /dev/null +++ b/docs/web/enterprise/realtime-engine-compaction.mdx @@ -0,0 +1,209 @@ +--- +title: "Real Time Engine compaction" +sidebarTitle: "RTE Compaction" +description: "How Enterprise automatically folds a Real Time Engine shard's SSTables into the base table and catches its indexes up." +icon: "compress" +availability: + embedded: unavailable + enterprise: available +--- + +[Distributed Compaction](/enterprise/distributed-compaction) merges small +base-table fragments and reclaims deleted rows -- the same operation +[Compaction](/maintenance/compaction) describes for LanceDB Embedded. A +table with the [real time engine](/tables/realtime-engine) enabled has a +second, unrelated compaction: folding a shard's accumulated SSTables into +the base table and catching the base table's indexes up over the rows that +just landed. This produces two job types, `memwal_compaction` and +`memwal_catchup_`, already distinct from ordinary `compact` in +`SHOW JOBS` and `list_jobs`. This page covers how Enterprise decides when +to run them, not just what they do. + +## What triggers a compaction pass {#trigger} + +A per-pod loop, ticking every `WAL_COMPACTION_INTERVAL_SECS` (5s by +default), walks every table this pod owns and reads each shard's manifest. +It dispatches a compaction job for a shard once any threshold crosses: + +| Trigger | Default | Checks | +| --- | --- | --- | +| `WAL_COMPACT_TRIGGER_COUNT` | 4 | The shard's SSTable count | +| `WAL_COMPACT_TRIGGER_BYTES` | 1 GiB | The shard's total flushed SSTable bytes | +| Oldest generation's age | 7 days | How long the head SSTable generation has sat, whatever the file count -- a file that will never gather enough siblings to cross the count trigger still gets compacted eventually | + +Whichever crosses first wins. A shard under write pressure does not wait +for the next tick either: the same thresholds are re-checked on every +backpressure relief pass, so a hot shard that already qualifies compacts +sooner than `WAL_COMPACTION_INTERVAL_SECS` would otherwise allow. Setting +`WAL_COMPACTION_INTERVAL_SECS` to `0` disables the periodic walk; an +operator can still force a pass with `POST /v1/compact`, and +`Table::checkpoint_rte` drives the same flush-then-compact cycle from the +client when you need a table to converge on demand rather than wait for +the trigger. `checkpoint_rte` has no liveness bound of its own -- it is +idempotent and abandonable at any point, but the caller owns the deadline +for how long to wait on it. + +This trigger decision is internal to the WAL pod -- it is not the general +job scheduler deciding to run `memwal_compaction`, the pod decides to +enqueue one. Once enqueued, the work is still tracked as an ordinary job +(`memwal_compaction`, then `memwal_catchup_` once it lands), so +`SHOW JOBS` and `list_jobs` surface it the same way they surface any other +background job. + +## What one pass does {#pass} + +By default (`wal.remoteMaintenance` is on), a tick's passes are offloaded +as ordinary Job Registry worker jobs instead of running in the WAL pod +itself, up to `WAL_COMPACT_CONCURRENCY` at a time (32 by default). With +remote maintenance off, the pod runs them itself, in a per-pod compactor +pool shared across every table it owns, bounded to 2 concurrent passes +instead. Either way, each pass: + +1. Snapshots the shard's current list of SSTables. +2. Takes a bounded prefix of them, oldest first (`WAL_COMPACT_PREFIX_MAX`, + 32 by default), further capped at `COMPACT_PASS_TARGET_BYTES` (2 GiB) + -- a budget every in-pod pass shares, but that an offloaded pass gets + in full to itself. +3. Opens each as a Lance file and scans its rows. +4. Deduplicates across the prefix by primary key -- a later SSTable's row + wins over an earlier one with the same key. +5. Merges the deduplicated rows into the base table with `merge_insert`. +6. Commits a manifest update that drops exactly the SSTables just folded + in, identified individually rather than by position, so a retried + commit against a newer manifest can't drop the wrong ones. +7. `memwal_catchup_` then extends each of the base table's indexes + -- one job per index type (`memwal_catchup_btree`, `memwal_catchup_fts`, + `memwal_catchup_ivfpq`, and so on) -- over the rows step 5 just added, + and records how far that index has caught up. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + A["Shard crosses a trigger
(count, bytes, or generation age)"] --> B["Per-pod trigger loop
or backpressure relief pass"] + B --> C["Compactor pool
dedup by PK, merge_insert into base"] + C --> D["Manifest drops
the folded SSTables"] + D --> E["memwal_catchup_<type>
extends each base index"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + A["Shard crosses a trigger
(count, bytes, or generation age)"] --> B["Per-pod trigger loop
or backpressure relief pass"] + B --> C["Compactor pool
dedup by PK, merge_insert into base"] + C --> D["Manifest drops
the folded SSTables"] + D --> E["memwal_catchup_<type>
extends each base index"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 +``` + +
+ +Only one compaction pass runs against a given shard at a time. A second, +concurrent pass against the same shard would corrupt it: a stale pass can +overwrite rows a newer generation already replaced, or resurrect a row a +newer generation deleted, since the merge step has no way to tell a +late-arriving write from a value that was already superseded. A per-shard +latch enforces this -- the periodic trigger skips a shard that's already +compacting, a manual `POST /v1/compact` is refused outright (never queued) +on the same collision, and node drain waits for the shard's current pass +instead of skipping it, since a skipped table is exactly what drain exists +to flush. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TD + Shard["Shard's per-shard latch"] --> Held{"Already held by
an in-progress pass?"} + Held -->|no| Grant["Grant the latch,
run the pass"] + Held -->|yes, periodic trigger| Skip["Skip this tick --
retried next tick"] + Held -->|yes, manual POST /v1/compact| Refuse["Refused outright,
never queued"] + Held -->|yes, node drain| Wait["Wait for the current
pass to finish, don't skip"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Shard accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart TD + Shard["Shard's per-shard latch"] --> Held{"Already held by
an in-progress pass?"} + Held -->|no| Grant["Grant the latch,
run the pass"] + Held -->|yes, periodic trigger| Skip["Skip this tick --
retried next tick"] + Held -->|yes, manual POST /v1/compact| Refuse["Refused outright,
never queued"] + Held -->|yes, node drain| Wait["Wait for the current
pass to finish, don't skip"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Shard accent +``` + +
+ +## Reading while compaction runs {#reads} + +A query against an RTE-enabled table always reads the shard's current +memtable and SSTables unioned with the base table, regardless of where a +compaction pass is in its cycle -- compaction only ever changes which side +of that union a row's latest value lives on, never which value is +current. There's no window where a row is visible in neither side: the +manifest update in step 6 is the single point where a row's SSTable copy +stops being listed, and it only commits after `merge_insert` has already +written that row into the base table. + +A table queried *without* the real time engine's live path only sees data +once it has been folded into the base table, so its staleness bound tracks +whichever trigger fires -- wider either way than the real time engine's +own millisecond-scale freshness. A shard under steady write pressure +compacts on the count or bytes trigger, within `WAL_COMPACTION_INTERVAL_SECS` +plus the compaction job's own runtime. A shard that never gathers enough +siblings or bytes instead waits on the age trigger, up to 7 days by +default, before it's compacted at all. `WAL_MAX_DATA_AGE_SECS` bounds two +independent stages -- the memtable freeze and this compaction age trigger +-- so a slow table's worst-case staleness without the live path is up to +roughly twice that default, not one interval plus one job's runtime. +Either way, the bound also assumes a free compaction slot when +the shard becomes eligible; an eligible shard can wait in queue behind +`WAL_COMPACT_CONCURRENCY` other passes already running, so the actual +delay can run longer than the trigger alone suggests. See +[RTE reads](/search/realtime-read) +for what a live RTE read sees instead. + +## What to read next {#next} + + + + The MemWAL format, shards, and WAL nodes this page assumes. + + + The unrelated, ordinary compaction every table -- WAL-enabled or not -- gets. + + + Job handles, waiting, and inspecting jobs -- memwal_compaction included. + + diff --git a/docs/web/enterprise/security.mdx b/docs/web/enterprise/security.mdx index 96846daa0..367e71b51 100644 --- a/docs/web/enterprise/security.mdx +++ b/docs/web/enterprise/security.mdx @@ -14,7 +14,8 @@ of LanceDB has no server to provide it. See Compliance posture (certifications, data residency, encryption at rest and in transit, audit logging) is a property of a deployment, so it is documented -with LanceDB Enterprise. +with LanceDB Enterprise. See [Audit Log](/governance/audit-log) for the +audit log's schema and how to query it. For LanceDB Embedded, these are properties of the object store you point it at and the process you run it in; LanceDB adds no layer of its own. diff --git a/docs/web/enterprise/tiered-index-cache.mdx b/docs/web/enterprise/tiered-index-cache.mdx new file mode 100644 index 000000000..692477498 --- /dev/null +++ b/docs/web/enterprise/tiered-index-cache.mdx @@ -0,0 +1,90 @@ +--- +title: "Tiered Index Cache" +sidebarTitle: "Tiered Index Cache" +description: "How LanceDB Enterprise caches deserialized index structures across memory and local disk." +icon: "layer-group" +availability: + embedded: unavailable + enterprise: available +--- + +The tiered index cache holds deserialized vector, full-text and scalar +index structures in memory, backed by a local-disk tier beneath it. When +memory fills, the cache serializes evicted entries and spills them to disk +instead of dropping them; a later hit on a spilled entry promotes it back +into memory. This lets a plan executor serve an index larger than its +available memory without re-reading and re-deserializing it from object +storage on every eviction. See [Architecture](/index#architecture). + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + R["Index lookup"] --> M{"In memory?"} + M -->|hit| Return["Served from memory"] + M -->|miss| D{"Spilled to disk?"} + D -->|hit| Promote["Deserialized,
promoted into memory,
served"] + D -->|miss| O[("Object storage")] + O --> Fill["Deserialized,
loads into memory,
served"] + + Evict["Memory eviction"] -.->|serialize, don't drop| D + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + R["Index lookup"] --> M{"In memory?"} + M -->|hit| Return["Served from memory"] + M -->|miss| D{"Spilled to disk?"} + D -->|hit| Promote["Deserialized,
promoted into memory,
served"] + D -->|miss| O[("Object storage")] + O --> Fill["Deserialized,
loads into memory,
served"] + + Evict["Memory eviction"] -.->|serialize, don't drop| D + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 +``` + +
+ +## Sharing the disk budget {#disk-budget} + +Where enabled, the index disk tier and the +[data page cache](/enterprise/data-page-cache)'s disk tier draw from one +combined, configurable disk allocation per executor, split between the two +tiers so neither one needs its own dedicated volume. + +## Why it matters {#why-it-matters} + +Vector, full-text, and scalar indexes can easily outgrow available memory +on large tables. Without this cache, an eviction means re-reading and +re-deserializing that index from object storage on the next request -- +slow, and repeated on every eviction. Spilling to local disk instead keeps +index lookups fast even when the working set is larger than memory, without +giving every executor enough memory to hold every index at once. + +[Contact us](https://www.lancedb.com/contact) to learn more about how +caching is sized and tuned for your workload. + +## Index cache interfaces {#interfaces} + +- [Cache Prewarm](/enterprise/cache-prewarm) for warming this cache ahead + of the first request. +- [Data Page Cache](/enterprise/data-page-cache) for the related cache + that holds raw table data pages instead of deserialized index structures. +- [Vector indexes](/indexing/vector-index), [full-text indexes](/indexing/fts-index), + and [scalar indexes](/indexing/scalar-index) for the index types this + cache serves. diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index aecb0acf0..2c9e9be4c 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -5,17 +5,12 @@ description: "Declare a column from a SQL expression. Nothing is evaluated until icon: table-columns keywords: ["computed columns", "add_columns", "transforms", "schema"] availability: - embedded: available + embedded: unavailable enterprise: available --- import { PySchemaAddSetup, - TsSchemaAddSetup, - RsSchemaAddSetup, - PyAddColumnsCalculated, - TsAddColumnsCalculated, - RsAddColumnsCalculated, } from '/snippets/tables.mdx'; Lance can write a new column without rewriting the columns already in the @@ -31,39 +26,106 @@ cheap on any table size, because nothing is evaluated until [a refresh](/feature-engineering/refresh-column) asks for it. -In the 0.41 SDK release, computed-column declaration and refresh in LanceDB Embedded require a -source build with the `experimental-functions` Cargo feature. Published Python -and TypeScript packages leave it disabled. LanceDB Enterprise operations -do not require this feature. Ordinary eager `add_columns` transforms remain available. +`computed` requires LanceDB Enterprise. Ordinary eager `add_columns` +transforms, without `computed`, remain available in LanceDB Embedded. -## Add a computed column {#declare} +## Fill a column with a Function {#functions} -```python -import lancedb +Enterprise -db = lancedb.connect("./.lancedb") +When the value cannot be expressed in SQL -- an embedding, a model call, an +image decode -- the column is filled by a registered +[function](/management/function) instead of a SQL expression. It needs a +deployment with Functions enabled. + +Connect with an [Enterprise connection](/basics/catalog#enterprise). +Continuing the [`caption` Function](/curation/create-function#chain) +registered in Create a Function, against a `frames` table that already has +a `jpeg` column: + + +```python Python icon="python" +version = db.create_function_async(caption).wait() +table.add_columns({"caption": version(jpeg=col("jpeg"))}) +``` + +```sql SQL icon="database" +ALTER TABLE frames ADD COLUMN caption AS caption(jpeg) WITH (version = 'fv_1') +``` + + +A Function application is called with its parameters bound to source +columns through `col(...)`, keyed by the output column name. It commits a +new, empty table version the same way a SQL expression does, so the usual +[versioning](/management/table#versioning) applies. + +Both a Function application and a SQL expression accept the same +`auto_refresh_enabled` and `auto_refresh_interval_seconds` options, and both +refresh and toggle the same way; see [Auto Refresh](/enterprise/auto-refresh). + +## Fill a column with a SQL expression {#expressions} + +A value that SQL can compute doesn't need a Function. Declare it with +`computed` instead, as an expression evaluated over the row: + + +```python Python icon="python" table = db.create_table("computed_demo", [{"x": 1}, {"x": 2}]) table.add_columns(computed={"doubled": "x * 2"}) # AddColumnsResult(version=2) ``` +```sql SQL icon="database" +ALTER TABLE computed_demo ADD COLUMN doubled AS x * 2 +``` + + That commits a new table version with the column present and empty. It is an ordinary table version, so the usual [versioning](/management/table#versioning) applies, including that you can travel back to before the column existed. +The expression can reference any column in the table, including another +computed column -- declaration order is dependency order, so it may +reference one declared earlier in the same mapping, but not one declared +after it: + + +```python Python icon="python" +table.add_columns(computed={ + "power_score": "cast(x as double) / 2.0", + "is_strong": "power_score > 0.5", +}) +``` + +```sql SQL icon="database" +ALTER TABLE computed_demo ADD COLUMN power_score AS cast(x as double) / 2.0 +ALTER TABLE computed_demo ADD COLUMN is_strong AS power_score > 0.5 +``` + + +The functions available are the ones the +[SQL dialect](/sql/dql/functions) documents. + +A literal in the expression has to fit the column it meets: `x / 2.0` is +refused when `x` is an integer column, so write `cast(x as double) / 2.0`. + + +Keep the expression to top-level columns. A column refresh can fail on an +expression that reads a field inside a struct, such as +`stats.magic + stats.strength`. Try a new expression on a small table first. + + ## Compute now or on refresh {#computed-vs-transforms} `add_columns` takes either, and the difference matters: - **SQL expressions in `transforms`** are evaluated *now*, for every row, as part of the call. Good for a small table, or a column you want populated - immediately. - {/* Draft for the Functions release: - A `FunctionApplication` passed through `transforms` instead + immediately. A `FunctionApplication` passed through `transforms` instead declares empty Function-bound columns, which a refresh fills; that needs a - deployment with Functions enabled, and the embedded library refuses it. */} + deployment with Functions enabled, and the embedded library refuses it. - **`computed`** stores the expression and evaluates nothing. The column is committed empty and filled later by [`refresh_column`](/feature-engineering/refresh-column). @@ -71,21 +133,27 @@ including that you can travel back to before the column existed. `computed` and `transforms` cannot be combined in one call. Reach for `computed` when the table is large enough that you would rather control when the work happens. -Pass `auto_refresh_enabled` and `auto_refresh_interval_seconds` alongside -`computed` to have the server keep the column refreshed instead of calling -[`refresh_column`](/feature-engineering/refresh-column) yourself: +Automatic refresh is on by default for each computed column, and takes effect +when your Enterprise deployment enables its refresh scheduler. Until then, +call [`refresh_column`](/feature-engineering/refresh-column) yourself. Pass +`auto_refresh_enabled=False` to opt a column out, or +`auto_refresh_interval_seconds` to set how often it refreshes: -```python + +```python Python icon="python" table.add_columns( computed={"doubled": "x * 2"}, - auto_refresh_enabled=True, auto_refresh_interval_seconds=300, ) ``` -A local table stores these settings but does not act on them -- automatic -scheduling runs on LanceDB Cloud or Enterprise. See -[Automatic refresh](/feature-engineering/refresh-column#automatic) for the +```sql SQL icon="database" +ALTER TABLE computed_demo ADD COLUMN doubled AS x * 2 +WITH (auto_refresh_interval_seconds = 300) +``` + + +See [Auto Refresh](/enterprise/auto-refresh) for the full behavior, including how to change the setting later. An eager `transforms` call looks like this, starting from a small product @@ -95,30 +163,26 @@ table: {PySchemaAddSetup} - - - {TsSchemaAddSetup} - - - - {RsSchemaAddSetup} -
- - {PyAddColumnsCalculated} - +```python Python icon="python" +# Add a discounted price column (10% discount) +table.add_columns({"discounted_price": "cast((price * 0.9) as float)"}) +``` - - {TsAddColumnsCalculated} - - - - {RsAddColumnsCalculated} - +```sql SQL icon="database" +ALTER TABLE schema_evolution_add_example ADD COLUMN discounted_price +AS cast((price * 0.9) as float) +``` +SQL's `ADD COLUMN ... AS` always declares the column empty and defers the +expression to a refresh, the same as `computed` does -- there is no SQL +form of eager `transforms`. The Python call above is the only way to get +discounted_price filled immediately; declaring it in SQL fills it only +once [`REFRESH COLUMN`](/sql/dml/refresh-column) runs. + For feature engineering on large existing tables, group related derived features into one `add_columns` call instead of running many separate writes: this creates one new table version for the schema change and @@ -126,43 +190,19 @@ computes every new column from the existing rows in it, rather than growing the table's version history with many small updates. -`add_columns` does not accept Python callables, batch UDFs, or PyArrow -`RecordBatch` iterators for populating new columns, whether through -`transforms` or `computed`. New column values must be defined with SQL -expressions, or added as NULL columns from an Arrow field or schema. If your -transformation cannot be expressed in SQL, compute the values outside -`add_columns` before writing them back through another workflow. +On local tables, Python `add_columns` also accepts pandas or Polars +DataFrames, PyArrow Tables, RecordBatches, RecordBatchReaders, and iterables +of batches. Pass only the new columns, with exactly one row per current live +table row in storage scan order. DataFrame indexes are ignored, and reader +batch boundaries need not match table fragments. Keep the table unchanged +between computing the values and adding them. Readers are consumed once. + +Data inputs cannot be combined with `computed` columns and are not supported +on remote tables. Python callables and batch UDFs are not accepted; compute +those values first, then pass the result as a DataFrame or reader. -## The expression {#expressions} - -The expression is SQL, evaluated over the row. It can reference any column in -the table, including another computed column: - -```python -table.add_columns(computed={ - "power_score": "cast(x as double) / 2.0", - "is_strong": "power_score > 0.5", -}) -``` - -Declaration order is dependency order: a computed column may reference one -declared earlier in the same mapping, but not one declared after it. - -The functions available are the ones the -[SQL dialect](/sql/functions) documents. - -A literal in the expression has to fit the column it meets: `x / 2.0` is -refused when `x` is an integer column, so write `cast(x as double) / 2.0`. - - -In LanceDB Enterprise, keep the expression to top-level columns. A column -refresh can fail on an expression that reads a field inside a struct, such as -`stats.magic + stats.strength`, which the embedded library computes. Try a new -expression on a small table first. - - -## Change columns used by an expression {#input-constraints} +## Change columns used by a computed column {#input-constraints} While a computed column's declaration references another column, that column @@ -173,60 +213,13 @@ if you need to change one of its inputs. This is worth knowing before deriving a column from something you expect to reshape later. Dropping the computed column releases the constraint. -## Filling with Python instead of SQL {#functions} - -Enterprise - -When the value cannot be expressed in SQL (an embedding, a model call, an -image decode), [Geneva](/geneva), the feature engineering package for LanceDB -Enterprise, fills the column with a Python function instead. - -{/* -Draft for the Functions release. Replaces the paragraph above: - -When the value cannot be expressed in SQL -- an embedding, a model call, an -image decode -- the column is filled by a registered -[function](/management/function) instead of an expression. Declaring it looks -the same; what differs is what fills it. It needs a deployment with Functions -enabled. - -The call passed to `add_columns` is the tell: a SQL expression in `computed` -is a string, keyed by the column name -- - - -```python Python icon="python" -table.add_columns(computed={"caption_length": "length(caption)"}) -``` - - --- while a Function application is the registered version itself, called with -its parameters bound to source columns through `col(...)`, keyed the same way -but passed positionally rather than through `computed`: - - -```python Python icon="python" -table.add_columns({"caption": caption_version(jpeg=col("jpeg"))}) -``` - - -Both accept the same `auto_refresh_enabled` and `auto_refresh_interval_seconds` -options, and both refresh and toggle the same way; see -[Refresh a computed column](/feature-engineering/refresh-column#automatic). -*/} - ## Related guides {#next} Fill the rows that lack values. - - Fill a column with Python on LanceDB Enterprise. - - {/* - Draft for the Functions release. Replaces the Geneva card above: Fill a column with Python. - */} diff --git a/docs/web/feature-engineering/index.mdx b/docs/web/feature-engineering/index.mdx index 6807998ec..405f4e852 100644 --- a/docs/web/feature-engineering/index.mdx +++ b/docs/web/feature-engineering/index.mdx @@ -10,18 +10,10 @@ Use feature engineering to turn raw data into features for search, analysis and model training. LanceDB stores derived columns and materialized views alongside the source data, so you can reuse the results across those workflows. -[Materialized views](/feature-engineering/materialized-views) are ordinary -[catalog objects](/basics/catalog). Create them through the SDK or SQL, -then refresh the derived data when its inputs change. - -{/* -Draft for the Functions release. Replaces the paragraph above: - [Functions](/management/function) and [materialized views](/feature-engineering/materialized-views) are ordinary [catalog objects](/basics/catalog). Create them through the SDK or SQL, then refresh the derived data when its inputs change. -*/} In LanceDB Enterprise, every operation here also has a SQL form. See [DDL](/sql/ddl/table#alter) to declare a column and [REFRESH COLUMN](/sql/dml/refresh-column) to fill it. @@ -76,15 +68,10 @@ Enterprise runs materialization on remote compute, as a server-side job. | | What it produces | Filled by | Available | | --- | --- | --- | --- | | [View](/feature-engineering/view) | a saved query, no stored rows of its own | nothing -- it runs on every read | Enterprise | -| [Computed column](/feature-engineering/add-computed-column) | a new column on an existing table | a SQL expression | Embedded and Enterprise | +| [Computed column](/feature-engineering/add-computed-column) | a new column on an existing table | a SQL expression | Enterprise | | [Materialized view](/feature-engineering/materialized-views) | a new table derived by a query | a refresh | Enterprise | -| [Geneva](/geneva) | columns filled by Python | the `geneva` package | Enterprise | - -{/* -Draft for the Functions release. Replace the Geneva row of the table above with: | [Function](/management/function) | a computed column filled by Python | registered code | Enterprise | | [Geneva](/geneva) | columns filled by Python, for existing pipelines | the `geneva` package | Enterprise | -*/} **A view** has no refresh and no staleness window, because it stores the query rather than its result. Reach for one first, before a computed column @@ -98,21 +85,13 @@ expression, filled by [a refresh](/feature-engineering/refresh-column). aggregated view of a source) and bring it up to date on each refresh. The result is an ordinary table: queryable, indexable, searchable. -**Geneva** is LanceDB Enterprise's Python package for work SQL cannot express: -embedding a column, calling a model, decoding an image. It defines features as -Python functions and backfills them as distributed jobs. - -{/* -Draft for the Functions release. Replaces the Geneva paragraph above: - **Functions** run Python where the data is, for work SQL cannot express: embedding a column, calling a model, decoding an image. Registered once, versioned, then applied as a column. They are the way to do that on a deployment; [Geneva](/geneva) remains available for existing pipelines. -*/} -A materialized view can select computed columns. -{/* Draft for the Functions release: A computed column can be filled by a registered function. */} +A materialized view can select computed columns. A computed column can be +filled by a registered function. ## Where the work runs {#where} @@ -124,28 +103,27 @@ cluster, and the API reflects that: `refresh_column` raises, and columns are off by default in LanceDB Enterprise, and its administrator has to enable them before a column can be declared there. -```python + +```python Python icon="python" job = table.refresh_column_async("power_score") result = job.wait() result.rows_assigned ``` + A backfill over a large table can therefore be started, left, and checked on from a different process: the connection does not have to stay open. -Enterprise manages the compute for the refresh. You still control when to -submit it; declaring a computed column does not schedule recurring refreshes. -{/* Draft for the Functions release: That is also why a function must declare the environment it needs. */} +Enterprise manages the compute for the refresh. Declaring a computed column +doesn't refresh it on a schedule unless your deployment enables automatic +refresh; see [Auto Refresh](/enterprise/auto-refresh). +That is also why a function must declare the environment it needs. ## Recovering from a failure {#failures} -{/* -Draft for the Functions release. - A function that raises fails the job. There is no per-row retry or skip policy in the function definition, so a function calling a flaky external service should handle that itself, inside the function body. -*/} When a refresh fails, fix the cause and run the refresh again. The new refresh fills what is still empty or stale. How much of the @@ -172,10 +150,7 @@ only the rows that did not complete. Bring a derived table up to date with its source. - {/* - Draft for the Functions release: Register Python to fill a column with. - */}
diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index 86a3667f3..0f9494c9f 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -19,70 +19,159 @@ In SQL this is [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view#create). ## Create a view {#create} +A materialized view is defined by a SQL query, so it is created with one. +From Python, run the statement on an [Enterprise connection](/basics/catalog#enterprise) +with [`execute_query`](/basics/sql#sql-from-python); the SQL is the same +either way: + ```python Python icon="python" -view = db.create_materialized_view( - "frames_captioned", - source="frames", - select=["frame_id", "video_id", "ts", "caption"], - where="selected = true", -) +db.execute_query(""" + CREATE MATERIALIZED VIEW frames_captioned AS + SELECT frame_id, video_id, ts, caption + FROM frames + WHERE selected = true +""").read_all() +view = db.open_materialized_view("frames_captioned") ``` -```typescript TypeScript icon="square-js" -const view = await db.createMaterializedView("frames_captioned", "frames", { - select: ["frame_id", "video_id", "ts", "caption"], - where: "selected = true", -}); +```sql SQL icon="database" +CREATE MATERIALIZED VIEW frames_captioned AS +SELECT frame_id, video_id, ts, caption +FROM frames +WHERE selected = true ``` -`source` names the table the view reads. `select` takes column names, -`(alias, expression)` pairs, or a dict of the same; omitting it selects every -source column, expanded against the schema as it was at creation time. -`where` filters source rows, and `limit` caps the view. +`execute_query` returns once the result stream is readable, not once the +statement has finished, so `.read_all()` waits out the full creation before +the next line opens it. -Creating the view computes its rows, so it is ready to read. Pass -`with_no_data=True` to create it empty instead; a later -[refresh](/feature-engineering/refresh-materialized-view) populates it. +The query defines the view: here, the `frames` table's `frame_id`, +`video_id`, `ts` and `caption` columns, filtered to the frames selected for +captioning. There is no separate, more limited form for defining one -- +joins and [Functions](#functions) in the select list work the same way any +other `SELECT` does, within the query shapes your deployment's LanceDB +Enterprise version and configuration accept; see the +[SQL reference](/sql/ddl/materialized-view#create). + +Creating the view computes its rows, so it is ready to read immediately. +[`db.open_materialized_view`](/management/materialized-view#manage) gets a +handle back for reading, refreshing or inspecting it from Python; the view +itself is also an ordinary table, queryable by name like any other. Your administrator manages stable row IDs and other source-table requirements for materialized views on the server; confirm support for your source table's shape before creating a view over it. +## Selecting a Function's output {#functions} + +Enterprise + +A `SELECT` expression is SQL text, so it can call a registered +[Function](/curation/create-function) the same way a computed column's +expression can. Continuing the +[`caption` Function](/curation/create-function#chain) registered in Create a +Function, against a `frames` table that already has a `jpeg` column: + + +```python Python icon="python" +db.execute_query(""" + CREATE MATERIALIZED VIEW frames_captioned AS + SELECT frame_id, jpeg, caption(jpeg) AS caption + FROM frames + WHERE selected = true +""").read_all() +``` + +```sql SQL icon="database" +CREATE MATERIALIZED VIEW frames_captioned AS +SELECT frame_id, jpeg, caption(jpeg) AS caption +FROM frames +WHERE selected = true +``` + + +A query that joins tables works the same way, with no separate syntax for +it. Continuing the join and chained Functions from +[Create a Function](/curation/create-function#chain), producing `jpeg` from +a separate `videos` table and captioning it in the same statement: + + +```python Python icon="python" +db.execute_query(""" + CREATE MATERIALIZED VIEW frames_captioned + WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 5) + AS + SELECT + f.frame_id, + extract_frame(v.video, f.ts) AS jpeg, + caption(extract_frame(v.video, f.ts)) AS caption + FROM videos v + JOIN frames f ON v.id = f.video_id + WHERE f.selected = true +""").read_all() +``` + +```sql SQL icon="database" +CREATE MATERIALIZED VIEW frames_captioned +WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 5) +AS +SELECT + f.frame_id, + extract_frame(v.video, f.ts) AS jpeg, + caption(extract_frame(v.video, f.ts)) AS caption +FROM videos v +JOIN frames f ON v.id = f.video_id +WHERE f.selected = true +``` + + +See [Joins](/curation/join) for the join itself, and +[Auto Refresh](/enterprise/auto-refresh) for what `WITH` sets here. + ## Automatic refresh at creation {#auto-refresh} -Pass `auto_refresh_enabled` and `auto_refresh_interval_seconds` to schedule -refreshes instead of calling +Set `auto_refresh_enabled` and `auto_refresh_interval_seconds` in the `WITH` +clause to schedule refreshes instead of calling [`refresh`](/feature-engineering/refresh-materialized-view) yourself: -```python -view = db.create_materialized_view( - "frames_captioned", - source="frames", - select=["frame_id", "video_id", "ts", "caption"], - where="selected = true", - auto_refresh_enabled=True, - auto_refresh_interval_seconds=300, -) + +```python Python icon="python" +db.execute_query(""" + CREATE MATERIALIZED VIEW frames_captioned + WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300) + AS + SELECT frame_id, video_id, ts, caption + FROM frames + WHERE selected = true +""").read_all() ``` +```sql SQL icon="database" +CREATE MATERIALIZED VIEW frames_captioned +WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300) +AS +SELECT frame_id, video_id, ts, caption +FROM frames +WHERE selected = true +``` + + Omit `auto_refresh_enabled` to let the server decide whether to enable it, and omit `auto_refresh_interval_seconds` to let the server decide the -pacing. See -[Automatic refresh](/feature-engineering/refresh-materialized-view#auto-refresh) -for how scheduling behaves once the view exists. +pacing. See [Auto Refresh](/enterprise/auto-refresh) for how scheduling +behaves once the view exists. ## Working with the view {#working-with-the-view} `view.table` is the underlying table, for querying, indexing, or search. -`view.definition` is the recorded query: the select list, predicate, and -limit. Use it to inspect the query without inferring it from the rows. Both -are properties; on an async view, the definition is read with -`await view.definition()`. +`view.definition` has a single field, `query` -- the recorded query, in the +canonical spelling the server stores. Use it to inspect the query without +inferring it from the rows. Both are properties; on an async view, the +definition is read with `await view.definition()`. -An existing view is reopened with `db.open_materialized_view(name)`. Creation, -refresh and drop also have async, job-returning SDK methods; see +Creation, refresh and drop also have async, job-returning SDK methods; see [Materialized view](/management/materialized-view#manage). ## Related guides {#next} diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index ba3934f1e..ac4ff93fe 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -5,7 +5,7 @@ description: "Populate a computed column and update it when its inputs change." icon: arrows-rotate keywords: ["refresh_column", "backfill", "job", "idempotent", "REFRESH COLUMN"] availability: - embedded: available + embedded: unavailable enterprise: available --- @@ -14,41 +14,47 @@ new rows and recompute values whose inputs changed. The example below continues with the `doubled` column from the computed-column guide. -In the 0.41 SDK release, declaration and refresh in LanceDB Embedded require a source build -with the `experimental-functions` Cargo feature. Published Python and TypeScript -packages leave it disabled. LanceDB Enterprise operations do not require -this feature; existing computed-column data remains readable in default builds. +Computed columns require LanceDB Enterprise. ```python Python icon="python" -table.refresh_column("doubled") -# RefreshColumnResult(rows_filled=2, version=4) +job = table.refresh_column_async("doubled") +job.wait() -table.to_arrow().sort_by("x").to_pandas() +table.search().to_arrow().sort_by("x").to_pandas() # x doubled # 0 1 2 # 1 2 4 ``` -```sql SQL +```sql SQL icon="database" REFRESH COLUMN doubled ON my_table ``` + +`table.refresh_column(...)` (sync) is also a local, blocking form, but it +raises on an Enterprise connection -- use `refresh_column_async`, shown +above, or the SQL form instead. See +[Run a refresh on Enterprise](#async) below for what the returned job +supports. + + The refresh commits ordinary table versions (the values, then a metadata-only record of the inputs they were computed from), so [versioning](/management/table#versioning) applies to it like any other write. -The SQL form is [`REFRESH COLUMN`](/sql/refresh#refresh-column), with the same resource options. +The SQL form is [`REFRESH COLUMN`](/sql/dml/refresh-column), with the same resource options. ## What a refresh recomputes {#idempotent} -A refresh fills rows that have no value and recomputes rows whose inputs -changed since they were computed. Every other row is left alone, so a second -refresh with nothing changed does nothing. This supports two common workflows. +Without a `WHERE` predicate, a refresh fills unassigned rows and recomputes +values whose inputs changed since they were computed. Every other row is left +alone, so a second refresh with nothing changed does nothing. This supports +two common workflows. **Appending is cheap.** Rows added since the last refresh are filled by the next one; filled rows whose inputs are unchanged are skipped. Backfilling a @@ -64,82 +70,57 @@ column is stale between an update and the next refresh. ## Automatic refresh {#automatic} -Set scheduling options when declaring a computed column: - -```python -table.add_columns( - computed={"doubled": "x * 2"}, - auto_refresh_enabled=True, - auto_refresh_interval_seconds=300, -) -``` - -These options apply to every computed output declared in that call. Automatic -refresh is enabled by default. When the interval is omitted, the server -determines when to refresh. Local tables store the setting, but automatic -execution requires a Cloud or Enterprise server with its separate -`column_refresh.enabled` switch turned on. That server switch is disabled in -the base configuration. - -The interval is a positive minimum delay after the last successful refresh -of that output. A first refresh is immediately eligible. The scheduler still -checks input freshness and waits for computed ancestors to settle; the timer -does not make unchanged inputs require recomputation. Each declared output's -interval is independent, so refreshing a sibling does not postpone it. - -Pacing uses retained live Job Registry history. If completed jobs are archived -before a configured interval expires, the scheduler can lose the last-success -timestamp and refresh earlier. Leave archival disabled, or retain live history -for at least the longest configured column interval. Archival is disabled in -the base configuration; its default retention threshold is seven days. - -Change a stored setting through SQL: - -```sql -ALTER TABLE my_table ALTER COLUMN doubled SET auto_refresh_enabled = false; -ALTER TABLE my_table ALTER COLUMN doubled SET auto_refresh_interval_seconds = 600; -ALTER TABLE my_table ALTER COLUMN doubled SET auto_refresh_enabled = true; -``` - - -The current setting is in the column's own field metadata, -`computed_column.auto_refresh_enabled`, readable from `table.schema` without -submitting a job to ask. - - -Setting the flag is a metadata-only change and always succeeds, independent of -whether the scheduler can actually refresh the column -- a deployment issue -that keeps the background job from running (for example, a worker that cannot -reach object storage) does not stop the `ALTER` from committing. Check the -column's job history, not just its metadata, if values stop appearing after -re-enabling. - -**Disabling does not skip or drop writes.** Rows written while disabled -commit with no computed value, the same as a row written before the column -existed; they do not queue anywhere separate. Inflight jobs may finish, and -manual refresh remains available throughout. - -**Re-enabling catches up the entire backlog in one pass**, not just rows -written after that point: the next scheduler tick processes every row left -unfilled since the column was disabled, in a single refresh, with no -further write required to trigger it. This is "catch up," not "resume -cadence" -- a column disabled for an hour and re-enabled fills everything -that accumulated during that hour, immediately, rather than only picking up -new rows from the moment it is re-enabled. +A computed column can refresh itself on a schedule instead of waiting for +an explicit call here. See [Auto Refresh](/enterprise/auto-refresh) for +enabling it, the SQL and SDK forms for changing the setting, and how +catch-up works when it's re-enabled after being off. ## Refreshing part of a table {#partial} -Enterprise In SQL a refresh can be scoped to a -predicate, which is useful for filling a slice first and checking it before -committing to the whole table: +Enterprise A refresh can be scoped to a predicate, +with `where=` in Python or `WHERE` in SQL, which is useful for filling a slice +first and checking it before committing to the whole table: -```sql -REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' + +```python Python icon="python" +job = table.refresh_column_async( + "embedding", + where="created_at > date '2026-01-01'", +) +job.wait() ``` +```sql SQL icon="database" +REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' +``` + + +A filtered refresh recomputes **every matching live row**, including rows +whose outputs are already current. Repeating the same predicate repeats those +Function calls and their cost. To select only null outputs within a slice: + + +```python Python icon="python" +job = table.refresh_column_async( + "embedding", + where="created_at > date '2026-01-01' AND embedding IS NULL", +) +job.wait() +``` + +```sql SQL icon="database" +REFRESH COLUMN embedding ON documents + WHERE created_at > date '2026-01-01' AND embedding IS NULL +``` + + +This skips non-null outputs even when their inputs changed, and can recompute +outputs that were successfully computed as `NULL`. Use an unfiltered refresh +to let LanceDB track which outputs need updating. + -**Enterprise job type:** `computed_refresh` for a SQL-expression column. -{/* Draft for the Functions release: `function_refresh` for one filled by a registered [function](/management/function). */} +**Enterprise job type:** `computed_refresh` for a SQL-expression column, +`function_refresh` for one filled by a registered [function](/management/function). ## Run a refresh on Enterprise {#async} @@ -151,7 +132,8 @@ cluster. `refresh_column` raises there; use `refresh_column_async`, which returns a [job](/basics/jobs) you can wait on or poll instead of holding a connection open: -```python + +```python Python icon="python" job = table.refresh_column_async("doubled") result = job.wait() result.rows_assigned @@ -159,6 +141,7 @@ result.rows_assigned job.status() # 'finished' ``` + Poll with `status()`, resolve with `wait()`. `status()` is a point snapshot and does not raise, which is what makes it safe in a loop; `wait()` raises @@ -172,22 +155,170 @@ process. SQL exposes the worker budget directly, which is the lever when a backfill is too slow or too expensive: -```sql + +```sql SQL icon="database" REFRESH COLUMN embedding ON documents WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2) ``` + -`num_workers` sets the count instead of a per-worker budget; the two are -alternatives rather than a pair. `batch_size` controls how many rows a worker -takes at a time, and `error_policy = 'skip'` continues past rows that fail -rather than failing the job. +The resource values cap the Function workers together: this example allows +up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the fleet. They are not +per-worker allocations or a guaranteed worker count. `num_workers` is only +accepted for SQL-expression columns; registered Function columns reject it. +When setting CPU or memory, supply all three budget fields, using +`gpu_count = 0` for a CPU-only Function. + +`batch_size` caps rows in one Function call; LanceDB adapts actual call and +work sizes. For Function columns, the refresh defaults to +`error_policy = 'fail'`. Set `error_policy = 'skip'` to write null outputs for +failing rows and record them in the error store, subject to failure limits. +See the [SQL refresh options](/sql/dml/refresh-column#options). + +{/* +Draft for the Function retry policy release. + +For registered Function columns, pass `retry_policy` to +`refresh_column_async` to replace the Function's registered retry policy +for this refresh. For example, +`retry_policy=FunctionRetryPolicy(transient=True, max_attempts=3)` allows +three attempts, including the first call. Import `FunctionRetryPolicy` +from `lancedb.functions`. Use `FunctionRetryPolicy(max_attempts=1)` to +disable user-error retries. Omitting the override preserves the registered +policy. + +This requires a supporting LanceDB Enterprise server as well as an SDK +that exposes these options. An older Function image may need +re-registration before it accepts a refresh override. Only enable retries +when repeating a failed call's partial work is safe, including any external +requests made before the error. + +The attempt budget belongs to one failed Function call. With an explicit +retry policy and `error_policy="skip"`, exhaustion in a batch Function +writes nulls for the whole failed call and records its errors, subject to +failure limits. It does not split the batch to restart the retry budget. +Row Functions isolate failures per row. Infrastructure recovery, framework +deadlines and cancellation remain separate from this user-error policy. +See [Function failure handling](/management/function#failures) for the +retry and replay boundaries. +*/} + +For a column filled by a registered Function, the Python and Rust job APIs can +override the Function's GPU placement for this refresh: + + +```python +classes = db.list_gpu_classes() +gpu_class = next(gpu.name for gpu in classes if gpu.gpu_model == "NVIDIA H100") + +job = table.refresh_column_async( + "embedding", + gpu_class=gpu_class, + gpu_count=4, + batch_size=32, +) +``` + +```rust +use lancedb::{Connection, Table, table::RefreshColumnOptions}; + +async fn refresh( + conn: &Connection, + table: &Table, +) -> Result<(), Box> { + let gpu_class = conn + .list_gpu_classes() + .await? + .into_iter() + .find(|class| class.gpu_model.as_deref() == Some("NVIDIA H100")) + .map(|class| class.name) + .ok_or("H100 GPU class is not configured")?; + let _job = table + .refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default() + .gpu_class(gpu_class) + .gpu_count(4) + .batch_size(32), + ) + .await?; + Ok(()) +} +``` + + +`gpu_count` is the aggregate GPU budget for the refresh's Function workers, +not a request for that many GPUs per worker. It must be positive. +`gpu_class` must name a class returned by `list_gpu_classes()`; class names +are lowercase DNS labels. Omit either option to use the Function's registered +class or the server's configured budget. `list_gpu_classes()` requires System +Usage permission, and raises `NotImplementedError` when the server predates +GPU class discovery. + + +The Rust GPU discovery and refresh controls are not in the latest Rust +release. TypeScript does not expose GPU class discovery; pass `gpuClass` +and `gpuCount` in the `refreshColumnAsync` options. + + +The job APIs also take the row filter and failure handling of the SQL +`REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed +to new rows (see [what a filter recomputes](#partial)) and told to skip rows +whose Function call fails: + + +```python +job = table.refresh_column_async( + "embedding", + where="created_at > date '2026-01-01'", + error_policy="skip", + max_failed_fraction=0.01, + row_timeout_seconds=30, +) +``` + +```typescript +const job = await table.refreshColumnAsync("embedding", { + where: "created_at > date '2026-01-01'", + errorPolicy: "skip", + maxFailedFraction: 0.01, + rowTimeoutSeconds: 30, +}); +``` + +```rust +use lancedb::{function::FunctionErrorPolicy, table::RefreshColumnOptions}; + +let _job = table + .refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default() + .where_clause("created_at > date '2026-01-01'") + .error_policy(FunctionErrorPolicy::Skip) + .max_failed_fraction(0.01) + .row_timeout_seconds(30.0), + ) + .await?; +``` + + +`max_failed_rows`, `init_timeout_seconds`, `num_workers` and +`max_executor_processes_per_worker` are accepted the same way; the +[SQL refresh options](/sql/dml/refresh-column#options) describe each one. +The SDK rejects a blank `where`, a `max_failed_fraction` outside 0 to 1, a +timeout that is not a positive number and a zero worker or process count +before sending the request; the server validates everything else. A LanceDB +Embedded refresh rejects every option other than `batch_size`, `gpu_class` +and `gpu_count`. ## When a refresh fails {#failures} -What a failure keeps depends on where the refresh ran. `refresh_column` in your -process writes the column in one commit, so a failure leaves the column as it -was. A refresh job in LanceDB Enterprise commits finished batches as it goes, so some -values can remain after a failure. +What a failure keeps depends on where the refresh ran. The local, blocking +`refresh_column` writes the column in one commit, so a failure leaves the +column as it was. A refresh job in LanceDB Enterprise -- always +`refresh_column_async` or `REFRESH COLUMN` there, never the blocking form -- +commits finished batches as it goes, so some values can remain after a +failure. Either way, recover by fixing the cause and refreshing again. The new refresh fills rows that are still empty or whose inputs changed, and normally skips @@ -196,22 +327,21 @@ that were already written (for example when the record of the inputs they were computed from was not saved), so do not count on a retry costing only the rows that did not complete. -{/* -Draft for the Functions release. - For a column filled by a [function](/management/function), the usual cause is the worker environment rather than the data. See [environment mismatches](/management/function#mismatch-symptoms) for the symptoms, which rarely name their cause. -*/} ## Related guides {#next} - + Waiting on, inspecting, and cancelling server-side work. The same idea, for a whole derived table. + + Refresh on a schedule instead of calling this yourself. + diff --git a/docs/web/feature-engineering/refresh-materialized-view.mdx b/docs/web/feature-engineering/refresh-materialized-view.mdx index 05ebff109..74fcce2fb 100644 --- a/docs/web/feature-engineering/refresh-materialized-view.mdx +++ b/docs/web/feature-engineering/refresh-materialized-view.mdx @@ -18,57 +18,113 @@ In SQL this is [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh-materialized-view) ## Refresh a view {#refresh} -```python + +```python Python icon="python" view.refresh() ``` + -Every refresh rebuilds the view completely from its source query -- there is -no incremental refresh. Calling it again with no source changes still -rebuilds and commits a new table version. +In LanceDB Embedded, every refresh rebuilds the view completely from its +source query -- there is no incremental refresh there. Calling it again +with no source changes still rebuilds and commits a new table version. In +LanceDB Enterprise, the server chooses the refresh mode instead; pass +`full=True` to force a full rebuild there too. -The result reports what the refresh did: +In LanceDB Embedded, the result reports what the refresh did: -```python + +```python Python icon="python" result = view.refresh() result.rows_written # rows in the rebuilt view result.source_version # the source table version the view now reflects result.version # the view's own new table version ``` + + +LanceDB Enterprise refreshes run through its SQL job adapter, which doesn't +expose these metrics: `mode`, `rows_written` and `source_version` are all +`None` on an Enterprise result, even though the refresh itself ran. Pass `source_version=N` to refresh against a particular source version -instead of the latest: +instead of the latest. This is a LanceDB Embedded capability only -- +LanceDB Enterprise's SQL refresh does not support pinning a source version: -```python -view.refresh(source_version=12) + +```python Python icon="python" +view.refresh(source_version=12) # LanceDB Embedded only +``` + + +Use `view.table.count_rows()` for the view's row count at any time; on +LanceDB Embedded it always matches `rows_written` from the most recent +refresh. + +{/* +Draft: publish this section after the Python/Rust resource-budget SDK support +is released. TypeScript parity is tracked separately in issue #4903. + +## Resource budgets {#resources} + +For training-data curation, bound the resources used to recompute a view: + + +```python Python icon="python" +job = view.refresh_async( + cpu_millis=8000, + memory_bytes=16 * 1024**3, + gpu_count=2, + gpu_class="h100", +) +job.wait() ``` -Use `view.table.count_rows()` for the view's row count at any time; it -always matches `rows_written` from the most recent refresh. +```rust Rust icon="rust" +use lancedb::materialized_view::MaterializedView; + +async fn refresh(view: &MaterializedView) -> lancedb::Result<()> { + let job = view + .refresh() + .cpu_millis(8000) + .memory_bytes(16_u64 << 30) + .gpu_count(2) + .gpu_class("h100") + .execute_async() + .await?; + job.wait().await?; + Ok(()) +} +``` + + +The same options are available on `refresh`, asynchronous Python connections, +and the Rust refresh builder (`cpu_millis`, `memory_bytes`, `gpu_count`, and +`gpu_class`). CPU is in millicores (8000 means eight cores), memory is bytes, +and GPU count is an aggregate concurrent cap. CPU or memory requires all three +budget fields. Use zero GPUs for a CPU-only view, or specify a GPU cap alone. + +The cap covers the refresh execution and its Function processes together. +It does not allocate that budget separately to each Function. A GPU class +selects placement for this execution; discover configured classes with +`db.list_gpu_classes()`. A cap does not promise more parallelism: current MV +refreshes use at most one GPU. Omitted settings keep existing defaults. + +These controls require an Enterprise server with an isolated backend that can +enforce them; Embedded and unsupported execution backends reject them. Earlier +Enterprise servers reject the new SQL options. See the +[SQL resource options](/sql/dml/refresh-materialized-view#resources). + +TypeScript does not expose these options yet; SDK parity is tracked in +[issue #4903](https://github.com/lancedb/lancedb/issues/4903). + +*/} ## Automatic refresh {#auto-refresh} -Set scheduling options when [creating the view](/feature-engineering/materialized-views#auto-refresh): - -```python -view = db.create_materialized_view( - "frames_captioned", - source="frames", - select=["frame_id", "video_id", "ts", "caption"], - where="selected = true", - auto_refresh_enabled=True, - auto_refresh_interval_seconds=300, -) -``` - -`auto_refresh_interval_seconds` is a positive minimum delay after the last -successful refresh before the next automatic one is eligible; omit it to let -the server decide. The whole view toggles together -- there is no -per-column granularity the way a computed column has one setting per output. - -The view's *initial* population, at creation or when the server first runs -it, happens regardless of these settings; only refreshes after that are -gated. Manual `view.refresh()` keeps working whether or not automatic -refresh is enabled. +A materialized view can refresh itself on a schedule instead of waiting +for an explicit `refresh()` call. See [Auto Refresh](/enterprise/auto-refresh) +for enabling it at creation, the SQL and SDK forms for changing the +setting afterward, and how it differs from a computed column's +per-output granularity. ## When a refresh fails {#failures} @@ -85,4 +141,7 @@ refresh again. The same idea, for a single derived column. + + Refresh on a schedule instead of calling this yourself. + diff --git a/docs/web/feature-engineering/view.mdx b/docs/web/feature-engineering/view.mdx index e61b2118a..ce9421532 100644 --- a/docs/web/feature-engineering/view.mdx +++ b/docs/web/feature-engineering/view.mdx @@ -20,24 +20,28 @@ underlying query is cheap enough to simply re-run on every read. A view over a products table, selecting and deriving a few columns: -```sql + +```sql SQL icon="database" CREATE VIEW "discounted_products" AS SELECT id, name, price, price * 0.9 AS sale_price FROM "products" WHERE in_stock = true ``` + The statement resolves the view's schema from the query at creation time. -Anything the [SQL dialect](/sql/functions) supports can define one: joins, +Anything the [SQL dialect](/sql/dql/functions) supports can define one: joins, predicates, aggregates, window functions -- the same expressiveness as [a computed column's](/feature-engineering/add-computed-column#expressions) SQL expression, just over a whole derived table instead of one column. ## Read it like a table {#reading} -```sql + +```sql SQL icon="database" SELECT * FROM "discounted_products" WHERE sale_price < 20 ``` + Every read runs the saved query against current data, so `sale_price` reflects whatever `price` is right now -- there is no staleness window to diff --git a/docs/web/governance/audit-log.mdx b/docs/web/governance/audit-log.mdx new file mode 100644 index 000000000..6e86f77b3 --- /dev/null +++ b/docs/web/governance/audit-log.mdx @@ -0,0 +1,157 @@ +--- +title: "Audit Log" +sidebarTitle: "Audit Log" +description: "The durable record of access attempts in the cluster: its schema, how to query it, and how to grant access." +icon: clipboard-list +keywords: ["audit log", "audit", "security", "compliance", "principal", "privilege"] +availability: + embedded: unavailable + enterprise: available +--- + +Every authorization check in LanceDB Enterprise -- the principal, the +privilege that was checked, and the object it was checked against -- can +be recorded as a durable audit log entry. On a failed check, the first +failure is logged; on success, the final successful check is logged. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + R["Request arrives"] --> C["Authorization check"] + C -->|denied| L1["Log the first failed check"] + C -->|granted| L2["Log the final successful check"] + L1 --> T[("__audit_log table
system database")] + L2 --> T + T --> Q["SELECT ... FROM system.public.__audit_log"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class T accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + R["Request arrives"] --> C["Authorization check"] + C -->|denied| L1["Log the first failed check"] + C -->|granted| L2["Log the final successful check"] + L1 --> T[("__audit_log table
system database")] + L2 --> T + T --> Q["SELECT ... FROM system.public.__audit_log"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class T accent +``` + +
+ +A deployment chooses how audit records are kept: discarded, written +alongside ordinary application logs, or stored durably as rows in a Lance +table. Only the durable Lance-backed sink produces something you can +query with SQL -- the other two modes exist, but leave nothing in the +table this page describes. + +## Schema {#schema} + +| Column | Type | Nullable | What it holds | +| --- | --- | --- | --- | +| `AccessId` | string | no | The record's own unique ID, a UUIDv4 in hyphenated text form | +| `AccessTime` | timestamp (microsecond, UTC) | no | When the check happened | +| `PrincipalId` | string | no | The checked principal's ID | +| `PrincipalName` | string | yes | The principal's display name, where known | +| `Object` | string | yes | The object checked against, when the operation maps to a single object | +| `AccessType` | string | no | The privilege that was checked | +| `Description` | string | no | A human-readable description of the check | +| `RequestId` | string | yes | The query node's own request ID, for correlating with request logs | +| `Granted` | boolean | no | Whether the check succeeded | + +`RequestId` ties an authorization decision back to the request that +produced it -- both the REST and Flight SQL transports accept only UUID +request IDs, generating one when a request arrives without a valid one, +so this column is always a canonical UUID string when present. + +## Accessing it {#access} + +The audit log is an ordinary table, not a special API -- it lives in the +`system` database's `public` namespace under the name `__audit_log` by +default (a deployment can configure a different suffix, producing +`__audit_` instead, but the `__audit_` prefix is fixed to keep +every audit table in its own part of the system database's namespace). +Query it the same way you would any other table, with its full three-part +name: + + +```sql SQL icon="database" +SELECT PrincipalName, AccessType, Object, Granted, AccessTime +FROM system.public.__audit_log +WHERE Granted = false +ORDER BY AccessTime DESC +LIMIT 100 +``` + + +## Durability {#durability} + +The Lance-backed sink batches records in the background instead of writing +on the request path: a batch flushes once it reaches a configured size or +once its oldest record has waited a configured linger period, whichever +comes first. Its queue holds a bounded number of pending records; once full, +requests producing new records wait for the writer to drain it rather than +having a record dropped, and a failed write is retried with growing backoff +rather than abandoned -- so a sink that cannot keep up applies back pressure +and, if sustained, eventually blocks request handling instead of silently +losing entries. The audit table is opened at service startup rather than on +first use, so a misconfigured or unreachable sink fails startup instead of +surfacing the first time something needs to be logged. + +This page does not cover retention -- how long written records are kept, or +whether anything prunes them -- which a deployment operator should confirm +for your version and configuration. + +## Granting access {#grant} + +`system` is not a grantable database -- SQL refuses `GRANT ... ON DATABASE +system`. Reaching into it instead requires `USAGE` on the `SYSTEM` +authorization object, plus `SELECT` on the table itself. Only a superuser +can run these grants. See [Privileges](/governance/privileges#sql) for the +full `GRANT`/`REVOKE` syntax: + + +```sql SQL icon="database" +GRANT USAGE ON SYSTEM TO ROLE security_team +GRANT SELECT ON TABLE system.public.__audit_log TO ROLE security_team +``` + + +System `USAGE` is broad: beyond reaching the audit log, it also lets the +grantee list every job and its events, look up identities, and run +untargeted `SHOW GRANTS` / `SHOW ROLE BINDINGS`. Grant it deliberately, +not as an incidental step toward audit-log access. + +The audit log itself still records who was granted access and who reads +it -- granting and querying it are both authorization checks like any +other, so they appear as rows in the table they govern. + +## What to read next {#next} + + + + Certifications, data handling, and the controls a deployment provides. + + + The full privilege model, and how creation privileges resolve upward. + + diff --git a/docs/web/governance/authorization.mdx b/docs/web/governance/authorization.mdx index c7831590b..41d4f67f0 100644 --- a/docs/web/governance/authorization.mdx +++ b/docs/web/governance/authorization.mdx @@ -1,9 +1,9 @@ --- title: "Authorization" sidebarTitle: "Authorization" -description: "Who may do what: privileges granted on catalog objects to principals, groups, roles, and API keys." +description: "Who may do what: an overview of LanceDB Enterprise's access control model." icon: shield-halved -keywords: ["authorization", "authz", "privileges", "rbac", "access control"] +keywords: ["authorization", "authz", "privileges", "rbac", "access control", "grant", "revoke"] availability: embedded: unavailable enterprise: available @@ -13,135 +13,40 @@ availability: Authorization decides what they may do. An access control entry grants **one privilege** on **one object** to **one -subject**. Everything below is a consequence of that shape. +subject**. Everything on the Principals and Privileges pages is a +consequence of that shape. -## Subjects {#subjects} +## Granting a privilege {#granting} -A grant is held by one of four kinds of subject, distinguished by a prefix: - -| Prefix | Subject | -| --- | --- | -| `p:` | a principal, by ID (`P:` by name) | -| `g:` | a group, by ID (`G:` by name) | -| `r:` | a role | -| `a:` | the principal holding an API key, named by the key | - -Granting to a group or role rather than a principal is what keeps the entry -count manageable: a principal's effective privileges are the union of what it -holds directly and what it inherits. - -`P:`, `G:` and `a:` are ways of naming a subject when you make a request. The -entry is stored against the ID they resolve to, so a grant to `a:` belongs to -the principal holding that key and carries that principal's full authority, -not a narrower one. - -## Objects {#objects} - -Objects are addressed by kind and path: +`GRANT` and `REVOKE` cover every object in the catalog -- system, database, +schema/namespace, table, view, materialized view, secret, function, and +storage integration. A Secret, the one a day-to-day user shares most +often, looks like this: + +```sql SQL icon="database" +GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE research +REVOKE USAGE ON SECRET platform.`model-api-key` FROM ROLE research ``` -system -database:db -namespace:db:ns -table:db:ns$table -view:db:ns$view -``` + -{/* -Draft for the Functions release. Replaces the object kinds above: +The caller must already hold `OWNERSHIP` on the object being granted (`GRANT` +additionally requires the object to already exist; `REVOKE` does not, so an +entry left on a dropped object can still be removed). A role need not exist +beforehand, but a `USER` or `GROUP` name must resolve to exactly one identity +in your identity provider, or the statement fails. -``` -system -database:db -namespace:db:ns -table:db:ns$table -view:db:ns$view -function:db:ns$function -secret:db:ns$secret -``` -*/} +See [Privileges](/governance/privileges) for the full statement syntax and +every privilege each operation needs. See [Principals](/governance/principals) +for who a grant can name. -A nested namespace joins its path with `$`, as in `namespace:db:parent$child` -or `table:db:parent$child$table`. +## What to read next {#next} -The hierarchy is not decorative. Reaching a table requires `USAGE` on the -namespace containing it and on the database containing that. A grant on the -table alone is not enough to traverse to it. - -## Privileges {#privileges} - -| Privilege | Granted on | Allows | -| --- | --- | --- | -| `OWNERSHIP` | any object but `system` | ownership, conveying full authority | -| `USAGE` | system | listing jobs and their events, and looking up other identities | -| `USAGE` | database | accessing the namespaces inside | -| `USAGE` | namespace | accessing the tables inside | -| `SELECT` | table, view | reading rows | -| `INSERT` | table | appending rows | -| `UPDATE` | table | modifying existing rows | -| `DELETE` | table | deleting rows | -| `CREATE_DATABASE` | system | creating a database | -| `CREATE_NAMESPACE` | database, namespace | creating immediate child namespaces | -| `CREATE_TABLE` | namespace | creating a table in it | -| `CREATE_MATERIALIZED_VIEW` | namespace | creating a materialized view in it | -| `CREATE_VIEW` | namespace | creating a non-materialized view in it | -| `OPERATE` | system | describing and controlling jobs, managing caches, and reading server configuration | - -{/* -Draft for the Functions release. Add these rows to the table above. -After the `USAGE` row for namespace: -| `USAGE` | function | binding it to a column, and refreshing a column it computes | -| `USAGE` | secret | binding and resolving it | -After the `UPDATE` row for table: -| `UPDATE` | secret | rotating it, without the right to bind or read it | -After the `CREATE_VIEW` row: -| `CREATE_FUNCTION` | namespace | registering a function in it | -| `CREATE_SECRET` | namespace | creating a secret in it | -*/} - -The four data privileges map onto the four -[ingestion operations](/ingestion), so a principal that may append but not -modify is expressed by granting `INSERT` without `UPDATE`. - - -`CREATE_MATERIALIZED_VIEW` and `CREATE_VIEW` are separate privileges because -[the two objects differ](/basics/catalog): one stores rows and is refreshed, -the other stores only a query. Granting the ability to create one does not -grant the other. - - -## Creation privileges resolve upward {#upward} - -A subtlety worth knowing, because it explains grants that appear to work on -objects that do not exist yet. - -When you create an object, the deployment checks the database and each -namespace that will contain it. One that **has no owner** (because it does -not exist yet, or predates per-object authorization) is treated as one you are -creating: the check falls back to `CREATE_DATABASE` on `system` for the -database, or to `CREATE_NAMESPACE` on its parent for a namespace, and you become -its owner. One that has an owner needs `USAGE` as usual. - -So a principal holding `CREATE_DATABASE` can create a table in a database that -has not been created, which is what makes creation possible at all, and why -an empty ACL set is not the same as a deny. The fallback applies only when -creating; other operations on a database or namespace need `USAGE` on it. - -## Listing grants {#listing} - -Entries can be listed filtered by object, by subject, or both: - -``` -object = table:db:ns$documents -subject = G:data-science -``` - -Results paginate through a continuation token. A page holds at most 100 stored -`(object, subject)` tuples, and a tuple carrying several privileges expands -into several entries in the response, so a page can return more than 100 -entries: the count reflects privileges rather than tuples. Keep requesting with -the returned token until a page comes back without one. - -Listing by subject answers "what can this team reach"; listing by object -answers "who can reach this table". Both are worth running before changing a -grant. + + + Users, groups, and roles -- where each comes from, and how a grant names one. + + + Every object's privileges, and the GRANT/REVOKE syntax that covers them. + + diff --git a/docs/web/governance/principals.mdx b/docs/web/governance/principals.mdx new file mode 100644 index 000000000..a56d2b2d8 --- /dev/null +++ b/docs/web/governance/principals.mdx @@ -0,0 +1,77 @@ +--- +title: "Principals" +sidebarTitle: "Principals" +description: "Users, groups, and roles: where each comes from, and how a GRANT or REVOKE statement names one." +icon: user +keywords: ["principal", "role", "group", "user", "subject", "rbac"] +availability: + embedded: unavailable + enterprise: available +--- + +A grant names one of three kinds of subject: + +| Subject | Where it comes from | +| --- | --- | +| User (principal) | Your identity provider -- OIDC, Microsoft Entra, Okta, or Keycloak. LanceDB never creates one. | +| Group | Also your identity provider. LanceDB never creates one. | +| Role | LanceDB itself. There is no statement that creates a role -- naming one in a grant is what brings it into existence. | + +## Naming a subject in SQL {#naming} + +`GRANT` and `REVOKE` accept a role, user, or group name directly, with an +optional keyword to disambiguate: + + +```sql SQL icon="database" +GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE research +GRANT USAGE ON SECRET platform.`model-api-key` TO USER alice +GRANT USAGE ON SECRET platform.`model-api-key` TO GROUP `data-science` +``` + + +A `USER` or `GROUP` name is resolved against your identity provider, but +only after the caller's `OWNERSHIP` on the object is checked. A name that +isn't found, or that matches more than one identity, is an error -- not a +silent no-op. `ROLE` needs no such lookup, since a role is simply whatever +name a grant has used. + +Name several subjects of the same kind in one statement by omitting the +keyword after the first: + + +```sql SQL icon="database" +GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service +``` + + +## Role membership in SQL {#membership} + +SQL manages which users or groups a role applies to -- its membership -- +directly: + + +```sql SQL icon="database" +GRANT ROLE analysts TO USER alice +GRANT ROLE analysts TO GROUP `data-science` +REVOKE ROLE analysts FROM USER alice +SHOW ROLE BINDINGS +``` + + +Changing membership (`GRANT`/`REVOKE ROLE`) needs system `OPERATE`; +`SHOW ROLE BINDINGS` needs only system `USAGE`. A role binding accepts a +`USER` or `GROUP` on the receiving side, never another `ROLE` -- granting +a privilege to a role before anyone is a member of it is still valid; the +role simply has no effect until it has members. + +## What to read next {#next} + + + + The access-control model a grant is built from. + + + Every object's privileges, and the GRANT/REVOKE syntax that covers them. + + diff --git a/docs/web/governance/privileges.mdx b/docs/web/governance/privileges.mdx new file mode 100644 index 000000000..e437b916f --- /dev/null +++ b/docs/web/governance/privileges.mdx @@ -0,0 +1,147 @@ +--- +title: "Privileges" +sidebarTitle: "Privileges" +description: "Every privilege, which object it's granted on, and the GRANT/REVOKE syntax that covers each one." +icon: key +keywords: ["privileges", "grant", "revoke", "rbac", "acl"] +availability: + embedded: unavailable + enterprise: available +--- + +| Privilege | Granted on | Allows | +| --- | --- | --- | +| `OWNERSHIP` | any object | full authority over it, including granting any other privilege | +| `USAGE` | system | listing, describing and reading the events of jobs, and looking up other identities | +| `USAGE` | database | accessing the namespaces inside | +| `USAGE` | namespace | accessing the tables inside | +| `USAGE` | secret | binding it to a Function, and resolving its value at evaluation time | +| `USAGE` | function | binding it to a column, and refreshing a column it computes | +| `USAGE` | storage integration | reading through it or importing with it | +| `SELECT` | table, view | reading rows | +| `INSERT` | table | appending rows | +| `UPDATE` | table | modifying existing rows | +| `UPDATE` | secret | rotating it, without the right to bind or read it | +| `DELETE` | table | deleting rows | +| `CREATE_DATABASE` | system | creating a database | +| `CREATE_NAMESPACE` | database, namespace | creating immediate child namespaces | +| `CREATE_TABLE` | namespace | creating a table in it | +| `CREATE_MATERIALIZED_VIEW` | namespace | creating a materialized view in it | +| `CREATE_VIEW` | namespace | creating a non-materialized view in it | +| `CREATE_SECRET` | namespace | creating a Secret in it | +| `CREATE_FUNCTION` | namespace | registering a Function in it | +| `CREATE_STORAGE_INTEGRATION` | namespace | registering a storage integration in it | +| `OPERATE` | system | controlling jobs (cancel, pause, resume), managing caches, reading server configuration, and managing role membership | + +`OWNERSHIP` is never revoked -- granting it again transfers it to a new +owner instead, and a single `GRANT OWNERSHIP` statement names exactly one +subject. The caller must already hold `OWNERSHIP` on an object to change +any grant on it. + + +`CREATE_MATERIALIZED_VIEW` and `CREATE_VIEW` are separate privileges because +[the two objects differ](/basics/catalog): one stores rows and is refreshed, +the other stores only a query. Granting the ability to create one does not +grant the other. + + +## Creating an object you don't own yet {#creation} + +Creating a database or namespace checks its *parent*, not itself: one with +no owner -- because it doesn't exist yet -- falls back to `CREATE_DATABASE` +on the system, or `CREATE_NAMESPACE` on its parent namespace, and the +creator becomes its owner. This is what makes creation possible at all, so +holding `CREATE_DATABASE` is enough to create a table in a database that +has not been created yet. + +## Granting privileges from SQL {#sql} + +`GRANT` and `REVOKE` reach every object in the table above -- `SYSTEM`, +`DATABASE`, `SCHEMA`, `NAMESPACE [IN ]`, `TABLE`, `VIEW`, +`MATERIALIZED VIEW`, `SECRET`, `STORAGE INTEGRATION`, and `FUNCTION` -- +with the same statement shape. `SCHEMA` and `NAMESPACE` both target a +namespace, but aren't interchangeable spellings: `SCHEMA` takes a +namespace's complete path, while `NAMESPACE` takes one unqualified +component, resolved under an explicit parent (`IN `) or the +session's current namespace when `IN` is omitted: + + +```sql SQL icon="database" +GRANT OPERATE, USAGE ON SYSTEM TO ROLE ops +GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE readers +GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl +GRANT SELECT ON VIEW dashboard TO ROLE analysts +GRANT SELECT, UPDATE ON MATERIALIZED VIEW daily_rollup TO ROLE analysts +GRANT CREATE SECRET, CREATE FUNCTION ON SCHEMA platform TO ROLE platform_admins +GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service +GRANT OWNERSHIP ON SECRET platform.`model-api-key` TO ROLE platform_admins +GRANT USAGE ON FUNCTION platform.embed TO ROLE etl +GRANT USAGE ON STORAGE INTEGRATION platform.hub TO ROLE research +REVOKE UPDATE ON SECRET platform.`model-api-key` FROM ROLE etl +``` + + +A materialized view is a table for authorization purposes: the same +`OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE` and `DELETE` privileges apply, and +granting one does not reach the non-materialized `VIEW` beside it. + +| Target in the statement | Privileges it accepts | +| --- | --- | +| `SYSTEM` | `OPERATE`, `CREATE DATABASE`, `USAGE` -- no `OWNERSHIP`; the system itself has no owner | +| `DATABASE` | `OWNERSHIP`, `USAGE`, `CREATE SCHEMA` (or `CREATE NAMESPACE`) | +| `SCHEMA` / `NAMESPACE` | `OWNERSHIP`, `USAGE`, `CREATE NAMESPACE`, `CREATE TABLE`, `CREATE MATERIALIZED VIEW`, `CREATE VIEW`, `CREATE SECRET`, `CREATE STORAGE INTEGRATION`, `CREATE FUNCTION` | +| `TABLE`, `MATERIALIZED VIEW` | `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE`, `DELETE` | +| `VIEW` | `OWNERSHIP`, `SELECT` | +| `SECRET` | `OWNERSHIP`, `USAGE` (bind it to a Function), `UPDATE` (rotate it) | +| `FUNCTION` | `OWNERSHIP`, `USAGE` (bind it to a column) | +| `STORAGE INTEGRATION` | `OWNERSHIP`, `USAGE` | + +See [GRANT and REVOKE](/sql/ddl/grant) for the full statement syntax, +including every grantee form (`ROLE`, `USER`, `GROUP`, the `ID ''` +form) and every status a statement can return, shared by every target +above. + +The REST ACL API covers the same objects and reaches further back: it works +against deployments whose SQL surface does not yet expose a given target, +and is the only option for a client that does not speak SQL. + +### What each Secret operation requires {#secret-operations} + +| Operation | Requires | +| --- | --- | +| Create a Secret | `CREATE_SECRET` on the namespace. The creator owns the new Secret. | +| Rotate (`alter`) | `UPDATE` on the Secret | +| Describe | `USAGE` on the Secret | +| List | `USAGE` on the database and the namespace | +| Drop | `OWNERSHIP` on the Secret. Dropping also deletes its grants. | +| Bind it to a Function | `USAGE` on the Secret | + +`UPDATE` is deliberately separate from `USAGE`, so a rotation service can +replace a value without being able to bind the Secret to a Function of its +own. + +### Example: sharing one key {#example} + +- A **platform operator** owns the `platform` namespace. They create + `platform$model-api-key`, then grant the `research` group `USAGE` on that + one Secret. +- A **researcher** in `research` registers a Function bound to + `platform$model-api-key`. Binding any other Secret in `platform` is + refused. +- A **table owner** in `research` adds a column computed by that Function. + They hold `USAGE` on the Secret through the group, but are refused until + they also hold `USAGE` on the Function. +- **Analysts** read the resulting column with table access alone -- no + Function runs on the read path, so they need no grant on the Function or + its Secret. + +## What to read next {#next} + + + + The access-control model a grant is built from. + + + Users, groups, and roles -- where each comes from, and how a grant names one. + + diff --git a/docs/web/index.mdx b/docs/web/index.mdx index 21c9134af..7b6bc6eed 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -23,7 +23,7 @@ time stitching infrastructure together and more time improving datasets, testing ## Accelerate the data flywheel for model research {#accelerate-the-data-flywheel-for-model-research} -Keep your AI data in one table, and give each agent-driven experiment its own isolated branch. +Keep your AI data in one table.{/* Draft until branching reaches early access: restore ", and give each agent-driven experiment its own isolated branch" before the period. */} Find the failure, fix the data, and retrain. @@ -31,11 +31,15 @@ Find the failure, fix the data, and retrain. Start from one failed grasp or evaluation example. [Search](/search/) multimodal data, metadata, and embeddings together, retrieve similar examples, and [curate](/curation) them into a targeted training subset. + {/* + Draft until branching reaches early access. + Don't let an agent silently corrupt your data and ruin a training run. Give each agent its own [branch](/tables/branching), a writable fork of the table, to experiment on, and review the changes before they reach `main`. See [Run experiments on branches](/agent-branch-experiments). + */} Keep episodes, frames, metadata, features, and embeddings together in one schema-enforced table, without pipelines to keep them in sync. Table [versions](/management/table#versioning) let you trace each training @@ -59,99 +63,27 @@ GPU-ready batches from a tagged dataset version. Training pipelines need curatio splits, fast random access, and a clean path into frameworks such as PyTorch -- LanceDB keeps all of it connected through the same table model, whether a workflow uses one table or several related ones. -## Architecture {#architecture} +## Architecture: Embedded and Enterprise {#architecture} -LanceDB Embedded and Enterprise are both built on [Lance](/basics/lance), which stores table data, versions, and -indexes in open, columnar files. The format and table model are the same across both offerings -- what changes is -how storage and compute are organized around them. +LanceDB ships as two offerings on the same [Lance](/basics/lance) format and table model, which stores table data, +versions, and indexes in open, columnar files. What changes between them is how storage and compute are organized +around that format: start locally with Embedded, then move to Enterprise when your team needs distributed scale, +managed infrastructure, private deployment, or higher-throughput curation, feature engineering, search and +retrieval, and training workflows. -![LanceDB suite: LanceDB Embedded for search, and LanceDB Enterprise for search, data exploration and curation, feature engineering, and training, both on the Lance format](/static/assets/images/overview/lancedb-suite.svg) + + + An open-source, embedded retrieval library that runs inside your application process, with no separate + database server to deploy. + + + A distributed multimodal lakehouse service for production workloads that need managed infrastructure and + higher-throughput workflows. + + -Embedded reads and writes tables on local disk or in object storage from inside your application process. -Enterprise keeps durable table data and index artifacts in object storage, independently of the machines serving -requests, and separates query serving, read execution and caching, and indexing and background work into their -own independently sized components. Caches accelerate reads; they are never the durable source of truth. With -multiple serving replicas, Enterprise routes traffic to surviving nodes when one fails; losing a cache node -temporarily raises latency while its replacement warms, rather than causing an outage. - -Sharing a format does not mean an Enterprise deployment automatically opens an existing Embedded database -- -plan how to move or connect your data and configure access for your deployment. - -## Embedded and Enterprise {#embedded-and-enterprise} - -LanceDB ships as two offerings on the same Lance format and table model. Start locally with Embedded, then move to -Enterprise when your team needs distributed scale, managed infrastructure, private deployment, or higher-throughput -curation, feature engineering, search and retrieval, and training workflows. - -### 1\. LanceDB Embedded {#1-lancedb-oss} - -**LanceDB Embedded** is an open-source, embedded retrieval library, with client SDKs in Python, TypeScript and -Rust -- the application itself plans queries, builds indexes, and runs background work, with no separate database -server to deploy. This fits local retrieval applications, notebooks, development, and single-node data pipelines, -where your application controls its own compute resources and [table maintenance](/maintenance/compaction). - -![LanceDB Embedded: the LanceDB SDK and the Lance format run in your application, reading and writing tables on local disk or in object storage.](/static/assets/images/overview/lancedb-embedded.png) - -### 2\. LanceDB Enterprise {#2-lancedb-enterprise} - -[LanceDB Enterprise](/enterprise) is a petabyte-scale (and beyond), distributed **multimodal lakehouse** platform -built for search, curation, feature engineering, and high-throughput training data access workflows on top of the -same core table abstraction, without building bespoke infrastructure. Applications connect through a LanceDB SDK -while the service handles requests across a fleet, with query serving, read execution and caching, and indexing -and background work sized and scaled as separate components. A control plane governs configuration, identity -and cluster lifecycle, separately from the data-plane components in the diagram below. See -[Distributed search](/enterprise/distributed-search) for how query nodes and plan executors divide a request. - -![LanceDB Distributed: the LanceDB SDK connects to LanceDB Enterprise, where a query fleet, executor and cache fleets, the realtime engine, and a jobs fleet run on top of the Lance format and object storage.](/static/assets/images/overview/lancedb-distributed.png) - -Teams choose Enterprise to: - -- **Serve growing workloads** -- add query-serving capacity and let Enterprise cache frequently read table data near - compute as traffic grows. -- **Reduce operational work** -- let the service handle background [compaction](/maintenance/compaction) and - [cleanup](/maintenance/cleanup) instead of scheduling them in application code. -- **Fit deployment requirements** -- run a managed deployment or bring LanceDB into your own cloud account, with - OpenTelemetry metrics and traces. -- **Connect data workflows** -- use the same tables for retrieval, curation, and training data access, with - [SQL](/basics/sql), [feature engineering](/feature-engineering), and [Geneva](/geneva) feature backfills. - -To set up LanceDB Enterprise in your organization, [reach out to us](https://www.lancedb.com/contact). - -### Compare features {#compare} - -| Area | Feature | Embedded | Enterprise | -| --- | --- | :-: | :-: | -| **Search** | [Vector search](/search/vector-search) | ✅ | ✅ | -| | [Full-text search](/search/full-text-search) | ✅ | ✅ | -| | [Hybrid search](/search/hybrid-search) | ✅ | ✅ | -| | [Filtering](/search/filtering) | ✅ | ✅ | -| | [Reranking](/reranking) | ✅ | ✅ | -| | [Query plans](/search/explain) | ✅ | ✅ | -| | [Distributed search](/enterprise/distributed-search) | ❌ | ✅ | -| **Indexing** | [Vector indexes](/indexing/vector-index) | ✅ | ✅ | -| | [Full-text indexes](/indexing/fts-index) | ✅ | ✅ | -| | [Scalar indexes](/indexing/scalar-index) | ✅ | ✅ | -| **SQL and curation** | [SQL (Arrow Flight SQL)](/basics/sql) | ❌ | ✅ | -| | [Aggregation and profiling](/curation/aggregate) | ❌ | ✅ | -| | [Sampling](/curation/sampling) | ❌ | ✅ | -| | [Joins](/curation/join) | ❌ | ✅ | -| | [Ranking and deduplication](/curation/windowing) | ❌ | ✅ | -| | [Near-duplicate detection](/curation/dedupe) | ❌ | ✅ | -| | [Chunking](/curation/chunking) | ❌ | ✅ | -| | [Changes since a version](/curation/changes) | ❌ | ✅ | -| | [Views](/management/view) | ❌ | ✅ | -| **Feature engineering** | [Computed columns, with refresh](/feature-engineering/add-computed-column) | ✅ | ✅ | -| | [Materialized views](/management/materialized-view) | ❌ | ✅ | -| | [Embedding registry](/embedding) | ✅ | ✅ | -| **Training** | [PyTorch data loader](/training/data-loading) | ✅ | ✅ | -| | [Permutations](/training/permutation) | ✅ | ✅ | -| | [Distributed training](/training/distributed-training) | ✅ | ✅ | -| **Data management** | [Branches](/tables/branching) | ✅ | ✅ | -| | [Compaction and cleanup](/maintenance/compaction) | ✅ | ✅ | -| | [Background jobs (managed indexing and maintenance)](/maintenance/background-jobs) | ❌ | ✅ | -| | [Real Time engine (streaming writes and reads)](/tables/realtime-engine) | ❌ | ✅ | -| **Security** | [Authentication](/enterprise/authentication) | ❌ | ✅ | -| | [Authorization](/governance/authorization) | ❌ | ✅ | +See [Embedded vs Enterprise](/basics/embedded-vs-enterprise) for a feature-by-feature comparison, including +architecture, latency, throughput, and day-to-day usage differences. ## Projects using LanceDB {#projects-using-lancedb} @@ -162,7 +94,7 @@ To set up LanceDB Enterprise in your organization, [reach out to us](https://www fraction of the disk footprint. - [le-wm](https://github.com/lucas-maes/le-wm) -- a joint-embedding predictive world model from pixels, trained on the stable-worldmodel platform and its LanceDB data layer. -- [lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb) -- a drop-in LanceDB backend for Hugging Face +- [lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb) -- a drop-in LanceDB backend for HuggingFace LeRobot datasets with faster loading across robotics datasets. ### Agentic applications {#agentic-applications} diff --git a/docs/web/indexing/fts-index.mdx b/docs/web/indexing/fts-index.mdx index ac3ff36e5..012b28eda 100644 --- a/docs/web/indexing/fts-index.mdx +++ b/docs/web/indexing/fts-index.mdx @@ -1,6 +1,6 @@ --- -title: "Full-Text Search (FTS) Index" -sidebarTitle: "FTS Index" +title: "Full-Text Search (FTS) Indexing" +sidebarTitle: "FTS Indexing" description: "Create and tune BM25-based full-text search indexes in LanceDB." icon: "book" availability: @@ -75,11 +75,13 @@ LanceDB rejects paths that don't resolve to a text leaf: The async API accepts the same dotted paths through `create_index`: + ```python Python icon="python" from lancedb.index import FTS await async_table.create_index("payload.text", config=FTS(with_position=True)) ``` + ## Configuration Options {#configuration-options} @@ -131,6 +133,7 @@ Lance `15.0.0-beta.1` revises the built-in stop-word lists, including the multil You can set the option through either the synchronous or asynchronous API. In the async Python API, pass it on the `FTS` config, and in the TypeScript API use the camelCase `blockSize` field on `FtsOptions`: + ```python Python icon="python" from lancedb.index import FTS @@ -142,6 +145,7 @@ await table.createIndex("text", { config: lancedb.Index.fts({ blockSize: 256 }), }); ``` + ### Phrase Query Configuration {#phrase-query-configuration} @@ -156,7 +160,8 @@ Enable phrase queries by setting: You can build an FTS index on a string field inside a struct by passing its full dotted path, like `nested.text`. The same path is used when you query the index through `fts_columns`, and the indexed column is reported back as the full path from `list_indices()`. -```python + +```python Python icon="python" # Schema: pa.struct([pa.field("text", pa.string())]) stored under the `nested` column. table.create_fts_index("nested.text") @@ -166,6 +171,7 @@ results = ( .to_list() ) ``` + Use the canonical Lance path: dot-separate each struct field from root to leaf (for example, `metadata.author.name`). The same convention applies to scalar and vector indexes. diff --git a/docs/web/indexing/gpu-indexing.mdx b/docs/web/indexing/gpu-indexing.mdx new file mode 100644 index 000000000..8370bfba1 --- /dev/null +++ b/docs/web/indexing/gpu-indexing.mdx @@ -0,0 +1,88 @@ +--- +title: "GPU Indexing" +sidebarTitle: "GPU Indexing" +description: "Build a vector index faster with GPU acceleration, manually in LanceDB Embedded or automatically in LanceDB Enterprise." +icon: "microchip" +keywords: ["gpu", "gpu indexing", "cuda", "mps", "ivf_pq", "index build"] +availability: + embedded: available + enterprise: available +--- + +import { + PyGpuIndexCuda as GpuIndexCuda, + PyGpuIndexMps as GpuIndexMps, +} from '/snippets/indexing.mdx'; + +GPU acceleration can reduce the time needed to build vector indexes on large +datasets. Actual build time depends on the index configuration, vector +dimensions, storage throughput and available GPU resources. + + +**Automatic GPU indexing** + +Automatic GPU Indexing is currently only available in [LanceDB Enterprise](/index#architecture). +Please [contact us](https://www.lancedb.com/contact) to enable this feature for your deployment. + +The vector index is created when you call `create_index`. The backend uses GPU resources +to build `IVF_PQ` indexes, with the number of GPUs set by the deployment's configuration. + +This process is also asynchronous by default, but you can use `wait_for_index` to convert it +into a synchronous process by waiting until the index is built. + + + +`wait_for_index(...)` waits for the index to exist and for `index_stats(...)` to report `num_unindexed_rows == 0`. It can time out if the table is receiving continuous writes while the build is trying to catch up. + +GPU acceleration changes how the vector index is built, not the lifecycle after the build. In the +embedded library, rows appended later still need `optimize()` before they are part of the index; a +deployment adds them in the background -- see [Incremental Indexing](/indexing/incremental-indexing). +`fast_search()` only searches indexed rows. + +## Manual GPU indexing in LanceDB Embedded {#gpu-manual-gpu-indexing-in-lancedb-oss} + +You can use the Python SDK to manually create the `IVF_PQ` index on a GPU. You'll need +[PyTorch>2.0](https://pytorch.org/). Note that GPU-based indexing is currently only +supported by the synchronous SDK in LanceDB Embedded. + +Specify the values `cuda` or `mps` (on Apple Silicon) for the `accelerator` parameter +to enable GPU training on your device. + +### GPU indexing on Linux {#gpu-gpu-indexing-on-linux} + + + + {GpuIndexCuda} + + + +### GPU indexing on macOS (Apple Silicon) {#gpu-gpu-indexing-on-macos-apple-silicon} + + + + {GpuIndexMps} + + + +## Performance considerations {#gpu-performance-considerations} + +- GPU memory usage scales with `num_partitions` and vector dimensions +- Size GPU memory for the training batches and index configuration +- Monitor memory use while choosing training batch sizes +- Measure build time and recall before changing training settings + +## Troubleshooting {#gpu-troubleshooting} + +If you encounter the error `AssertionError: Torch not compiled with CUDA enabled`, +you need to [install PyTorch with CUDA support](https://pytorch.org/get-started/locally/). + +## What to read next {#next} + + + + Keeping an index up-to-date as new data arrives. + + + Running these GPU workers alongside training on shared Slurm-scheduled infrastructure. + + diff --git a/docs/web/indexing/incremental-indexing.mdx b/docs/web/indexing/incremental-indexing.mdx new file mode 100644 index 000000000..42c864ae9 --- /dev/null +++ b/docs/web/indexing/incremental-indexing.mdx @@ -0,0 +1,98 @@ +--- +title: "Incremental Indexing" +sidebarTitle: "Incremental Indexing" +description: "Keep an index up-to-date as new data arrives, without a full rebuild." +icon: "refresh" +keywords: ["reindexing", "re-index", "incremental indexing", "reindex", "index_remap", "spfresh_merge"] +availability: + embedded: available + enterprise: available +--- + +import { + PyReindexingIncremental as ReindexingIncremental, +} from '/snippets/indexing.mdx'; + +As you add new data to your LanceDB tables, your indexes may become outdated. +Reindexing is the process of updating the index to account for new data. This +applies to either a full-text search (FTS) index or a vector index. +Reindexing is an important operation to run periodically as your data grows, +as it has performance implications. + +As data is being added and a reindex operation is running, LanceDB will +combine results from the existing index with exhaustive/flat search on the +new data. This is done to ensure that you're still retrieving results over +all your data, but it does come at a performance cost. The more data that you +add without reindexing, the impact on latency (due to exhaustive search) can +be noticeable. + +Rather than dropping an existing index entirely and reindexing from scratch, +LanceDB supports **incremental indexing**. + + +**Enterprise job types:** an index build runs as `reindex_` followed by the +algorithm, such as `reindex_ivf_pq`, `reindex_btree` or `reindex_fts`, and so +does folding new rows into an existing index. A create-only build, one that must +not replace an existing index, runs as `create_` followed by the algorithm +instead; Python's `create_scalar_index` and `create_fts_index` ask for that by +default. The name says which algorithm is building, not a separate feature. + + +## Triggering an incremental update {#incremental-reindexing} + +In the embedded library, you trigger an incremental indexing operation on +updated data with the `optimize()` method on a table. A deployment does this +for you and does not support `optimize()`, as described below. + +Table optimization performs three maintenance operations: + +1. **Compaction**: merges small fragments into larger ones to improve read performance +2. **Pruning/Cleanup**: removes files from versions older than a retention window (7 days by default) -- see [Cleanup](/maintenance/cleanup) for how retention works +3. **Index update**: adds newly-ingested data to existing vector, scalar, and FTS indexes + + + + {ReindexingIncremental} + + + +Enterprise + +LanceDB Enterprise supports incremental reindexing through an automated background process. Once enough new rows have been added to a table, the system automatically adds them to its indexes. As the dataset grows, indexes are asynchronously updated in the background. + +- While indexes are being rebuilt, queries use brute force methods on unindexed rows, which may temporarily increase latency. If you can omit unindexed rows, set `fast_search=True` to search only indexed data. + This can return incomplete results while indexing catches up. +- Use `index_stats()` to view the number of unindexed rows. This will be zero when indexes are fully up-to-date. If you call `wait_for_index(...)`, it polls the same status and can time out while continuous writes keep adding unindexed rows. +- Rows below the deployment's threshold stay unindexed until more arrive, so the count can stay above zero without further writes. `FM` indexes are not updated in the background. + +The benefit of using LanceDB Enterprise is that it automates the reindexing process +and operates continuously in the background, minimizing the impact on latency under high loads. +In LanceDB Embedded, you must manually manage the reindexing cadence based on your data growth and performance needs. +Opening a table in LanceDB Embedded logs a warning at most once per table per +process when any index has at least 1,000,000 unindexed rows. Set +`LANCEDB_LOG=warn` to surface this log if your logger hides warnings by default. + +## Index maintenance jobs {#index} + +Two further Enterprise job types keep an index correct as the rows underneath +it move, rather than adding new rows to it: + +| Job type | What it does | +| --- | --- | +| `index_remap` | Reassigns index entries after row ids shift underneath an index (the kind of remap a delta compaction can require). | +| `spfresh_merge` | Merges SPFresh-managed segments for indexes that use it. | + +See [Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution) +for why `index_remap` exists as a separate, deferred job rather than +happening synchronously inside every compaction. + +## What to read next {#next} + + + + How an index build itself scales across the jobs fleet. + + + Building a vector index faster with GPU acceleration. + + diff --git a/docs/web/indexing/index.mdx b/docs/web/indexing/index.mdx index e408acb78..963f2f567 100644 --- a/docs/web/indexing/index.mdx +++ b/docs/web/indexing/index.mdx @@ -24,8 +24,9 @@ patterns. LanceDB supports three main index families: | `FTS` (Full-text search) | String columns (e.g., title, description, content) requiring keyword-based search with BM25 ranking. | Full-text search index using BM25 ranking algorithm. Tokenizes text with configurable tokenization, stemming, stop word removal, and language-specific processing. | | `BTree` (Scalar) | Numeric, temporal, and string columns with mostly distinct values. Best for selective equality, inequality, and range predicates. | Sorted index storing sorted copies of scalar columns with block headers in a btree cache. Header entries map to blocks of rows (4096 rows per block) for efficient disk reads. | | `Bitmap` (Scalar) | Low-cardinality columns with few thousand or fewer distinct values. Accelerates equality and range filters. | Stores a bitmap for each distinct value in the column, with one bit per row indicating presence. Memory-efficient for low-cardinality data. | -| `LabelList` (Scalar) | List columns (e.g., tags, categories, keywords) requiring `array_contains_all` or `array_contains_any` filters. | Scalar index for `List` and `LargeList` columns of primitive values, using an underlying bitmap index structure to enable fast array membership lookups. | +| `LabelList` (Scalar) | List columns (e.g., tags, categories, keywords) requiring `array_has_all` or `array_has_any` filters. | Scalar index for `List` and `LargeList` columns of primitive values, using an underlying bitmap index structure to enable fast array membership lookups. | | `FM` (Scalar) | String or binary columns that need raw substring search. | FM-Index over `Utf8`, `LargeUtf8`, `Binary`, or `LargeBinary` data for filters such as `contains(path, 'needle')`. Use FTS instead for tokenized word search and BM25 ranking. | +| `NGram` (Scalar) | String columns that need substring search using character trigrams. | Trigram index over `Utf8` and `LargeUtf8` columns that narrows `contains(col, 'needle')` and some `LIKE` and regular expression predicates to rows sharing the query's trigrams, then rechecks the predicate. A query shorter than the trigram length cannot use it; use `FM` for arbitrary length substrings or `FTS` for tokenized word search. | A deployment builds the vector indexes `IVF_FLAT`, `IVF_PQ`, `IVF_RQ` and `IVF_HNSW_SQ`. `IVF_SQ`, `IVF_HNSW_FLAT` and `IVF_HNSW_PQ` are built only by the @@ -61,7 +62,7 @@ The distance metric is fixed once the index is built. Pick the distance metric b Scalar indexes can reduce the rows scanned for selective filters and speed up `merge_insert` key lookups. Start with columns used frequently in those operations, -then use [query plans](/search/explain) to check whether the index helps. Choose +then use [query plans](/basics/sql#query-plans) to check whether the index helps. Choose the index type based on the column's values: | Index | Best for | diff --git a/docs/web/indexing/reindexing.mdx b/docs/web/indexing/reindexing.mdx deleted file mode 100644 index 68d0f5d73..000000000 --- a/docs/web/indexing/reindexing.mdx +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: "Building and repairing indexes" -sidebarTitle: "Build & Repair" -description: "Learn how to keep your indexes up-to-date in LanceDB using incremental indexing, including best practices for adding new records without full reindexing." -icon: "refresh" -keywords: ["reindexing", "re-index", "incremental indexing", "reindex"] -availability: - embedded: available - enterprise: available ---- - -import { - PyReindexingIncremental as ReindexingIncremental, - PyGpuIndexCuda as GpuIndexCuda, - PyGpuIndexMps as GpuIndexMps, -} from '/snippets/indexing.mdx'; - -As you add new data to your LanceDB tables, your indexes may become outdated. -Reindexing is the process of updating the index to account for new data. This applies to either a full-text search (FTS) index or a vector index. Reindexing is an important operation to run periodically as your data grows, as it has performance implications. - -As data is being added and a reindex operation is running, LanceDB will combine results from the existing index with exhaustive/flat search on the new data. This is done to ensure that you're still retrieving results over all your data, but it does come at a performance cost. The more data that you add without reindexing, the impact on latency (due to exhaustive search) can be noticeable. - -Rather than dropping an existing index entirely and reindexing from scratch, LanceDB supports **incremental indexing**. - - -**Enterprise job types:** an index build runs as `reindex_` followed by the -algorithm, such as `reindex_ivf_pq`, `reindex_btree` or `reindex_fts`, and so -does folding new rows into an existing index. A create-only build, one that must -not replace an existing index, runs as `create_` followed by the algorithm -instead; Python's `create_scalar_index` and `create_fts_index` ask for that by -default. The name says which algorithm is building, not a separate feature. - - -## Incremental Reindexing {#incremental-reindexing} - -In the embedded library, you trigger an incremental indexing operation on -updated data with the `optimize()` method on a table. A deployment does this -for you and does not support `optimize()`, as described below. - -Table optimization performs three maintenance operations: - -1. **Compaction**: merges small fragments into larger ones to improve read performance -2. **Pruning/Cleanup**: removes files from versions older than a retention window (7 days by default) -3. **Index update**: adds newly-ingested data to existing vector, scalar, and FTS indexes - - - - {ReindexingIncremental} - - - -Enterprise - -LanceDB Enterprise supports incremental reindexing through an automated background process. Once enough new rows have been added to a table, the system automatically adds them to its indexes. As the dataset grows, indexes are asynchronously updated in the background. - -- While indexes are being rebuilt, queries use brute force methods on unindexed rows, which may temporarily increase latency. If you can omit unindexed rows, set `fast_search=True` to search only indexed data. - This can return incomplete results while indexing catches up. -- Use `index_stats()` to view the number of unindexed rows. This will be zero when indexes are fully up-to-date. If you call `wait_for_index(...)`, it polls the same status and can time out while continuous writes keep adding unindexed rows. -- Rows below the deployment's threshold stay unindexed until more arrive, so the count can stay above zero without further writes. `FM` indexes are not updated in the background. - -The benefit of using LanceDB Enterprise is that it automates the reindexing process -and operates continuously in the background, minimizing the impact on latency under high loads. -In LanceDB Embedded, you must manually manage the reindexing cadence based on your data growth and performance needs. - -## Disk utilization {#disk-utilization} - -Compaction by itself does not immediately free disk space, and can temporarily increase it because new -compacted files are written before old-version files are deleted. Disk space is reclaimed when old versions -are pruned during cleanup. Set retention only as low as your rollback and time-travel requirements allow. - -If you need to reclaim space more aggressively in LanceDB Embedded, use a shorter retention window: - - ```python Python icon=Python - from datetime import timedelta - - table.optimize(cleanup_older_than=timedelta(days=1)) - ``` - - -## Building on GPUs {#gpu} - -GPU acceleration can reduce the time needed to build vector indexes on large -datasets. Actual build time depends on the index configuration, vector -dimensions, storage throughput and available GPU resources. - - -**Automatic GPU indexing** -Enterprise-only - -Automatic GPU Indexing is currently only available in [LanceDB Enterprise](/enterprise/). -Please [contact us](https://www.lancedb.com/contact) to enable this feature for your deployment. - -The vector index is created when you call `create_index`. The backend uses GPU resources -to build `IVF_PQ` indexes, with the number of GPUs set by the deployment's configuration. - -This process is also asynchronous by default, but you can use `wait_for_index` to convert it -into a synchronous process by waiting until the index is built. - - - -`wait_for_index(...)` waits for the index to exist and for `index_stats(...)` to report `num_unindexed_rows == 0`. It can time out if the table is receiving continuous writes while the build is trying to catch up. - -GPU acceleration changes how the vector index is built, not the lifecycle after the build. In the -embedded library, rows appended later still need `optimize()` before they are part of the index; a -deployment adds them in the background. `fast_search()` only searches indexed rows. - -### Manual GPU indexing in LanceDB Embedded {#gpu-manual-gpu-indexing-in-lancedb-oss} - -You can use the Python SDK to manually create the `IVF_PQ` index on a GPU. You'll need -[PyTorch>2.0](https://pytorch.org/). Note that GPU-based indexing is currently only -supported by the synchronous SDK in LanceDB Embedded. - -Specify the values `cuda` or `mps` (on Apple Silicon) for the `accelerator` parameter -to enable GPU training on your device. - -#### GPU indexing on Linux {#gpu-gpu-indexing-on-linux} - - - - {GpuIndexCuda} - - - -#### GPU indexing on macOS (Apple Silicon) {#gpu-gpu-indexing-on-macos-apple-silicon} - - - - {GpuIndexMps} - - - -### Performance considerations {#gpu-performance-considerations} - -- GPU memory usage scales with `num_partitions` and vector dimensions -- Size GPU memory for the training batches and index configuration -- Monitor memory use while choosing training batch sizes -- Measure build time and recall before changing training settings - -### Troubleshooting {#gpu-troubleshooting} - -If you encounter the error `AssertionError: Torch not compiled with CUDA enabled`, -you need to [install PyTorch with CUDA support](https://pytorch.org/get-started/locally/). diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx index d99bb6003..f674a988d 100644 --- a/docs/web/indexing/scalar-index.mdx +++ b/docs/web/indexing/scalar-index.mdx @@ -1,6 +1,6 @@ --- -title: "Scalar Indexes" -sidebarTitle: "Scalar Index" +title: "Scalar Indexing" +sidebarTitle: "Scalar Indexing" description: "Learn how to use scalar indexes in LanceDB for efficient metadata filtering and query optimization." icon: "tree" availability: @@ -26,12 +26,13 @@ Scalar indexes accelerate filters on values such as numbers, categories and strings. Use them for selective table queries or metadata filters combined with vector and full-text search. -LanceDB supports four types of scalar indexes: +LanceDB supports five types of scalar indexes: - `BTREE`: Stores column data in sorted order for binary search. Best for columns with many unique values. - `BITMAP`: Uses bitmaps to track value presence. Ideal for columns with few unique values (e.g., categories, tags). -- `LABEL_LIST`: Special index for `List` and `LargeList` columns of primitive values supporting `array_contains_all` and `array_contains_any` queries. +- `LABEL_LIST`: Special index for `List` and `LargeList` columns of primitive values supporting `array_has_all` and `array_has_any` queries. - `FM`: FM-Index over string or binary columns that accelerates substring search via `contains(col, 'needle')`. +- `NGRAM`: Trigram index over UTF-8 string columns that accelerates substring search via `contains(col, 'needle')`, along with some `LIKE` and regular-expression filters. Use scalar indexes with: @@ -50,10 +51,11 @@ Use scalar indexes with: | Boolean, numbers or strings with fewer than 1,000 unique values | `<`, `=`, `>`, `in`, `between`, `is null` | `BITMAP` | | List of low cardinality of numbers or strings | `array_has_any`, `array_has_all` | `LABEL_LIST` | | String or binary (`Utf8`, `LargeUtf8`, `Binary`, `LargeBinary`) | `contains(col, 'needle')` | `FM` | +| String (`Utf8`, `LargeUtf8`) | `contains(col, 'needle')`, `LIKE`, regex | `NGRAM` | ## Scalar Index Operations -### 1. Build the Index +### 1\. Build the Index You can create multiple scalar indexes within a table. By default, the index will be `BTREE`, but you can always configure another type like `BITMAP` @@ -67,7 +69,7 @@ You can create multiple scalar indexes within a table. By default, the index wil If you are using LanceDB Enterprise, the `create_scalar_index` API returns immediately, but the building of the scalar index is asynchronous. To wait until all data is fully indexed, you can specify the `wait_timeout` parameter on `create_scalar_index()` or call `wait_for_index()` on the table. -### 2. Check Index Status +### 2\. Check Index Status @@ -77,7 +79,7 @@ If you are using LanceDB Enterprise, the `create_scalar_index` API returns immed `wait_for_index(...)` waits until the named scalar indexes exist and `index_stats(...)` reports `num_unindexed_rows == 0`. If a table is receiving steady writes, that fully indexed state may not stabilize before the timeout. In LanceDB Enterprise, rows added after the index was built are indexed only once enough have accumulated, so a small remainder can also keep the wait from finishing. -### 3. Update the Index +### 3\. Update the Index Updating the table data (adding, deleting, or modifying records) requires that you also update the scalar index. In the embedded library, call `optimize`, which will trigger an update to the existing scalar index. @@ -91,7 +93,7 @@ Updating the table data (adding, deleting, or modifying records) requires that y New data added after creating the scalar index will still appear in search results if optimize is not used, but with increased latency due to a flat search on the unindexed portion. LanceDB Enterprise does not support `optimize()`; instead it adds new rows to `BTREE`, `BITMAP` and `LABEL_LIST` indexes in the background once enough have accumulated. It does not update `FM` indexes automatically. -### 4. Run Indexed Searches +### 4\. Run Indexed Searches The following scan will be faster if the column `book_id` has a scalar index: @@ -109,22 +111,6 @@ Scalar indexes can also speed up scans containing a vector search or full text s -## Indexing nested fields - -Scalar indexes can target a scalar field inside a struct by passing its full dotted path. The path is preserved end to end: it's the value you pass to `create_scalar_index`, it's what `list_indices()` reports under `columns`, and it's the column reference you use in filter predicates. - -```python -# Schema: pa.struct([pa.field("user_id", pa.int32())]) stored under the `metadata` column. -table.create_scalar_index("metadata.user_id", name="metadata_user_id_idx") - -# The same dotted path works in WHERE clauses. -table.search().where("metadata.user_id = 42").limit(1).to_list() -``` - - -Nested paths follow Lance field-path semantics: dot-separate each struct field from root to leaf (for example, `metadata.author.name`). The same convention applies to FTS and vector indexes. - - ## FM-Index for substring search The `FM` index is a scalar index built over string or binary columns that @@ -177,11 +163,52 @@ tbl.create_index(&["text"], Index::Fm(FmIndexBuilder::default())) After the index is built, substring filters use it automatically: + +```python Python icon="python" +table.search().where("contains(text, 'needle')").limit(10).to_pandas() +``` + + +`list_indices()` reports the index type as `"Fm"`. + +## NGram index for substring search + +The `NGram` index is a scalar index over UTF-8 string columns. It tokenizes +values into overlapping character n-grams (using Lance's default trigram +parameters) and uses them to accelerate `contains(col, 'needle')`, along with +some `LIKE` and regular-expression filters. Unlike the `FM` index, which matches +arbitrary substrings of the raw bytes, the `NGram` index is trigram based, so a +query shorter than the n-gram length cannot be served by it. + +### Create an NGram index + +Build an NGram index with the async `create_index` API by passing the `NGram` +config in Python. In Rust, use `Index::NGram(NGramIndexBuilder::default())`. + + +```python Python icon="python" +from lancedb.index import NGram + +await tbl.create_index("text", config=NGram()) +``` + +```rust Rust icon="rust" +use lancedb::index::Index; +use lancedb::index::scalar::NGramIndexBuilder; + +tbl.create_index(&["text"], Index::NGram(NGramIndexBuilder::default())) + .execute() + .await?; +``` + + +After the index is built, substring filters use it automatically: + ```python table.search().where("contains(text, 'needle')").limit(10).to_pandas() ``` -`list_indices()` reports the index type as `"Fm"`. +`list_indices()` reports the index type as `"NGram"`. ## Index UUID Columns @@ -194,7 +221,7 @@ LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)` - TypeScript SDK version `0.19.0` or later -### 1. Define UUID Type +### 1\. Define UUID Type @@ -202,7 +229,7 @@ LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)` -### 2. Generate UUID Data +### 2\. Generate UUID Data @@ -210,7 +237,7 @@ LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)` -### 3. Create Table with UUID Column +### 3\. Create Table with UUID Column @@ -218,7 +245,7 @@ LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)` -### 4. Create and Wait for the Index +### 4\. Create and Wait for the Index @@ -226,7 +253,7 @@ LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)` -### 5. Perform Operations with the UUID Index +### 5\. Perform Operations with the UUID Index @@ -246,7 +273,9 @@ named `user.id` nested inside `metadata`), wrap that segment in backticks so LanceDB can tell the dot apart from the path separator: `` metadata.`user.id` ``. `list_indices()` echoes the same canonical path back, so the column you pass in -round-trips through index metadata regardless of nesting depth or escaping. +round-trips through index metadata regardless of nesting depth or escaping. Use the +same path in filter predicates, for example `metadata.user_id = 42`. FTS and vector +indexes follow the same path convention. diff --git a/docs/web/indexing/vector-index.mdx b/docs/web/indexing/vector-index.mdx index 3e2b7d6f0..33fc802fa 100644 --- a/docs/web/indexing/vector-index.mdx +++ b/docs/web/indexing/vector-index.mdx @@ -1,6 +1,6 @@ --- -title: "Vector Indexes" -sidebarTitle: "Vector Index" +title: "Vector Indexing" +sidebarTitle: "Vector Indexing" description: "Build and manage LanceDB vector indexes." icon: "arrow-up-right-dots" availability: @@ -55,7 +55,7 @@ Lance with `index_type`. | :--- | :--- | :--- | :--- | :--- | | Maximum compression | `IVF_RQ` | IVF indexing with RaBitQ quantization | Around `1/32` of raw size with `num_bits=1` | `IvfRq` | | Higher accuracy at small dimensions (`dimension <= 256`) | `IVF_PQ` | IVF indexing with product quantization | Usually `1/64` to `1/16` of raw size (depends on `num_sub_vectors`) | `IvfPq` | -| Best recall/latency trade-off | `IVF_HNSW_SQ` | IVF-HNSW indexing with scalar | Typically a little larger than `1/4` of raw size | `IvfHnswSq` | +| Best recall/latency trade-off | `IVF_HNSW_SQ` | IVF-HNSW indexing with scalar quantization | Typically a little larger than `1/4` of raw size | `IvfHnswSq` | | Highest recall / no quantization | `IVF_HNSW_FLAT` | IVF-HNSW indexing with no quantization; embedded library only | Around raw vector size plus HNSW graph overhead | `IvfHnswFlat` | @@ -84,7 +84,8 @@ giving an approximate ANN result. However, observe that a queried vector may lie near the boundary of $2$ or more partitions; thus, the true nearest neighbors are scattered across several different partitions. To address this, LanceDB exposes the `nprobes` parameter, which specifies the number of partitions searched. -A high `nprobes` parameter will yield more accurate results at slightly higher runtime. +A higher probe budget searches more partitions, which can improve recall at +higher CPU and I/O cost. IVF vector-space partitioning @@ -142,11 +143,12 @@ Learn how to configure, build, and search LanceDB vector indexes, including buil | Parameter | Description | | :--- | :--- | | `limit` | Number of results to return (the `k` in `k-ANN`). | -| `nprobes` | Sets both `minimum_nprobes` and `maximum_nprobes` to the same value in Lance. Leave unset to use Lance's adaptive defaults. At very high scales you will likely need to experiment to find your preferred recall / latency balance. | -| `minimum_nprobes` | Minimum number of partitions scanned. Leave unset to use Lance's default. | -| `maximum_nprobes` | Maximum number of partitions scanned. Only scans more than `minimum_nprobes` if an initial pass does not return enough results, which is useful for narrow filters. Leave unset, or set to `0`, to remove the cap. | +| `nprobes` | Search a fixed number of partitions per index segment. Leave unset to use Auto. | +| `search_effort` | A value from `0` to `1` for tuning recall and latency. `0.5` uses Auto; higher values search more partitions. This is not a recall percentage. | +| `minimum_nprobes` | Minimum number of partitions to search per segment. Auto may search more from the start. | +| `maximum_nprobes` | Maximum number of partitions to search per segment. Leave unset to allow further searching when needed. A low cap can reduce recall or return fewer results than requested. | | `ef` | HNSW search-time exploration factor. Start around `1.5 * k` and increase up to `10 * k` for higher recall. | -| `refine_factor` | Reads and reranks additional candidates in memory to recover recall lost to quantization. Start between `5` and `50` (a factor of `25` reads and reranks the top `25 * k` candidates) and measure the latency cost, typically a few milliseconds, against the recall gained. | +| `refine_factor` | Rerank candidates using full vectors to improve accuracy. A factor of `25` requests up to `25 * k` candidates. Higher values read more data; measure the recall gain and latency cost. | | `distance_range(lower_bound, upper_bound)` | Return only rows whose distance falls within `[lower_bound, upper_bound)`. Either bound is optional. Useful for near-duplicate detection or "close-enough" matching. | | `bypass_vector_index()` | Ignore the ANN index entirely and perform an exact (flat) scan. Can be used to measure ANN `recall@k`, or to query with a metric the index was not built for (e.g., a non-cosine query on a multivector column). | @@ -173,14 +175,17 @@ older client. -**Filtered queries and adaptive `nprobes`.** When a `where(...)` filter is active, LanceDB initially scans `minimum_nprobes` -partitions and uses a wider scan if too few rows are found. -Set `minimum_nprobes == maximum_nprobes` or call `nprobes(n)` to instead fix the partition count. -Whether a deployment widens the scan this way depends on its version; one that does not scans exactly -`minimum_nprobes` partitions. +Start with Auto, then measure recall and latency before changing probe settings. +If you set both `search_effort` and `nprobes`, effort takes precedence. Explicit +min/max bounds still apply; equal bounds fix the count. See +[tuning vector search](/search/vector-search#tuning-nprobes) for examples and +guidance on choosing these controls. -Here is an example of a vector search exercising several of the above parameters. + + +For a filtered search, you can let Auto choose within a range. The maximum also +limits further searching if too few matches are found: @@ -199,6 +204,8 @@ LanceDB also supports advanced search-time controls for thresholded retrieval, r + + **Using `bypass_vector_index`:** Use `bypass_vector_index` to compute an exact **kNN** result. Note that exact queries may be prohibitively slow on production scales. diff --git a/docs/web/ingestion/create-table.mdx b/docs/web/ingestion/create-table.mdx index ec13c02b7..5bae930a5 100644 --- a/docs/web/ingestion/create-table.mdx +++ b/docs/web/ingestion/create-table.mdx @@ -55,14 +55,11 @@ values, and set the size of your vectors. ## Create a table with data {#create-a-table-with-data} -The Python input examples below are complete programs. Install `lancedb` and -any additional libraries imported by the example, save one as a Python file, -and run it. Each uses its own temporary local database. - -The TypeScript and Rust blocks illustrate the corresponding input formats. -For a complete connection-to-result program in either language, expand -[the write workflow](#complete-example). Table names follow the -[naming rules](/basics/naming). +The Python, TypeScript and Rust blocks below illustrate the corresponding +input formats; each assumes a `db` connection already open, as in +[Connect to LanceDB](/basics/catalog). For a complete connection-to-result +program, expand [the write workflow](#complete-example). Table names +follow the [naming rules](/basics/naming). ### From list of objects {#from-list-of-objects} @@ -349,7 +346,7 @@ Use the `drop_table()` method on the database to remove a table. Dropping a table removes the table object. Deleting rows keeps the table and changes its contents; retained versions and cleanup are described in -[Cleanup](/maintenance/cleanup). +[Garbage Collection](/maintenance/cleanup). On a local database, dropping a table that does not exist raises an error; in Python, pass `ignore_missing=True` to suppress it. A deployment may report success instead, depending on how it stores its catalog, so do not rely on the @@ -369,7 +366,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/ingestion/define-storage-integration.mdx b/docs/web/ingestion/define-storage-integration.mdx new file mode 100644 index 000000000..446d47d22 --- /dev/null +++ b/docs/web/ingestion/define-storage-integration.mdx @@ -0,0 +1,175 @@ +--- +title: "Define Storage Integration" +sidebarTitle: "Define Storage Integration" +description: "Set up a reusable credential for AWS, GCP, Azure or HuggingFace before importing data from it." +icon: cloud +keywords: ["storage integration", "s3", "gcs", "azure", "huggingface", "credentials", "ingestion"] +availability: + embedded: unavailable + enterprise: available +--- + +Before you can [import data](/ingestion/import) from external storage or +[attach an existing database](/ingestion/migrate-from-embedded), define a +storage integration once per location. It is a namespace-scoped catalog +object that stores the credential -- neither operation names the +integration directly, LanceDB matches the URI you read against whichever +integration's prefix covers it. + +## What each provider needs {#providers} + +| Provider | Credential | Notes | +| --- | --- | --- | +| AWS S3 | An IAM role to assume, or a static access key pair | A role needs one extra step outside LanceDB: [trust policy setup](#trust). | +| Google Cloud Storage | A service account's JSON key | No role-based alternative. | +| Azure Blob Storage | A service principal's tenant, client ID and client secret | All three required together. | +| HuggingFace | An access token | Always required to create an integration. For anonymous access at HuggingFace's default rate limits, register no integration for that prefix instead. | + +Every credential option takes a [Secret](/management/secret) reference, +never the value directly -- create the Secret first. + +## Create one {#create} + +### AWS S3 {#aws} + +Give either an IAM role to assume, or a static access key pair -- mixing +the two, or supplying only one half of the key pair, is refused. + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION raw + STORAGE_PROVIDER = 'S3' + STORAGE_PREFIX = 's3://customer-data/raw/' + STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/lancedb-access' + +CREATE STORAGE INTEGRATION raw + STORAGE_PROVIDER = 'S3' + STORAGE_PREFIX = 's3://customer-data/raw/' + STORAGE_AWS_ACCESS_KEY_ID_SECRET = aws_key_id + STORAGE_AWS_SECRET_ACCESS_KEY_SECRET = aws_key_secret +``` +```python Python icon="python" +db.create_storage_integration( + "raw", "s3://customer-data/raw/", + storage_provider="S3", + aws_role_arn="arn:aws:iam::123456789012:role/lancedb-access", +) + +db.create_storage_integration( + "raw", "s3://customer-data/raw/", + storage_provider="S3", + aws_access_key_id_secret="aws_key_id", + aws_secret_access_key_secret="aws_key_secret", +) +``` +```rust +use lancedb::storage_integration::CreateStorageIntegrationRequest; + +let info = db.create_storage_integration( + "raw", + CreateStorageIntegrationRequest::s3( + "s3://customer-data/raw/", + "arn:aws:iam::123456789012:role/lancedb-access", + ), + &[], +).await?; +``` + + +### Google Cloud Storage {#gcp} + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION gcs + STORAGE_PROVIDER = 'GCP' + STORAGE_PREFIX = 'gs://customer-data/raw/' + GCP_CREDENTIALS_JSON_SECRET = gcp_service_account +``` +```python Python icon="python" +db.create_storage_integration( + "gcs", "gs://customer-data/raw/", + storage_provider="GCP", + gcp_credentials_json_secret="gcp_service_account", +) +``` + + +The Secret holds the full service-account JSON key. GCP has no +role-based alternative. + +### Azure Blob Storage {#azure} + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION blobs + STORAGE_PROVIDER = 'AZURE' + STORAGE_PREFIX = 'az://customer-data/raw/' + STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount' + STORAGE_AZURE_TENANT_ID_SECRET = azure_tenant + STORAGE_AZURE_CLIENT_ID_SECRET = azure_client + STORAGE_AZURE_CLIENT_SECRET_SECRET = azure_credential +``` +```python Python icon="python" +db.create_storage_integration( + "blobs", "az://customer-data/raw/", + storage_provider="AZURE", + azure_storage_account="customeraccount", + azure_tenant_id_secret="azure_tenant", + azure_client_id_secret="azure_client", + azure_client_secret_secret="azure_credential", +) +``` + + +All four options are required together; there is no role-based +alternative for Azure. + +### HuggingFace {#huggingface} + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION hub + STORAGE_PROVIDER = 'HUGGINGFACE' + STORAGE_PREFIX = 'hf://datasets/owner/private/data/' + HUGGINGFACE_TOKEN_SECRET = hf_token +``` +```python Python icon="python" +db.create_storage_integration( + "hub", "hf://datasets/owner/private/data/", + storage_provider="HUGGINGFACE", + huggingface_token_secret="hf_token", +) +``` + + +`HUGGINGFACE_TOKEN_SECRET` is required to create this integration; omitting +it is rejected, not treated as anonymous. For anonymous access at +HuggingFace's default rate limits, register no integration for that prefix +at all. + +### Finish the AWS trust policy {#trust} + +An IAM role integration needs one step outside LanceDB: describing it +returns the `trust_policy` and `permissions_policy` documents your role +needs. Attach them in AWS, then describe the integration again and check +`access_verified` to confirm LanceDB can assume the role. A static access +key pair skips this step entirely. + +See [Storage Integration](/sql/ddl/storage-integration) for every +provider's complete option reference, S3's two credential modes in full, +and the output schema, or [Storage Integration](/management/storage-integration) +for the Python and SQL CRUD operations at a glance. + +## What to read next {#next} + + + + Read or import through the integration once it exists. + + + Attach an existing database at a location the integration covers. + + + The complete SQL reference: every provider's options and output columns. + + diff --git a/docs/web/ingestion/delete.mdx b/docs/web/ingestion/delete.mdx index 2b961fc4b..b80ab1c33 100644 --- a/docs/web/ingestion/delete.mdx +++ b/docs/web/ingestion/delete.mdx @@ -34,7 +34,7 @@ database is removed when the program finishes. `python delete_rows.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `delete_rows.mts`, and run `node delete_rows.mts` with Node.js 22.18 or later. -- **Rust:** download the [Rust examples](/static/code/ingestion-feedback-rust.zip), +- **Rust:** download the [Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-feedback-rust.zip), extract the project, and run `cargo run --locked --bin delete`. @@ -72,7 +72,7 @@ In LanceDB Embedded, `optimize()` provides maintenance operations. In Enterprise maintenance and retention follow the service configuration. Choose retention according to the history you need, rather than shortening it as part of a routine delete example. See [Compaction](/maintenance/compaction) and -[Cleanup](/maintenance/cleanup) for the separate maintenance workflow. +[Garbage Collection](/maintenance/cleanup) for the separate maintenance workflow. ## Complete write workflow {#complete-example} @@ -85,7 +85,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/ingestion/import.mdx b/docs/web/ingestion/import.mdx new file mode 100644 index 000000000..0affeb4cf --- /dev/null +++ b/docs/web/ingestion/import.mdx @@ -0,0 +1,74 @@ +--- +title: "Import Datasets" +sidebarTitle: "Import Datasets" +description: "Create a table directly from a HuggingFace dataset or an existing Lance dataset in object storage, with one CREATE TABLE AS SELECT." +icon: file-import +keywords: ["import", "ctas", "create table as select", "huggingface", "s3", "gcs", "azure"] +availability: + embedded: unavailable + enterprise: available +--- + +A `CREATE TABLE ... AS SELECT` (CTAS) reads directly from a HuggingFace +dataset or an existing Lance dataset in object storage, once a +[storage integration](/ingestion/define-storage-integration) covers that +location -- the integration is never named in the statement, LanceDB +matches it by URI prefix. + +## Import a HuggingFace dataset {#huggingface} + + +```sql SQL icon="database" +CREATE TABLE imported AS +SELECT * FROM 'hf://datasets/owner/repo/data/train-*.parquet' +``` + + +See [Inspect Datasets](/curation/inspect-datasets#import) for +the full workflow, including querying a dataset directly without importing +it first. + +## Import a Lance dataset from object storage {#object-storage} + + +```sql SQL icon="database" +CREATE TABLE events_copy AS +SELECT * FROM 's3://customer-data/raw/events.lance' +``` + + +An `s3://`, `gs://` or `az://` prefix reads an existing **Lance** dataset +the same way as a managed table -- use this to copy a dataset another +process already wrote in Lance format, not an arbitrary file format. See +[Storage Integration](/sql/ddl/storage-integration#read-import) for GCS and +Azure examples. + +## How the import runs {#distributed} + +See [Distributed Write](/enterprise/distributed-write) for how an import's +writes divide across plan executors, and when a small import instead runs +as one local task. + + +Importing requires a native database with `database_manifest_enabled`. +Combining a HuggingFace source with a WAL-backed destination table in one +CTAS is rejected, since the import cannot publish a base-only read that +omits the destination's unflushed data. + + +## What to read next {#next} + + + + Set up the credential an import reads through. + + + Query and import HuggingFace or object-storage datasets in full. + + + How an import's writes divide across plan executors. + + + The complete SQL reference for every provider. + + diff --git a/docs/web/ingestion/index.mdx b/docs/web/ingestion/index.mdx index 28cfce650..26628c017 100644 --- a/docs/web/ingestion/index.mdx +++ b/docs/web/ingestion/index.mdx @@ -55,7 +55,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/ingestion/insert.mdx b/docs/web/ingestion/insert.mdx index cd15bc65b..befc1c37b 100644 --- a/docs/web/ingestion/insert.mdx +++ b/docs/web/ingestion/insert.mdx @@ -112,7 +112,7 @@ Each program uses a temporary local database and removes it when finished. `python insert_progress.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `insert_progress.mts`, and run `node insert_progress.mts` with Node.js 22.18 or later. -- **Rust:** download the [Rust examples](/static/code/ingestion-feedback-rust.zip), +- **Rust:** download the [Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-feedback-rust.zip), extract the project, and run `cargo run --locked --bin progress`. @@ -192,10 +192,12 @@ Two environment variables control how a multipart write's parts are cut. Both ar A part is cut after the input batch that reaches either limit, so cuts fall between batches. Lower the byte budget, with smaller input batches, when large ingests hit the read timeout; lower the duration when uploads are slow or throttled and the byte budget isn't the limiting factor. -```bash + +```bash Bash icon="terminal" export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=1073741824 # 1 GiB export LANCE_CLIENT_MAX_REQUEST_DURATION=120 # 2 minutes ``` + Splitting into more parts does not change the final table. The server stages the parts under their shared upload ID before committing the write. This upload protocol is separate from repeating an application-level @@ -212,7 +214,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/ingestion/merge-insert.mdx b/docs/web/ingestion/merge-insert.mdx index a9ad3071c..8106e7706 100644 --- a/docs/web/ingestion/merge-insert.mdx +++ b/docs/web/ingestion/merge-insert.mdx @@ -1,6 +1,6 @@ --- -title: "Merge insert" -sidebarTitle: "Merge Insert" +title: "Merge" +sidebarTitle: "Merge" description: "Match incoming records by key and choose which rows to update, insert or remove." icon: code-merge availability: @@ -30,6 +30,8 @@ import { import { PyWriteWorkflow, TsWriteWorkflowBody, TsWriteWorkflowTail, RsWriteWorkflow } from '/snippets/ingestion_examples.mdx'; +Early access in Enterprise + Use merge insert when incoming records should be compared with existing rows. Combine update and insert policies for an **upsert**. Use [append](/ingestion/insert) when every incoming row should simply be added. @@ -241,7 +243,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/ingestion/migrate-from-embedded.mdx b/docs/web/ingestion/migrate-from-embedded.mdx new file mode 100644 index 000000000..e55c29275 --- /dev/null +++ b/docs/web/ingestion/migrate-from-embedded.mdx @@ -0,0 +1,74 @@ +--- +title: "Attach Database" +sidebarTitle: "Attach Database" +description: "Point Enterprise at an existing database in object storage with ATTACH DATABASE, without copying data." +icon: plug +keywords: ["attach database", "migrate", "embedded", "object storage", "s3", "gcs", "azure"] +availability: + embedded: unavailable + enterprise: available +--- + +If your LanceDB Embedded database already lives in object storage -- +Embedded reads and writes tables on S3, GCS or Azure as well as local +disk -- you can move to Enterprise by attaching that same location, +rather than copying any data. A database on local disk has no such path: +`ATTACH DATABASE` only accepts an object-storage URI or a path relative +to Enterprise's own storage root, never a local filesystem path. Move it +to object storage first if it is not there already. + +## Prerequisites {#prerequisites} + +A [storage integration](/sql/ddl/storage-integration) covering the +database's location must already exist. `ATTACH DATABASE` never names an +integration explicitly -- Enterprise automatically binds the most +specific integration whose `STORAGE_PREFIX` covers the location you +attach. + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION raw + STORAGE_PROVIDER = 'S3' + STORAGE_PREFIX = 's3://customer-data/embedded-db/' + STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/lancedb-access' +``` + + +## Attach the database {#attach} + + +```sql SQL icon="database" +ATTACH DATABASE analytics WITH (location = 's3://customer-data/embedded-db/') +``` + + +See [Database](/sql/ddl/database#attach) for the full `ATTACH DATABASE` +syntax, including GCS and Azure locations (Azure requires an +account-qualified URI), `IF NOT EXISTS`, and quoted names. + +## What changes, and what doesn't {#what-changes} + +Attaching makes the location a database LanceDB Enterprise manages the +same way as one it created itself: Enterprise writes its own tracking +metadata into that location to bring it under management, enabling +capabilities Embedded never had there -- every table becomes reachable +through Enterprise's SQL and SDK surface immediately, with Enterprise's +authorization, Secrets, Functions, and +[background maintenance](/basics/jobs) now available to +it. Attaching does not rewrite, move, or re-encode any table's own data. + +[`DROP DATABASE`](/sql/ddl/database#drop) on an attached database +unregisters it and releases the storage-integration reference, without +deleting the underlying data -- the location can be reattached at any +time. + +## What to read next {#next} + + + + Configure the credential an attach depends on, for S3, GCS, or Azure. + + + Full ATTACH, CREATE, DESCRIBE and DROP DATABASE syntax. + + diff --git a/docs/web/ingestion/realtime-write.mdx b/docs/web/ingestion/realtime-write.mdx index bed77eed5..5b61e67bc 100644 --- a/docs/web/ingestion/realtime-write.mdx +++ b/docs/web/ingestion/realtime-write.mdx @@ -1,22 +1,33 @@ --- -title: "Real Time writes" -sidebarTitle: "Real Time Write" +title: "RTE Write (Upsert)" +sidebarTitle: "RTE Write (Upsert)" description: "Enable the real time engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds." icon: "bolt" keywords: ["rte", "real time engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] availability: - embedded: unavailable + embedded: available enterprise: available --- The [real time engine](/tables/realtime-engine) puts an LSM-style write tier in front of a table, turning many small writes into a few large commits. This page covers enabling it and writing to a table; for querying an RTE table, see -[Real Time reads](/search/realtime-read). +[RTE reads](/search/realtime-read). + +`table.enable_rte(spec)` is the same call on both connections, but what it +does underneath differs: + +- **Embedded** runs Lance's MemWAL `ShardWriter` directly in your process -- + the WAL buffer, memtables and SSTables all live wherever your table does, and + there is no separate serving layer to scale or configure. +- **Enterprise** forwards the call to the server, which runs it on a + dedicated, horizontally scalable WAL-node tier instead of your table's + query-serving fleet. See [Distributed RTE Write](/enterprise/distributed-real-time-write) + for how that tier shards a table's writes and the throughput limits that come with it. ## Getting started {#getting-started} -### 1. Create a table with a primary key {#primary-key} +### 1\. Create a table with a primary key {#primary-key} RTE deduplicates writes by primary key. Create the table with a non-nullable key column, then declare it with `set_unenforced_primary_key`. The key is a @@ -32,12 +43,12 @@ like [LeRobotDataset](/integrations/lerobotdataset)'s `frames` table — ```python Python icon="python" from datetime import timedelta -import lancedb import numpy as np import pyarrow as pa from lancedb import RTEWriteSpec from lancedb.index import FTS, BTree, IvfPq +# Embedded: db = lancedb.connect("./my_db") db = lancedb.connect("db://my_db", api_key="...", host_override="https://...") dim = 768 @@ -50,6 +61,46 @@ schema = pa.schema([ frames = db.create_table("frames", schema=schema) frames.set_unenforced_primary_key("frame_id") ``` + +```typescript TypeScript icon="square-js" +import * as arrow from "apache-arrow"; + +const dim = 768; +const schema = new arrow.Schema([ + new arrow.Field("frame_id", new arrow.Int64(), false), + new arrow.Field("video_id", new arrow.Utf8(), false), + new arrow.Field( + "embedding", + new arrow.FixedSizeList(dim, new arrow.Field("item", new arrow.Float32(), true)), + true, + ), + new arrow.Field("caption", new arrow.Utf8(), true), +]); + +const frames = await db.createEmptyTable("frames", schema); +await frames.setUnenforcedPrimaryKey("frame_id"); +``` + +```rust +use std::sync::Arc; + +use arrow_schema::{DataType, Field, Schema}; + +let dim = 768; +let schema = Arc::new(Schema::new(vec![ + Field::new("frame_id", DataType::Int64, false), + Field::new("video_id", DataType::Utf8, false), + Field::new( + "embedding", + DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), dim), + true, + ), + Field::new("caption", DataType::Utf8, true), +])); + +let frames = db.create_empty_table("frames", schema).execute().await?; +frames.set_unenforced_primary_key(["frame_id"]).await?; +``` Or in SQL: @@ -60,7 +111,7 @@ ALTER TABLE frames SET UNENFORCED PRIMARY KEY (frame_id) ``` -### 2. Create indexes {#indexes} +### 2\. Create indexes {#indexes} By default, RTE maintains every supported index on the table, including indexes created after it is enabled. A scalar index on the primary key is @@ -75,12 +126,22 @@ frames.wait_for_index(["embedding_idx", "caption_idx", "frame_id_idx"], timeout= ``` -### 3. Enable RTE {#enable} +### 3\. Enable RTE {#enable} ```python Python icon="python" frames.enable_rte(RTEWriteSpec.unsharded()) ``` + +```typescript TypeScript icon="square-js" +await frames.enableRTE({ specType: "unsharded" }); +``` + +```rust +use lancedb::table::RTEWriteSpec; + +frames.enable_rte(RTEWriteSpec::unsharded()).await?; +``` Or in SQL: @@ -91,7 +152,7 @@ ALTER TABLE frames SET RTE ``` -### 4. Write {#write} +### 4\. Write {#write} On an RTE table, an upsert through `merge_insert` is the only way to write @@ -101,7 +162,7 @@ conditional updates or deleting rows missing from the source, are rejected. Writes go through `merge_insert` on the primary key, and are visible to queries -immediately — see [Real Time reads](/search/realtime-read) for querying them +immediately — see [RTE reads](/search/realtime-read) for querying them back: @@ -161,36 +222,23 @@ frames.disable_rte() ``` -## Write performance {#write-performance} +## Write throughput {#write-throughput} RTE acknowledges a write as soon as it is durable in the write-ahead log, so -ingest is no longer limited by how fast the table can commit. +ingest is no longer limited by how fast the table can commit. On Embedded, +durability means your local disk or object store, so throughput is bounded by +your own machine's resources. -**Compared with writing directly to the table.** On tables ranging from -hundreds of thousands to tens of millions of rows, RTE delivered 4–12× the -write throughput and 24–52× lower p99 write latency, depending on the mix of -inserts, updates, and deletes. - -**Scaling with shards.** An RTE table can be split into -[shards](/sql/ddl/table#properties) that write independently, and a single -table's ingest grows with its shard count. In our testing on AWS, with every -index on the table (vector, full-text, and BTree) kept current, a single table -reached these peak rates: - -| Shards | Peak ingest | -| --: | --: | -| 1 | 90 MB/s | -| 2 | 170 MB/s | -| 4 | 340 MB/s | -| 8 | 625 MB/s | -| 16 | 690 MB/s | -| 32 | 885 MB/s | - -Adding shards scales a table's ingest nearly linearly. +An Enterprise table can be split into shards that write independently, with +each shard's durable-append throughput bounded by its WAL node's own +capacity -- measured, not an enforced cap. See +[Distributed RTE Write](/enterprise/distributed-real-time-write#throughput) +for the numbers. ## Next steps {#next-steps} -- [Real Time reads](/search/realtime-read) — query an RTE table -- [How the real time engine works](/tables/realtime-engine#how-it-works) +- [RTE reads](/search/realtime-read) — query an RTE table +- [Distributed RTE Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales this +- [How the real time engine works](/tables/realtime-engine#memwal-format) - [Merge insert](/ingestion/merge-insert) - [`ALTER TABLE ... SET RTE`](/sql/ddl/table#properties) diff --git a/docs/web/ingestion/update.mdx b/docs/web/ingestion/update.mdx index ad4ae23b2..4e2c2160c 100644 --- a/docs/web/ingestion/update.mdx +++ b/docs/web/ingestion/update.mdx @@ -78,13 +78,20 @@ Read the selected rows again and inspect the changed fields. For another connection or table handle, account for its [read consistency](/tables/consistency) settings. +Python's `update` does not compute embeddings. When changing a configured embedding +source column, provide every associated vector column in the same call. This applies +to both literal values and SQL expressions, and to synchronous and asynchronous +tables. Otherwise, the call raises `ValueError` before writing any rows. Use +[`merge_insert`](/ingestion/merge-insert) with the new source values to generate +embeddings automatically. + Nested-field updates are not supported by these operations. For schema changes, see [schema evolution](/management/table#schema). Treat derived values separately: changing an input field is not a guarantee that every stored feature has been recomputed. See [Refresh a computed column](/feature-engineering/refresh-column). Updates can change index coverage and query cost. After a large update, -inspect the workload and follow [index maintenance](/indexing/reindexing) +inspect the workload and follow [index maintenance](/indexing/incremental-indexing) guidance for the backend you use. ## Complete write workflow {#complete-example} @@ -98,7 +105,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/integrations/ai/agno.mdx b/docs/web/integrations/ai/agno.mdx index 9ad9daeac..99188a8fc 100644 --- a/docs/web/integrations/ai/agno.mdx +++ b/docs/web/integrations/ai/agno.mdx @@ -146,6 +146,6 @@ To start, LanceDB Embedded can run from a local directory, so transcript data ca - One explicit Agno `Knowledge` object, backed by LanceDB, defines both ingestion and search behavior in one place. - Fewer moving parts means the tutorial stays readable and the same pattern is easier to carry into production code. -As your application needs grow, you can migrate to LanceDB [Enterprise](/enterprise) for +As your application needs grow, you can migrate to LanceDB [Enterprise](/index#architecture) for convenience features like automatic compaction and reindexing and the ability to scale to really large datasets. diff --git a/docs/web/integrations/ai/genkit.mdx b/docs/web/integrations/ai/genkit.mdx index 1ccbf834d..71c0e9a73 100644 --- a/docs/web/integrations/ai/genkit.mdx +++ b/docs/web/integrations/ai/genkit.mdx @@ -17,9 +17,11 @@ inside your Genkit flows, so you can index, search, and retrieve data efficientl applications. ### Installation {#installation} -```bash + +```bash Bash icon="terminal" pnpm install genkitx-lancedb ``` + ### Usage {#usage} @@ -30,18 +32,24 @@ Adding LanceDB plugin to your genkit instance.
You can run this app with the following command: -```bash + +```bash Bash icon="terminal" genkit start -- tsx --watch src/index.ts ``` + This'll add LanceDB as a retriever and indexer to the genkit instance. You can see it in the GUI view Screenshot 2025-05-11 at 7 21 05 PM -**Testing retrieval on a sample table** -Let's see the raw retrieval results +### Testing retrieval on a sample table {#testing-retrieval-on-a-sample-table} + +To see the raw retrieval results, open the LanceDB retriever in the Genkit Developer UI, +enter a query and run it: Screenshot 2025-05-11 at 7 21 05 PM -On running this query, you'll get 5 results fetched from the lancedb table, where each result looks something like this: + +The retriever returns 5 results from the LanceDB table. Each result looks something like this: + Screenshot 2025-05-11 at 7 21 18 PM diff --git a/docs/web/integrations/ai/hermes-agent.mdx b/docs/web/integrations/ai/hermes-agent.mdx index e899e2e60..8a71f5cc4 100644 --- a/docs/web/integrations/ai/hermes-agent.mdx +++ b/docs/web/integrations/ai/hermes-agent.mdx @@ -54,17 +54,21 @@ done, `rm -rf ~/.hermes/profiles/demo` removes all trace. Skip this if you already have Hermes installed. -```bash + +```bash Bash icon="terminal" curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash ``` + This shallow-clones the plugin into `~/.hermes/plugins/lancedb/`. -```bash + +```bash Bash icon="terminal" hermes plugins install lancedb/hermes-agent-memory ``` + @@ -72,9 +76,11 @@ Hermes loads plugins inside its own Python interpreter, so the dependencies go * into a separate virtualenv. (This interpreter is shared across profiles, so you only install once.) -```bash + +```bash Bash icon="terminal" uv pip install --python ~/.hermes/hermes-agent/venv/bin/python3 lancedb openai pyyaml ``` + @@ -91,16 +97,20 @@ change needed. See [Configuration](#configuration) below. Switch memory on and pick this plugin: -```bash + +```bash Bash icon="terminal" hermes memory setup # choose "lancedb" ``` + Then confirm it's actually active before you start chatting. This is the one step worth not skipping, because Hermes quietly falls back to its built-in notes if the provider isn't set: -```bash + +```bash Bash icon="terminal" hermes memory status ``` + ```text Memory status @@ -160,9 +170,11 @@ line below: First, take Hermes' built-in notes out of the picture so recall can *only* come from LanceDB (the two layers run side by side otherwise, and either could answer): -```bash + +```bash Bash icon="terminal" hermes config set memory.memory_enabled false ``` + Now start a fresh session (`/new`) and ask for the convention back, worded completely differently from how you saved it: @@ -260,13 +272,13 @@ it's a plain LanceDB table, you can open it directly and see exactly what the ag A `kind` column separates extracted `fact` rows from the raw `turn` rows they were drawn from: -```python -import lancedb - + +```python Python icon="python" db = lancedb.connect("~/.hermes/lancedb") tbl = db.open_table("memories") print(tbl.to_pandas()[["kind", "category", "content"]].head()) ``` + ## Configuration {#configuration} @@ -321,7 +333,7 @@ per-question-type breakdown, and a reproducible harness, see the - **Memories are structured and traceable.** Each fact is a row with metadata and a link back to the messages it came from, and `forget` always previews before it deletes. - **Nothing about it is a dead end.** As your needs grow, the same table abstraction carries - over to LanceDB [Enterprise](/enterprise) for automatic compaction, reindexing, and scale. + over to LanceDB [Enterprise](/index#architecture) for automatic compaction, reindexing, and scale. To try it, install the plugin, enable it with `hermes memory setup`, and run the kind of workflow we walked through above. diff --git a/docs/web/integrations/ai/huggingface.mdx b/docs/web/integrations/ai/huggingface.mdx index b284d38a2..603ce3b68 100644 --- a/docs/web/integrations/ai/huggingface.mdx +++ b/docs/web/integrations/ai/huggingface.mdx @@ -1,17 +1,17 @@ --- -title: "Hugging Face Hub" -sidebarTitle: "Hugging Face" -description: "Use LanceDB directly on Lance datasets hosted on the Hugging Face Hub for multimodal search and retrieval." +title: "HuggingFace Hub" +sidebarTitle: "HuggingFace" +description: "Use LanceDB directly on Lance datasets hosted on the HuggingFace Hub for multimodal search and retrieval." availability: embedded: available enterprise: available --- -[Hugging Face Hub](https://huggingface.co/datasets?format=format:lance&sort=trending) is a popular platform for sharing machine learning datasets, models, and other resources. +[HuggingFace Hub](https://huggingface.co/datasets?format=format:lance&sort=trending) is a popular platform for sharing machine learning datasets, models, and other resources. -LanceDB can directly scan Lance datasets hosted on the [Hugging Face Hub](https://huggingface.co/datasets?format=format:lance) with `hf://` URIs. +LanceDB can directly scan Lance datasets hosted on the [HuggingFace Hub](https://huggingface.co/datasets?format=format:lance) with `hf://` URIs. This is enabled under the hood by the [lance-huggingface](https://lance.org/integrations/huggingface/) -integration that allows users to stream Lance datasets directly from Hugging Face without needing to +integration that allows users to stream Lance datasets directly from HuggingFace without needing to download them first. For ML and AI engineers working in LanceDB, this capability is incredibly useful for quickly exploring @@ -22,7 +22,7 @@ The snippets below use the [`lance-format/laion-1m`](https://huggingface.co/data dataset published in Lance format. The dataset includes a million image-caption pairs, and the Lance dataset can package image embeddings alongside the metadata. This makes it useful for demonstrating LanceDB's multimodal search capabilities in combination with easy sharing via the -Hugging Face Hub. +HuggingFace Hub. The LAION table includes multimodal columns such as: @@ -33,33 +33,37 @@ The LAION table includes multimodal columns such as: ## Install dependencies {#install-dependencies} -```bash + +```bash Bash icon="terminal" pip install lancedb pillow ``` + ## Open the dataset with LanceDB {#open-the-dataset-with-lancedb} LanceDB can open the dataset directly from the Hub, without needing to download it first. Note that in LanceDB, you need to specify the table name when opening a Lance dataset, -and the Hugging Face convention is to use `train` and `test` splits for datasets. +and the HuggingFace convention is to use `train` and `test` splits for datasets. The LAION dataset is uploaded as a single split named `train`, so we specify the table name that contains the `*.lance` files when opening the dataset. -```python -import lancedb - + +```python Python icon="python" db = lancedb.connect("hf://datasets/lance-format/laion-1m/data") table = db.open_table("train") print(f"Opened table: {table.name}") print(f"Rows: {len(table)}") ``` + ## Inspect schema and available indexes {#inspect-schema-and-available-indexes} -```python + +```python Python icon="python" print(table.schema) ``` + This prints the schema of the LAION table. Note that there's an image embedding column that's a fixed-size list of 768-dimensional floats, and a binary column containing the raw JPEG bytes of the image. ``` @@ -83,12 +87,14 @@ img_emb: fixed_size_list[768] image: binary ``` -When inspecting Lance datasets from Hugging Face, it's also a good idea to check whether the dataset author included +When inspecting Lance datasets from HuggingFace, it's also a good idea to check whether the dataset author included any pre-built indexes that you can use for search. You can check the available indexes with: -```python + +```python Python icon="python" print(table.list_indices()) ``` + ``` [ Index(IvfPq, columns=["img_emb"], name="img_emb_idx"), @@ -102,7 +108,7 @@ without needing to build the indexes ourselves! If you see an empty list, it may be because the dataset author did not include the index files when uploading -to Hugging Face. You can download the dataset locally, and build the indexes yourself. See the [indexing guide](/indexing/) +to HuggingFace. You can download the dataset locally, and build the indexes yourself. See the [indexing guide](/indexing/) for instructions on building different types of indexes with LanceDB. @@ -111,7 +117,8 @@ for instructions on building different types of indexes with LanceDB. Run a simple scan by projecting relevant columns to get a feel for the dataset. For example, we can run a search without any filters or input parameters to get a small subset of the data: -```python + +```python Python icon="python" rows = ( table.search() .select(["caption", "url", "similarity"]) @@ -124,6 +131,7 @@ for i, row in enumerate(rows, start=1): print(f" url={row['url']}") print(f" similarity={row['similarity']}") ``` + We get the first three rows and their metadata printed out, which look like this: ``` @@ -143,7 +151,8 @@ We get the first three rows and their metadata printed out, which look like this Filtered search is a common pattern to narrow down interesting subsets of the data during early exploration. Here's an example: -```python + +```python Python icon="python" filtered = ( table.search() .where("height > 600") @@ -155,6 +164,7 @@ filtered = ( for row in filtered: print(row["caption"], row["url"], row["width"], row["height"]) ``` + This prints out the metadata for large images with height greater than 600 pixels: ``` @@ -166,7 +176,8 @@ pattern cutting made easy pdf https://i.pinimg.com/736x/7c/6c/a7/7c6ca7361815a89 ## Export image bytes to local files {#export-image-bytes-to-local-files} To work with a subset of the data locally, you can export the image bytes from the table and save them as JPEG files. -```python + +```python Python icon="python" from pathlib import Path sample = ( @@ -185,6 +196,7 @@ for i, row in enumerate(sample): f.write(row["image"]) print(f"Saved {out_path} | caption={row['caption']}") ``` + You can now preview the images you just exported on your local machine to get a better sense of the data. @@ -194,7 +206,8 @@ You can use LanceDB to run vector search directly on the data on the Hub, **with or build your own vector index**. This makes it incredibly easy to explore the dataset and iterate on your search queries before you decide to download a local copy for further experimentation on your end. -```python + +```python Python icon="python" # Pick an arbitrary image embedding from the dataset query_embedding = ( table.search() @@ -213,6 +226,7 @@ results = ( for row in results: print(row["_distance"], row["caption"]) ``` + | distance | caption | | --- | --- | @@ -229,7 +243,8 @@ showing up multiple times in the search results. Run an FTS search query that uses BM25 ranking on the `caption` column (on which we already have an FTS index): -```python + +```python Python icon="python" fts_results = ( table.search("dog running on beach", query_type="fts") .select(["caption", "url", "_score"]) @@ -237,6 +252,7 @@ fts_results = ( .to_list() ) ``` + | caption | url | _score | | --- | --- | --- | @@ -247,41 +263,47 @@ fts_results = ( ## Download the full dataset {#download-the-full-dataset} -You may hit Hugging Face rate limits when streaming large samples from `hf://`, despite using a Hugging Face token. +You may hit HuggingFace rate limits when streaming large samples from `hf://`, despite using a HuggingFace token. For repeated queries or queries that operate on the full dataset, it's recommended to download the dataset locally and query from disk. -Here's how to download the entire dataset via the [Hugging Face CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli): +Here's how to download the entire dataset via the [HuggingFace CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli): -```bash + +```bash Bash icon="terminal" huggingface-cli download lance-format/laion-1m --repo-type dataset --local-dir ./laion-1m ``` + -## Upload your own datasets to Hugging Face in Lance format {#upload-your-own-datasets-to-hugging-face-in-lance-format} +## Upload your own datasets to HuggingFace in Lance format {#upload-your-own-datasets-to-hugging-face-in-lance-format} -This section shows how you can upload your own Lance datasets to the Hugging Face Hub to share with the community. +This section shows how you can upload your own Lance datasets to the HuggingFace Hub to share with the community. -First, install the [Hugging Face CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) and export both `OPENAI_API_KEY` and `HF_TOKEN`. +First, install the [HuggingFace CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) and export both `OPENAI_API_KEY` and `HF_TOKEN`. Then, create a Lance dataset using LanceDB on a local machine, and then proceed to upload it to the Hub via a CLI command. -```bash + +```bash Bash icon="terminal" export OPENAI_API_KEY=... export HF_TOKEN=hf_... hf auth login --token "$HF_TOKEN" ``` + A typical sequence of steps is given below. ### 1\. Upload your local directory to the Hub {#1-upload-your-local-directory-to-the-hub} -Upload the full local directory to a specified repository on the Hugging Face Hub. The command below uploads the contents of your local LanceDB directory at `/path/to/your_local_dir` to a new repository named `your_hf_org/repo_name` under your Hugging Face account. +Upload the full local directory to a specified repository on the HuggingFace Hub. The command below uploads the contents of your local LanceDB directory at `/path/to/your_local_dir` to a new repository named `your_hf_org/repo_name` under your HuggingFace account. -```bash bash icon="code" + +```bash bash icon="terminal" hf upload-large-folder /path/to/your_local_dir your_hf_org/repo_name \ --repo-type dataset \ --revision main ``` + The `upload-large-folder` command is designed for [uploading large datasets](https://huggingface.co/docs/huggingface_hub/en/guides/upload) (potentially terabytes in size) and will handle multipart uploads, retries, and resuming interrupted uploads. @@ -289,17 +311,17 @@ The `upload-large-folder` command is designed for [uploading large datasets](htt ### 2\. Inspect dataset versions {#2-inspect-dataset-versions} -Because you can query your remote dataset directly from Hugging Face with `hf://` URIs in LanceDB, you can easily inspect the dataset versions and updates on the Hub without needing to download the data locally. This is very useful to keep track of changes to the dataset and iterate on your data collection and curation process. +Because you can query your remote dataset directly from HuggingFace with `hf://` URIs in LanceDB, you can easily inspect the dataset versions and updates on the Hub without needing to download the data locally. This is very useful to keep track of changes to the dataset and iterate on your data collection and curation process. + ```python Python icon="python" -import lancedb - db = lancedb.connect("hf://datasets/your_hf_org/repo_name") table = db.open_table("table_name") versions = table.list_versions() print(versions) ``` + This will print out the list of versions available for the dataset on the Hub, along with their metadata such as creation date and description. ### 3\. Add a dataset card {#3-add-a-dataset-card} @@ -309,36 +331,40 @@ This project keeps the source card text in `HF_DATASET_CARD.md`, so you can publ to the dataset there and upload it as `README.md` using the following command on the HF CLI: this requires a regular `hf upload` because it is a single-file upload to a specific target path (a custom commit message can be added if you wish). -```bash + +```bash Bash icon="terminal" hf upload lancedb/magical_kingdom HF_DATASET_CARD.md README.md \ --repo-type dataset \ --commit-message "Update dataset card" ``` + ### 4\. Update the dataset {#4-update-the-dataset} Over time, you may want to add new rows (append) or columns (backfill) to your dataset as your needs evolve. You can make the necessary updates to your local dataset using LanceDB, and then upload the updated version back to the Hub with the same `hf upload-large-folder` command. -```bash bash icon="code" + +```bash bash icon="terminal" hf upload-large-folder /path/to/your_local_dir your_hf_org/repo_name \ --repo-type dataset \ --revision main ``` + The CLI will only upload the new data that has changed since the last upload, avoiding wasted I/O while making it easy to keep your dataset up-to-date on the Hub. -That's it! Your dataset is now updated on the Hub with the new data and schema changes, and other users can query the latest version of the dataset directly from Hugging Face with `hf://` URIs in LanceDB. +That's it! Your dataset is now updated on the Hub with the new data and schema changes, and other users can query the latest version of the dataset directly from HuggingFace with `hf://` URIs in LanceDB. -## Explore more Lance datasets on Hugging Face {#explore-more-lance-datasets-on-hugging-face} +## Explore more Lance datasets on HuggingFace {#explore-more-lance-datasets-on-hugging-face} -The LanceDB team is actively uploading useful and interesting datasets in Lance format to the Hugging Face Hub -under the [lance-format](https://huggingface.co/lance-format) organization. We actively encourage the Hugging Face +The LanceDB team is actively uploading useful and interesting datasets in Lance format to the HuggingFace Hub +under the [lance-format](https://huggingface.co/lance-format) organization. We actively encourage the HuggingFace and LanceDB communities to upload their own Lance datasets to the Hub to share with others! -In the meantime, feel free to check out the Hugging Face Hub to discover more Lance datasets uploaded by the community. +In the meantime, feel free to check out the HuggingFace Hub to discover more Lance datasets uploaded by the community. -Click here to explore the latest trending Lance datasets on 🤗 Hugging Face! +Click here to explore the latest trending Lance datasets on 🤗 HuggingFace! diff --git a/docs/web/integrations/ai/kiln.mdx b/docs/web/integrations/ai/kiln.mdx index 91da617c4..1f51cafa4 100644 --- a/docs/web/integrations/ai/kiln.mdx +++ b/docs/web/integrations/ai/kiln.mdx @@ -15,7 +15,7 @@ Kiln's [app](https://kiln.tech/download) makes it easy to: - Build a RAG pipeline with a simple drag-and-drop interface - [Compare](#find-the-best-rag-pipeline-for-your-use-case) search index options (powered by LanceDB), document extractors, embedding models, and chunking strategies - Create end-to-end [evaluations](https://docs.kiln.tech/docs/evaluations) to determine which search configuration works best for your use case - - Load your data from Kiln into [LanceDB Enterprise](/enterprise) for production use + - Load your data from Kiln into [LanceDB Enterprise](/index#architecture) for production use - Iterate with confidence by evaluating new content, prompts, models, and embeddings in minutes instead of weeks ## Find the Best RAG Pipeline for Your Use Case {#find-the-best-rag-pipeline-for-your-use-case} diff --git a/docs/web/integrations/ai/langchain.mdx b/docs/web/integrations/ai/langchain.mdx index 8d012e01e..c87253169 100644 --- a/docs/web/integrations/ai/langchain.mdx +++ b/docs/web/integrations/ai/langchain.mdx @@ -200,7 +200,7 @@ Maximal marginal relevance optimizes for similarity to query AND diversity among | `fetch_k`| `Optional[int]`| Number of Documents to fetch to pass to MMR algorithm.| `None` | | `lambda_mult` | `float` | Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. | `0.5` | | `filter`| `Optional[Dict[str, str]]`| Filter by metadata. | `None` | -|`kwargs`| Other keyworded arguments provided by the user. |-| +| `kwargs` | `Any` | Other keyworded arguments provided by the user. | N/A | Similarly, `max_marginal_relevance_search_by_vector()` function returns docs most similar to the embedding passed to the function using MMR. instead of a string query you need to pass the embedding to be searched for. diff --git a/docs/web/integrations/ai/synthetic-data-kit.mdx b/docs/web/integrations/ai/synthetic-data-kit.mdx index 18b90674a..7c1ac7168 100644 --- a/docs/web/integrations/ai/synthetic-data-kit.mdx +++ b/docs/web/integrations/ai/synthetic-data-kit.mdx @@ -16,7 +16,7 @@ One of the key features of the `synthetic-data-kit` is its use of the Lance form * **Data Ingestion:** The toolkit can ingest various file formats, including PDF, HTML, YouTube transcripts, DOCX, PPT, and TXT. * **Fine-tuning Format Creation:** It can create different fine-tuning formats, such as question-answer (QA) pairs, QA pairs with Chain-of-Thought (CoT), and summarization formats. * **Data Curation:** The tool uses Llama as a judge to curate high-quality examples, ensuring the quality of the generated dataset. -* **Flexible Saving Options:** You can save the generated datasets in various formats compatible with your fine-tuning workflow, including Hugging Face, JSONL, and JSON. +* **Flexible Saving Options:** You can save the generated datasets in various formats compatible with your fine-tuning workflow, including HuggingFace, JSONL, and JSON. ### How it Works: {#how-it-works} @@ -35,40 +35,47 @@ Here is an example of the end-to-end workflow: 1. **Ingest Data into a LanceDB dataset** - This command takes a directory of source files and creates a LanceDB dataset from them. + This command reads a source document and creates a Lance dataset from it. - ```bash + + ```bash Bash icon="terminal" synthetic-data-kit ingest docs/report.pdf --multimodal # This will create a Lance dataset at data/parsed/report.lance # with 'text' and 'image' columns. - - #Generate multimodal-qa pairs from the ingested data - synthetic-data-kit create data/parsed/report.lance --type multimodal-qa ``` + 2. **Create fine-tuning data** - This command uses the LanceDB dataset created in the previous step to generate synthetic data in the desired format. + This command uses the Lance dataset created in the previous step to generate multimodal question-answer pairs. - ```bash - synthetic_data create data/parsed/report.lance + + ```bash Bash icon="terminal" + synthetic-data-kit create data/parsed/report.lance --type multimodal-qa + # This writes data/generated/report.json ``` + 3. **Curate the data** This step uses a language model to curate the generated data and ensure its quality. - ```bash - synthetic_data curate report.json + + ```bash Bash icon="terminal" + synthetic-data-kit curate data/generated/report.json + # This writes data/curated/report_cleaned.json ``` + 4. **Save the final dataset** - Finally, save the curated data to a file in the desired format. + Finally, save the curated data in the format you need: `jsonl`, `alpaca`, `ft` or `chatml`. - ```bash - synthetic_data save-as report.json --save_path ./my_finetuning_data.jsonl + + ```bash Bash icon="terminal" + synthetic-data-kit save-as data/curated/report_cleaned.json -f jsonl -o ./my_finetuning_data.jsonl ``` + This workflow allows you to go from a collection of documents to a high-quality, fine-tuning dataset with just a few commands. The use of LanceDB in the background makes the process efficient and scalable. @@ -77,5 +84,3 @@ This workflow allows you to go from a collection of documents to a high-quality, To get started with the synthetic-data-kit, you can clone the [GitHub Repository](https://github.com/meta-llama/synthetic-data-kit) and install the necessary dependencies. > **Note:** You will also need access to a Llama model, either running locally or via a hosted API. - - diff --git a/docs/web/integrations/ai/vscode.mdx b/docs/web/integrations/ai/vscode.mdx index 4c9319dd5..61d6e6f3b 100644 --- a/docs/web/integrations/ai/vscode.mdx +++ b/docs/web/integrations/ai/vscode.mdx @@ -48,15 +48,19 @@ workspace and searches them by meaning, using a local embedding model, so no API Use the official generator. Choose **New Extension (TypeScript)** and **esbuild** as the bundler. -```bash + +```bash Bash icon="terminal" npx --package yo --package generator-code -- yo code ``` + -```bash + +```bash Bash icon="terminal" npm install @lancedb/lancedb apache-arrow@18.1.0 ``` + Your code imports Arrow types directly, so add `apache-arrow` as a dependency, pinned inside LanceDB's peer dependency range (`>=15.0.0 <=18.1.0`). If the project already depends on a @@ -215,7 +219,8 @@ bundle native binaries, so building with LanceDB fails with `No loader is configured for ".node" files`. Mark the packages that load native code as external so they're loaded from `node_modules` at runtime: -```js esbuild.js icon="square-js" + +```javascript esbuild.js icon="square-js" external: [ "vscode", "@lancedb/lancedb", @@ -224,6 +229,7 @@ external: [ "apache-arrow", ], ``` + External packages must be in the VSIX, but the template's `.vscodeignore` excludes `node_modules/**`. Delete that line. `vsce` then includes your production dependencies and @@ -237,9 +243,11 @@ npm installs LanceDB's native binary only for the machine it runs on, such as `@lancedb/lancedb-win32-x64-msvc` on 64-bit Windows. Build one VSIX per platform, each on a matching machine or CI runner, and publish them all. The Marketplace serves each user the right one. -```bash + +```bash Bash icon="terminal" npx @vscode/vsce package --target win32-x64 ``` + | `vsce` target | LanceDB native package | |:--|:--| diff --git a/docs/web/integrations/data/dlt.mdx b/docs/web/integrations/data/dlt.mdx index f5ede936b..6dd6712da 100644 --- a/docs/web/integrations/data/dlt.mdx +++ b/docs/web/integrations/data/dlt.mdx @@ -17,14 +17,18 @@ import { In this example, we will be fetching movie information from the [Open Movie Database (OMDb) API](https://www.omdbapi.com/) and loading it into a local LanceDB instance. To implement it, you will need an API key for the OMDb API (which can be created freely [here](https://www.omdbapi.com/apikey.aspx)). 1. **Install `dlt` with LanceDB extras:** - ```sh + + ```bash Bash icon="terminal" pip install dlt[lancedb] ``` + 2. **Inside an empty directory, initialize a `dlt` project with:** - ```sh + + ```bash Bash icon="terminal" dlt init rest_api lancedb ``` + This will add all the files necessary to create a `dlt` pipeline that can ingest data from any REST API (ex: OMDb API) and load into LanceDB. ```text ├── .dlt @@ -45,7 +49,7 @@ In this example, we will be fetching movie information from the [Open Movie Data dlt's LanceDB integration also allows you to automatically embed the data during ingestion. Depending on the embedding model chosen, you may need to paste the necessary credentials inside `.dlt/secrets.toml`: ```toml [sources.rest_api] - api_key = "api_key" # Enter the API key for the OMDb API + api_token = "api_token" # Enter the API key for the OMDb API [destination.lancedb] embedding_model_provider = "sentence-transformers" @@ -79,19 +83,25 @@ In this example, we will be fetching movie information from the [Open Movie Data This will use the embedding model specified inside `.dlt/secrets.toml` to embed the field `"Title"`. 5. **Install necessary dependencies:** - ```sh + + ```bash Bash icon="terminal" pip install -r requirements.txt - ``` + ``` + Note: You may need to install the dependencies for your embedding models separately. - ```sh + + ```bash Bash icon="terminal" pip install sentence-transformers ``` + 6. **Run the pipeline:** Finally, running the following command will ingest the data into your LanceDB instance. - ```sh - python custom_source.py + + ```bash Bash icon="terminal" + python rest_api_pipeline.py ``` + For more information and advanced usage of dlt's LanceDB integration, read [the dlt documentation](https://dlthub.com/docs/dlt-ecosystem/destinations/lancedb). diff --git a/docs/web/integrations/data/duckdb.mdx b/docs/web/integrations/data/duckdb.mdx index 25c982b90..f49bf961e 100644 --- a/docs/web/integrations/data/duckdb.mdx +++ b/docs/web/integrations/data/duckdb.mdx @@ -15,18 +15,22 @@ Install the DuckDB CLI as per [their docs](https://duckdb.org/install) and alter Then, open the DuckDB CLI and install and load the Lance extension as follows: + ```sql SQL icon="database" INSTALL lance; LOAD lance; ``` + ## Attach the directory namespace in DuckDB {#attach-the-directory-namespace-in-duckdb} Attach the LanceDB root directory as a Lance namespace: + ```sql SQL icon="database" ATTACH './local_lancedb' AS lance_ns (TYPE LANCE); ``` + In this page, tables are referenced using `lance_ns.main.`, so the table path is `lance_ns.main.lance_duck`. @@ -34,6 +38,7 @@ In this page, tables are referenced using `lance_ns.main.`, so the t Create the `lance_duck` table using SQL and populate it with sample data: + ```sql SQL icon="database" CREATE OR REPLACE TABLE lance_ns.main.lance_duck AS SELECT * @@ -44,6 +49,7 @@ FROM ( ('dragon', 'roar', [0.5, 0.2, 0.7]::FLOAT[]) ) AS t(animal, noise, vector); ``` + This table is the source of truth for all DuckDB queries below. @@ -54,14 +60,17 @@ Python as well, using LanceDB and DuckDB's Python clients in your application co ## Query the table with SQL {#query-the-table-with-sql} + ```sql SQL icon="database" SELECT * FROM lance_ns.main.lance_duck LIMIT 5; ``` + ## Vector search {#vector-search} + ```sql SQL icon="database" SELECT animal, noise, vector, _distance FROM lance_vector_search( @@ -73,9 +82,11 @@ SELECT animal, noise, vector, _distance ) ORDER BY _distance ASC; ``` + ## Full-text search {#full-text-search} + ```sql SQL icon="database" SELECT animal, noise, vector, _score FROM lance_fts( @@ -87,9 +98,11 @@ SELECT animal, noise, vector, _score ) ORDER BY _score DESC; ``` + ## Hybrid search {#hybrid-search} + ```sql SQL icon="database" SELECT animal, noise, vector, _hybrid_score, _distance, _score FROM lance_hybrid_search( @@ -105,12 +118,15 @@ SELECT animal, noise, vector, _hybrid_score, _distance, _score ) ORDER BY _hybrid_score DESC; ``` + ## Directory namespace model {#directory-namespace-model} -A directory namespace maps a LanceDB catalog root to namespace-qualified table identifiers in DuckDB. This keeps table discovery and table naming stable as your project grows. +A directory namespace maps a LanceDB namespace root -- there's no catalog in +Embedded -- to namespace-qualified table identifiers in DuckDB. This keeps +table discovery and table naming stable as your project grows. -To learn more about the catalog and namespace model, see [Namespaces and the Catalog Model](/management/namespace). +To learn more about the namespace and catalog model, see [Namespaces and the Catalog Model](/management/namespace). ## Advanced usage {#advanced-usage} diff --git a/docs/web/integrations/data/voxel51.mdx b/docs/web/integrations/data/voxel51.mdx index a04cd0c3e..30fc4728d 100644 --- a/docs/web/integrations/data/voxel51.mdx +++ b/docs/web/integrations/data/voxel51.mdx @@ -105,8 +105,9 @@ Make sure you install torch ([guide here](https://pytorch.org/get-started/locall {PyPlatformsVoxel51ComputeSimilarity} -!!! note - Running the code above will download the clip model (2.6Gb) + +Running the code above downloads the CLIP model (2.6 GB). + Once the similarity index has been generated, we can query our data in FiftyOne by specifying the `brain_key`: diff --git a/docs/web/integrations/embedding/aws.mdx b/docs/web/integrations/embedding/aws.mdx index 4e1c4fb90..e23df6b27 100644 --- a/docs/web/integrations/embedding/aws.mdx +++ b/docs/web/integrations/embedding/aws.mdx @@ -7,14 +7,18 @@ import { PyEmbeddingAwsUsage } from '/snippets/integrations.mdx'; AWS Bedrock supports multiple base models for generating text embeddings. You need to setup the AWS credentials to use this embedding function. You can do so by using `awscli` and also add your session_token: -```shell + +```bash Bash icon="terminal" aws configure aws configure set aws_session_token "" ``` + to ensure that the credentials are set up correctly, you can run the following command: -```shell + +```bash Bash icon="terminal" aws sts get-caller-identity ``` + Supported Embedding modelIDs are: * `amazon.titan-embed-text-v1` diff --git a/docs/web/integrations/embedding/cohere.mdx b/docs/web/integrations/embedding/cohere.mdx index 3c56fec76..f4f0d8722 100644 --- a/docs/web/integrations/embedding/cohere.mdx +++ b/docs/web/integrations/embedding/cohere.mdx @@ -8,9 +8,11 @@ import { PyEmbeddingCohereUsage } from '/snippets/integrations.mdx'; Using cohere API requires cohere package, which can be installed using `pip install cohere`. Cohere embeddings are used to generate embeddings for text data. The embeddings can be used for various tasks like semantic search, clustering, and classification. You also need to set the `COHERE_API_KEY` environment variable to use the Cohere API. -```shell + +```bash Bash icon="terminal" export COHERE_API_KEY="your-api-key" ``` + Supported models are: @@ -37,18 +39,13 @@ Supported parameters (to be passed in `create` method) are: Cohere supports following input types: -| Input Type | Description | -|-------------------------|---------------------------------------| -| "`search_document`" | Used for embeddings stored in a vector| -| | database for search use-cases. | -| "`search_query`" | Used for embeddings of search queries | -| | run against a vector DB | -| "`semantic_similarity`" | Specifies the given text will be used | -| | for Semantic Textual Similarity (STS) | -| "`classification`" | Used for embeddings passed through a | -| | text classifier. | -| "`clustering`" | Used for the embeddings run through a | -| | clustering algorithm | +| Input type | Description | +| --- | --- | +| `search_document` | Used for embeddings stored in a vector database for search use cases. | +| `search_query` | Used for embeddings of search queries run against a vector database. | +| `semantic_similarity` | Specifies that the text will be used for semantic textual similarity (STS). | +| `classification` | Used for embeddings passed through a text classifier. | +| `clustering` | Used for embeddings run through a clustering algorithm. | Usage Example: diff --git a/docs/web/integrations/embedding/gemini.mdx b/docs/web/integrations/embedding/gemini.mdx index e3359ec0d..532969122 100644 --- a/docs/web/integrations/embedding/gemini.mdx +++ b/docs/web/integrations/embedding/gemini.mdx @@ -10,11 +10,11 @@ The Gemini Embedding Model API supports various task types: | Task Type | Description | |-------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------| -| "`retrieval_query`" | Specifies the given text is a query in a search/retrieval setting. | -| "`retrieval_document`" | Specifies the given text is a document in a search/retrieval setting. Using this task type requires a title but is automatically provided by Embeddings API | -| "`semantic_similarity`" | Specifies the given text will be used for Semantic Textual Similarity (STS). | -| "`classification`" | Specifies that the embeddings will be used for classification. | -| "`clustering`" | Specifies that the embeddings will be used for clustering. | +| `retrieval_query` | Specifies the given text is a query in a search/retrieval setting. | +| `retrieval_document` | Specifies the given text is a document in a search/retrieval setting. Using this task type requires a title but is automatically provided by Embeddings API | +| `semantic_similarity` | Specifies the given text will be used for Semantic Textual Similarity (STS). | +| `classification` | Specifies that the embeddings will be used for classification. | +| `clustering` | Specifies that the embeddings will be used for clustering. | Usage Example: diff --git a/docs/web/integrations/embedding/huggingface.mdx b/docs/web/integrations/embedding/huggingface.mdx index c62ba03ac..1995390ba 100644 --- a/docs/web/integrations/embedding/huggingface.mdx +++ b/docs/web/integrations/embedding/huggingface.mdx @@ -1,11 +1,11 @@ --- -title: Hugging Face -sidebarTitle: Hugging Face +title: HuggingFace +sidebarTitle: HuggingFace --- import { PyEmbeddingHuggingfaceUsage } from '/snippets/integrations.mdx'; -We offer support for all Hugging Face models (which can be loaded via [transformers](https://huggingface.co/docs/transformers/en/index) library). The default model is `colbert-ir/colbertv2.0` which also has its own special callout - `registry.get("colbert")`. Some Hugging Face models might require custom models defined on the Hugging Face Hub in their own modeling files. You may enable this by setting `trust_remote_code=True`. This option should only be set to True for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. Pin `revision` to a commit hash, and note that tables using such a model need it approved with `get_registry().allow_remote_code(...)` when opened in a new process. See [Trusting remote code and custom endpoints](/embedding#trusting-remote-code-and-custom-endpoints). +We offer support for all HuggingFace models (which can be loaded via [transformers](https://huggingface.co/docs/transformers/en/index) library). The default model is `colbert-ir/colbertv2.0` which also has its own special callout - `registry.get("colbert")`. Some HuggingFace models might require custom models defined on the HuggingFace Hub in their own modeling files. You may enable this by setting `trust_remote_code=True`. This option should only be set to True for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. Pin `revision` to a commit hash, and note that tables using such a model need it approved with `get_registry().allow_remote_code(...)` when opened in a new process. See [Trusting remote code and custom endpoints](/embedding#trusting-remote-code-and-custom-endpoints). Example usage: diff --git a/docs/web/integrations/embedding/ibm.mdx b/docs/web/integrations/embedding/ibm.mdx index 6dd3d57e3..b2a2b4d61 100644 --- a/docs/web/integrations/embedding/ibm.mdx +++ b/docs/web/integrations/embedding/ibm.mdx @@ -17,10 +17,9 @@ You can find a list of supported models at [IBM watsonx.ai Documentation](https: | `ibm/slate-125m-english-rtrvr-v2` | 768 | | `ibm/slate-30m-english-rtrvr-v2` | 384 | | `intfloat/multilingual-e5-large` | 1024 | -| `sentence-transformers/all-minilm-l6-v2` | 384 | -For new tables, `ibm/granite-embedding-278m-multilingual` is the recommended default. Older model IDs (such as `ibm/slate-125m-english-rtrvr` and `sentence-transformers/all-minilm-l12-v2`) remain resolvable for tables whose stored metadata references them, but they are no longer advertised for new use. +For new tables, pass `name="ibm/granite-embedding-278m-multilingual"`. The default `name` is still the legacy `ibm/slate-125m-english-rtrvr`, so tables created with it reload with the same model. Legacy and deprecated IDs (such as `ibm/slate-125m-english-rtrvr`, `sentence-transformers/all-minilm-l6-v2` and `sentence-transformers/all-minilm-l12-v2`) still work for tables whose stored metadata references them, but they aren't listed above for new use. ## Parameters {#parameters} @@ -50,12 +49,14 @@ pip install ibm-watsonx-ai Optionally set environment variables (if not passing credentials to `create` directly): -```sh + +```bash Bash icon="terminal" export WATSONX_API_KEY="YOUR_WATSONX_API_KEY" # Provide exactly one of the following: export WATSONX_PROJECT_ID="YOUR_WATSONX_PROJECT_ID" # export WATSONX_SPACE_ID="YOUR_WATSONX_SPACE_ID" ``` + Replace the credential placeholders with your provider credentials. The registry variable keeps the API key out of stored embedding configuration. In application diff --git a/docs/web/integrations/embedding/nvidia.mdx b/docs/web/integrations/embedding/nvidia.mdx index c0664684a..793b36edb 100644 --- a/docs/web/integrations/embedding/nvidia.mdx +++ b/docs/web/integrations/embedding/nvidia.mdx @@ -13,13 +13,15 @@ Image and combined text/image inputs are not supported by this integration. Install the optional client and set your NVIDIA API key: -```shell + +```bash Bash icon="terminal" pip install openai export NVIDIA_API_KEY="your-api-key" ``` + -```python -import lancedb + +```python Python icon="python" from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector @@ -36,6 +38,7 @@ table = db.create_table("documents", schema=Document) table.add([{"text": "Paris is the capital of France."}]) results = table.search("What is the capital of France?").limit(3).to_list() ``` + For a LanceDB Enterprise table, connect as usual, for example `lancedb.connect("db://my-database", api_key=..., region=...)`. The same schema, @@ -72,13 +75,17 @@ served profile. This provider batches by item count, not token count. Set `name` to the exact ID returned by your deployment's `GET /v1/models` and `dim` to an output dimension that deployment supports: -```python + +```python Python icon="python" func = get_registry().get("nvidia").create( name="nvidia/Nemotron-3.5-Embed-1B-BF16", base_url="http://localhost:8000/v1", dim=2048, ) ``` + + +### Authenticated endpoints {#authenticated-endpoints} Custom endpoints may run without a key. `NVIDIA_API_KEY` is only sent to the hosted API, so for authenticated endpoints use @@ -87,20 +94,21 @@ stored in the schema. Restore registry variables in each process. Before using a custom endpoint restored from table metadata in a new process, call `get_registry().allow_endpoint("http://localhost:8000/v1")`. +### Output dimensions {#output-dimensions} + The NIM 2.4 support matrix lists `nvidia/Nemotron-3.5-Embed-8B-BF16` at 2048 dimensions, whereas the hosted 8B reference specifies 4096. For self-hosted model IDs, this provider requires an explicit `dim` and checks the response instead of assuming the hosted defaults. -SDK coverage: Python. TypeScript, Rust, and Java do not gain a NVIDIA provider -from this integration. Automated tests use mocked NVIDIA and Enterprise HTTP -responses plus real local tables. The opt-in hosted smoke test runs with -`NVIDIA_API_KEY` and `pytest python/tests/test_nvidia_embeddings.py -m slow -k nvidia_live` -from the repository's Python environment. It sends five small requests per model -(ten total), with retries disabled, to check local ingestion, reopening, search, -and reduced-dimensional embeddings. +## SDK support {#sdk-support} -NVIDIA references (checked October 23, 2026): +The NVIDIA provider is available in the Python SDK only. TypeScript, Rust and Java +don't have an NVIDIA embedding provider. + +## References {#references} + +NVIDIA documentation: [hosted 1B API](https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3_5-embed-1b-infer), [hosted 8B API](https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3_5-embed-8b-infer), [NIM request/response format](https://docs.nvidia.com/nim/nemo-retriever/embedding/2.4/use-the-api-openai.html), diff --git a/docs/web/integrations/embedding/openai.mdx b/docs/web/integrations/embedding/openai.mdx index fbfa62d9d..9160d961d 100644 --- a/docs/web/integrations/embedding/openai.mdx +++ b/docs/web/integrations/embedding/openai.mdx @@ -10,14 +10,16 @@ LanceDB registers the OpenAI embeddings function in the registry by default, as | Parameter | Type | Default Value | Description | |---|---|---|---| | `name` | `str` | `"text-embedding-ada-002"` | The name of the model. | -| `dim` | `int` | Model default | Requested output dimensions for models that support shortening embeddings. Use `func.ndims()` when defining the vector field. | +| `dim` | `int` | Model default | Requested output dimensions for models that support shortening embeddings. Required for model names other than the OpenAI ones listed by `model_names()` (for example a model served behind an OpenAI-compatible `base_url`), where it is the model's embedding dimension. Use `func.ndims()` when defining the vector field. | | `use_azure` | bool | `False` | Set true to use Azure OpenAI SDK | Set your OpenAI API key before running the example: -```shell + +```bash Bash icon="terminal" export OPENAI_API_KEY="your-api-key" ``` + diff --git a/docs/web/integrations/embedding/sentence-transformers.mdx b/docs/web/integrations/embedding/sentence-transformers.mdx index 0096d11ab..39e714c2c 100644 --- a/docs/web/integrations/embedding/sentence-transformers.mdx +++ b/docs/web/integrations/embedding/sentence-transformers.mdx @@ -12,7 +12,7 @@ Sentence transformer embeddings are normalized by default. It is recommended to -Setting `trust_remote_code=True` allows the model to execute arbitrary code from its Hugging Face repository during loading. Only enable it for repositories you trust, and pin `revision` to a commit hash. When a table using such a model is opened in a new process, the model must be approved with `get_registry().allow_remote_code(...)`. See [Trusting remote code and custom endpoints](/embedding#trusting-remote-code-and-custom-endpoints). +Setting `trust_remote_code=True` allows the model to execute arbitrary code from its HuggingFace repository during loading. Only enable it for repositories you trust, and pin `revision` to a commit hash. When a table using such a model is opened in a new process, the model must be approved with `get_registry().allow_remote_code(...)`. See [Trusting remote code and custom endpoints](/embedding#trusting-remote-code-and-custom-endpoints). | Parameter | Type | Default Value | Description | @@ -20,7 +20,7 @@ Setting `trust_remote_code=True` allows the model to execute arbitrary code from | `name` | `str` | `all-MiniLM-L6-v2` | The name of the model | | `device` | `str` | `cpu` | The device to run the model on (can be `cpu` or `gpu`) | | `normalize` | `bool` | `True` | Whether to normalize the input text before feeding it to the model | -| `trust_remote_code` | `bool` | `False` | Whether to trust and execute remote code from the model's Hugging Face repository | +| `trust_remote_code` | `bool` | `False` | Whether to trust and execute remote code from the model's HuggingFace repository | | `revision` | `str` | `None` | The model revision to load, such as a commit hash | @@ -158,7 +158,7 @@ You can also load many other model architectures from the library. For example m -Here is an example that uses the BAAI embedding model from the Hugging Face Hub [supported models](https://huggingface.co/models?library=sentence-transformers). +Here is an example that uses the BAAI embedding model from the HuggingFace Hub [supported models](https://huggingface.co/models?library=sentence-transformers). @@ -166,5 +166,5 @@ Here is an example that uses the BAAI embedding model from the Hugging Face Hub -Visit the sentence-transformers [Hugging Face Hub](https://huggingface.co/sentence-transformers) page for more information on the available models. +Visit the sentence-transformers [HuggingFace Hub](https://huggingface.co/sentence-transformers) page for more information on the available models. diff --git a/docs/web/integrations/embedding/superlinked.mdx b/docs/web/integrations/embedding/superlinked.mdx index bb2768d74..92ed491d4 100644 --- a/docs/web/integrations/embedding/superlinked.mdx +++ b/docs/web/integrations/embedding/superlinked.mdx @@ -8,11 +8,11 @@ sidebarTitle: Superlinked ## Installation {#installation} -```bash Python icon=Python +```bash Python icon="python" pip install sie-lancedb ``` -```bash TypeScript icon=js +```bash TypeScript icon="square-js" npm install @superlinked/sie-lancedb @lancedb/lancedb ``` @@ -35,11 +35,11 @@ Supported parameters on `.create()`: ## Usage {#usage} -```py Python icon=Python + +```python Python icon="python" import tempfile from pathlib import Path -import lancedb from lancedb.embeddings import get_registry from lancedb.pydantic import LanceModel, Vector import sie_lancedb # registers "sie" and "sie-multivector" @@ -65,6 +65,7 @@ table.add([ results = table.search("What is deep learning?").limit(3).to_list() ``` + LanceDB handles embedding generation for both inserts and queries automatically, based on the `SourceField` / `VectorField` declarations on the schema. The `id` column gives each document a stable key, which [entity extraction](#entity-extraction) uses to merge its results back. @@ -72,7 +73,8 @@ LanceDB handles embedding generation for both inserts and queries automatically, `SIEReranker` plugs into LanceDB's hybrid search pipeline. It uses SIE's cross-encoder `score()` to rerank combined vector + full-text search results. You need a full-text search index on the column first: -```py Python icon=Python + +```python Python icon="python" from sie_lancedb import SIEReranker # Create FTS index for hybrid search @@ -88,13 +90,15 @@ results = ( for r in results: print(f"{r['_relevance_score']:.3f} {r['text']}") ``` + The reranker also works with pure vector or pure FTS search via `.rerank()`. ## ColBERT and multivector {#colbert-and-multivector} `SIEMultiVectorEmbeddingFunction` (registered as `"sie-multivector"`) works with LanceDB's native `MultiVector` type and MaxSim scoring for ColBERT and ColPali models. In LanceDB Python 0.40.0, a multivector that LanceDB generates on insert is stored as null unless the document's token count happens to equal the per-token dimension, so this example computes the document multivectors with `compute_source_embeddings()` and passes them in the `vector` column. LanceDB still generates the query multivector automatically: -```py Python icon=Python + +```python Python icon="python" from lancedb.pydantic import MultiVector sie_colbert = get_registry().get("sie-multivector").create( @@ -116,12 +120,14 @@ table.add([{"text": text, "vector": vector} for text, vector in zip(texts, vecto # MaxSim search - query and document multivectors compared token-by-token results = table.search("What is ML?").limit(5).to_list() ``` + ## Entity extraction {#entity-extraction} `SIEExtractor` adds entity extraction to LanceDB's data-enrichment workflows. Extract entities from a text column and merge the results back as a structured Arrow column - enabling filtered search on extracted entities. This example enriches the `docs` table from [Usage](#usage), matching rows on its `id` column: -```py Python icon=Python + +```python Python icon="python" from sie_lancedb import SIEExtractor extractor = SIEExtractor( @@ -138,6 +144,7 @@ extractor.enrich_table( id_column="id", ) ``` + The `entities` column stores structured Arrow data (`list>`), so you can filter on extracted entities in queries. diff --git a/docs/web/integrations/embedding/voyageai.mdx b/docs/web/integrations/embedding/voyageai.mdx index 957ab2b4d..94ec0a245 100644 --- a/docs/web/integrations/embedding/voyageai.mdx +++ b/docs/web/integrations/embedding/voyageai.mdx @@ -11,9 +11,11 @@ Voyage AI provides cutting-edge embedding and rerankers. Using voyageai API requires voyageai package, which can be installed using `pip install voyageai`. Voyage AI embeddings are used to generate embeddings for text data. The embeddings can be used for various tasks like semantic search, clustering, and classification. You also need to set the `VOYAGE_API_KEY` environment variable to use the Voyage AI API. -```shell + +```bash Bash icon="terminal" export VOYAGE_API_KEY="your-api-key" ``` + Supported models are: diff --git a/docs/web/integrations/index.mdx b/docs/web/integrations/index.mdx index 640628684..96af43120 100644 --- a/docs/web/integrations/index.mdx +++ b/docs/web/integrations/index.mdx @@ -10,7 +10,7 @@ below to jump straight into the guides that matter for your workflow. | Group | Description | |:----------------|:-------------| -| [Embedding models](/integrations/embedding/) | Connect with popular embedding model providers including OpenAI, Cohere, Hugging Face, and more | +| [Embedding models](/integrations/embedding/) | Connect with popular embedding model providers including OpenAI, Cohere, HuggingFace, and more | | [Reranking models](/integrations/reranking/) | Enhance search results with advanced reranking models and techniques | | [AI platforms & frameworks](/integrations/ai/) | Integrate with LangChain, LlamaIndex, Kiln, and other AI development frameworks | | [Data platforms & frameworks](/integrations/data/) | Integrate LanceDB with popular data tools and platforms like DuckDB, Pydantic and dlt | diff --git a/docs/web/integrations/lerobotdataset.mdx b/docs/web/integrations/lerobotdataset.mdx index 260921034..4d5df0786 100644 --- a/docs/web/integrations/lerobotdataset.mdx +++ b/docs/web/integrations/lerobotdataset.mdx @@ -7,12 +7,11 @@ keywords: ["lerobot", "robotics", "droid", "training", "dataloader"] import { PyFrameworksLerobotFilterFrames, - PyFrameworksLerobotLoad, + PyFrameworksLerobotLancedbDataset, PyFrameworksLerobotOpenLanceTables, - PyFrameworksLerobotTrainReady, } from '/snippets/integrations.mdx'; -[LeRobot](https://huggingface.co/docs/lerobot/index) is Hugging Face's open-source robotics stack. Since [lerobot#4363](https://github.com/huggingface/lerobot/pull/4363) it reads Lance datasets natively: same `LeRobotDataset` class, same items, same training pipeline. The dataset's `"storage_format": "lance"` picks the reader. No subclasses, no wrapper library. +[LeRobot](https://huggingface.co/docs/lerobot/index) is HuggingFace's open-source robotics stack. Since [lerobot#4363](https://github.com/huggingface/lerobot/pull/4363) it reads Lance datasets natively, and `lerobot-lancedb` wraps that into a ready-made dataset class for video features: same items, same training pipeline. Image-backed features are not supported -- re-encode them as video first. What you get: @@ -46,18 +45,22 @@ Same model, same loss, 33 minutes sooner, and no 384 GB download first. The diff ## Install -```bash + +```bash Bash icon="terminal" pip install "lerobot[lancedb]" # the reader, inside lerobot itself pip install lerobot-lancedb # the converter ``` + ## Convert a dataset Any LeRobot v3.0 dataset, from the Hub or a local directory: -```bash + +```bash Bash icon="terminal" lerobot-lance-convert --repo-id lerobot/pusht --out ./pusht-lance ``` + **Migration costs about as much as a file copy.** Videos are stored as blobs without re-encoding, so items are bit-identical to the source: 392,578 frames convert in 10 seconds, DROID's 27.6M in 34 minutes. Nothing about your recording or training code changes. The output keeps `meta/` as is and adds three Lance tables (`frames`, `videos`, `meta`). `lerobot-lance-doctor` audits the result and often finds problems in the source: DROID carries 44% orphaned rows, and three of eight public datasets we converted have frame-count defects that only random access exposes. @@ -65,33 +68,40 @@ Host the result anywhere: an HF dataset repo (`hf upload`, tag it `v3.0`), an HF ## Load and train - - {PyFrameworksLerobotLoad} - - -An explicit `root` works for any object store: `LeRobotDataset("lerobot/pusht", root="s3://my-bucket/pusht-lance")`. Remote roots download only `meta/`. Data is fetched per batch. Temporal windows, `DataLoader` and the rest of the training stack work unchanged: +`lerobot-lancedb` provides one map-style dataset class for both image and +video features, reading from a local path or an `s3://`, `gs://` or `hf://` +URI with nothing downloaded up front. Pair it with `lance_mp_context()` so +multi-worker `DataLoader`s share Lance's own multiprocessing context instead +of the default one: - {PyFrameworksLerobotTrainReady} + {PyFrameworksLerobotLancedbDataset} +Items are bit-exact with `LeRobotDataset`, and `delta_timestamps` configures +temporal windows the same way. + Or from the CLI. Held-out evaluation on a remote dataset needs random access, so it only works on the Lance path: -```bash + +```bash Bash icon="terminal" lerobot-train \ --dataset.repo_id=my-org/my-bucket/pusht-lance \ --dataset.repo_type=bucket \ --dataset.eval_split=0.02 \ --policy.type=act ``` + ## Visualize TB-scale datasets in Foxglove LeRobot's dataset viewer can serve an episode to [Foxglove](https://foxglove.dev) over its WebSocket protocol ([lerobot#4542](https://github.com/huggingface/lerobot/pull/4542)), and with a Lance dataset it works wherever the data lives: -```bash + +```bash Bash icon="terminal" lerobot-dataset-viz --repo-id lance-format/pusht-lance --episode-index 3 --display-mode foxglove ``` + Open the Foxglove app, connect to `ws://localhost:8765`, and scrub. Cameras, joint state and actions show up as topics you can lay out however you like: @@ -117,7 +127,8 @@ From here it is standard LanceDB. The examples below are from our DROID walkthro **Feature engineering costs nothing until you use it.** With [Geneva](/geneva/udfs/udfs), `add_columns` registers a `@udf` function and its input columns as a new column and computes nothing; `backfill` computes and stores the values later, in parallel. No copy of the dataset, and the videos are never touched: -```python + +```python Python icon="python" @udf(data_type=pa.float32(), input_columns=["action_joint_velocity"]) def jerk_score(v): # per-frame motion roughness ... @@ -125,18 +136,21 @@ def jerk_score(v): # per-frame motion roughness tbl.add_columns({"jerk_score": jerk_score}) # nothing computed yet tbl.backfill("jerk_score", concurrency=8) # 610,403 rows in 16.7 s ``` + -Embeddings work the same way, reading frames straight from the video blobs in the same table: +Embeddings work the same way, reading frames straight from the video blobs in the `videos` table: -```python + +```python Python icon="python" @udf(data_type=pa.list_(pa.float32(), 768), num_gpus=1, input_columns=["episode_index", "frame_index"]) class EmbedFromBlob: # SigLIP2 loads once per worker def __call__(self, episode_index, frame_index): - blob = self.videos.take_blobs("video_bytes", indices=[vrow])[0] + blob = self.videos.fetch_blob_files("video_bytes", [video_row_id])[0] frame = VideoDecoder(blob).get_frames_at([pos]).data[0] ... ``` + **Deduplication** removes near-static runs before they skew curation or training. A stopped gripper holding one pose for a few seconds produces many @@ -144,12 +158,18 @@ frames whose `emb_siglip2` vectors are nearly identical; LanceDB Enterprise's native [`dedupe`](/sql/dql/dedupe) collapses them into one representative per cluster, directly over the index, without a pairwise scan: -```python + +```python Python icon="python" db.execute_query(""" CREATE MATERIALIZED VIEW frames_deduped AS - SELECT * FROM dedupe('frames', 'emb_siglip2', distance_threshold => 0.01) + SELECT * FROM dedupe( + 'frames', + 'emb_siglip2', + distance_threshold => 0.01 + ) """) ``` + Every column survives the dedup unchanged -- `jerk_score`, the episode and camera metadata, the video blob reference -- since `dedupe` returns full @@ -161,7 +181,8 @@ to keep the deduplicated set current as new episodes land; see **Curation** is one query across all of it. Semantic search with a predicate on the derived score, no join, no second system: -```python + +```python Python icon="python" results = ( tbl.search(vec("a gripper closing on an object"), vector_column_name="emb_siglip2") .where("jerk_score > 1.2875") # the roughest 1% of frames @@ -169,6 +190,7 @@ results = ( .to_arrow() ) ``` + **Mining** is the same query pointed at the rare cases. `tbl.search().where("jerk_score > 1.2875 AND success = false")` pulls the rough, failed frames out of 27.6M rows in milliseconds, ready to become a fine-tuning set or a labeling queue. diff --git a/docs/web/integrations/reranking/answerdotai.mdx b/docs/web/integrations/reranking/answerdotai.mdx index 22814e822..9d2b6f0f6 100644 --- a/docs/web/integrations/reranking/answerdotai.mdx +++ b/docs/web/integrations/reranking/answerdotai.mdx @@ -26,7 +26,7 @@ This integration uses [AnswersDotAI's rerankers](https://github.com/AnswerDotAI/ | `model_type` | `str` | `"colbert"` | The type of model to use. Supported model types can be found here: https://github.com/AnswerDotAI/rerankers. | | `model_name` | `str` | `"answerdotai/answerai-colbert-small-v1"` | The name of the reranker model to use. | | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | -| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | +| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | diff --git a/docs/web/integrations/reranking/cohere.mdx b/docs/web/integrations/reranking/cohere.mdx index bc731b39e..2ab980c3f 100644 --- a/docs/web/integrations/reranking/cohere.mdx +++ b/docs/web/integrations/reranking/cohere.mdx @@ -14,9 +14,11 @@ This reranker uses the [Cohere](https://cohere.ai/) API to rerank the search res > **Note:** Supported query types: Hybrid, Vector, and FTS. -```shell + +```bash Bash icon="terminal" pip install cohere ``` + Replace the credential placeholders with your provider credentials. In application code, load credentials from environment variables or a secrets manager. @@ -33,7 +35,7 @@ Replace the credential placeholders with your provider credentials. In applicati | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `top_n` | `str` | `None` | The number of results to return. If None, will return all results. | | `api_key` | `str` | `None` | The API key for the Cohere API. If not provided, the `COHERE_API_KEY` environment variable is used. | -| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type | +| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type | diff --git a/docs/web/integrations/reranking/colbert.mdx b/docs/web/integrations/reranking/colbert.mdx index ffb3f8d2c..fa369d392 100644 --- a/docs/web/integrations/reranking/colbert.mdx +++ b/docs/web/integrations/reranking/colbert.mdx @@ -25,7 +25,7 @@ This reranker uses ColBERT model to rerank the search results. You can use this | `model_name` | `str` | `"colbert-ir/colbertv2.0"` | The name of the reranker model to use.| | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `device` | `str` | `None` | The device to use for the cross encoder model. If None, will use "cuda" if available, otherwise "cpu". | -| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | +| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | ## Supported Scores for each query type {#supported-scores-for-each-query-type} diff --git a/docs/web/integrations/reranking/jina.mdx b/docs/web/integrations/reranking/jina.mdx index c2b1db6db..bf7f2d4da 100644 --- a/docs/web/integrations/reranking/jina.mdx +++ b/docs/web/integrations/reranking/jina.mdx @@ -30,7 +30,7 @@ Replace the credential placeholders with your provider credentials. In applicati | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `top_n` | `str` | `None` | The number of results to return. If None, will return all results. | | `api_key` | `str` | `None` | The API key for the Jina API. If not provided, the `JINA_API_KEY` environment variable is used. | -| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | +| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | diff --git a/docs/web/integrations/reranking/openai.mdx b/docs/web/integrations/reranking/openai.mdx index 71fe63117..0d7a56de7 100644 --- a/docs/web/integrations/reranking/openai.mdx +++ b/docs/web/integrations/reranking/openai.mdx @@ -9,7 +9,7 @@ import { PyRerankingOpenaiUsage } from '/snippets/provider_examples.mdx'; # OpenAI Reranker (Experimental) -This reranker uses OpenAI chat model to rerank the search results. You can use this reranker by passing `OpenAI()` to the `rerank()` method. +This reranker uses OpenAI chat model to rerank the search results. You can use this reranker by passing `OpenaiReranker()` to the `rerank()` method. > **Note:** Supported query types: Hybrid, Vector, and FTS. > **Warning:** This reranker is experimental. OpenAI does not have a dedicated reranking model, so it uses a chat model under the hood. @@ -28,7 +28,7 @@ credentials from environment variables or a secrets manager. | --- | --- | --- | --- | | `model_name` | `str` | `"gpt-5.6-sol"` | The name of the reranker model to use.| | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | -| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | +| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | | `api_key` | `str` | `None` | The API key to use. If None, will use the OPENAI_API_KEY environment variable. diff --git a/docs/web/integrations/reranking/voyageai.mdx b/docs/web/integrations/reranking/voyageai.mdx index eaf2d83f8..18a59ec94 100644 --- a/docs/web/integrations/reranking/voyageai.mdx +++ b/docs/web/integrations/reranking/voyageai.mdx @@ -33,7 +33,7 @@ credentials from environment variables or a secrets manager. | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `top_n` | `str` | `None` | The number of results to return. If None, will return all results. | | `api_key` | `str` | `None` | The API key for the Voyage AI API. If not provided, the `VOYAGE_API_KEY` environment variable is used. | -| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type | +| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score` column. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type | | `truncation` | `bool` | `None` | Whether to truncate the input to satisfy the "context length limit" on the query and the documents. | diff --git a/docs/web/integrations/reranking/watsonx.mdx b/docs/web/integrations/reranking/watsonx.mdx index 13420ebe6..cc3161562 100644 --- a/docs/web/integrations/reranking/watsonx.mdx +++ b/docs/web/integrations/reranking/watsonx.mdx @@ -13,9 +13,11 @@ This reranker uses the [IBM watsonx.ai](https://cloud.ibm.com/docs/apis/watsonx- > **Note:** Supported query types: Hybrid, Vector, and FTS. -```shell + +```bash Bash icon="terminal" pip install ibm-watsonx-ai ``` + Replace the credential placeholders with your provider credentials. In application code, load credentials from environment variables or a secrets manager. diff --git a/docs/web/integrations/stable-worldmodel.mdx b/docs/web/integrations/stable-worldmodel.mdx index ee35e2159..c42723834 100644 --- a/docs/web/integrations/stable-worldmodel.mdx +++ b/docs/web/integrations/stable-worldmodel.mdx @@ -19,9 +19,11 @@ Random access speed is the bottleneck for world model training, since the loop r ## Install {#install} -```bash + +```bash Bash icon="terminal" pip install stable-worldmodel ``` + Datasets and checkpoints are stored under `$STABLEWM_HOME`, which defaults to `~/.stable_worldmodel/`. diff --git a/docs/web/maintenance/background-jobs.mdx b/docs/web/maintenance/background-jobs.mdx deleted file mode 100644 index 3c2718cfe..000000000 --- a/docs/web/maintenance/background-jobs.mdx +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: "Background jobs" -sidebarTitle: "Background Jobs" -description: "Understand the Enterprise background jobs that maintain tables, indexes and caches." -icon: gears -keywords: ["background jobs", "job type", "wal", "spfresh", "prewarm", "archive"] -availability: - embedded: unavailable - enterprise: available ---- - -The jobs documented elsewhere in these docs ([Build & Repair](/indexing/reindexing), -[Compaction](/maintenance/compaction), [Cleanup](/maintenance/cleanup), -[Refresh Computed Column](/feature-engineering/refresh-column)) start from a call you -make or, for compaction, cleanup and index updates, from the deployment's own -maintenance. This page is the rest: jobs the deployment runs to keep itself -correct and fast, which you may see named in [`SHOW JOBS`](/sql/ddl/job#show) -without having asked for any of them. - -These jobs are configured by the deployment's operators rather than through -the table SDK. If a maintenance job repeatedly fails or stops making progress, -share its job ID and errors with your Enterprise support team. Operators can -also start cache-warming jobs through the admin API. - -## Write-ahead log maintenance {#wal} - -For a table with the [real time engine](/tables/realtime-engine) enabled, two jobs keep the -log from growing without bound: - -| Job type | What it does | -| --- | --- | -| `memwal_compaction` | Folds a table shard's SSTables into the base table by primary key. Distinct from `compact`, which merges base-table fragments. The two are unrelated. | -| `memwal_catchup_` | Extends a base-table index over the rows `memwal_compaction` just folded in, and records how far the index has caught up. Nothing else advances that record. The suffix names the index type, for example `memwal_catchup_btree`, `memwal_catchup_fts`, or `memwal_catchup_ivfpq`. | - -## Index maintenance {#index} - -| Job type | What it does | -| --- | --- | -| `index_remap` | Reassigns index entries after row ids shift underneath an index (the kind of remap a delta compaction can require). | -| `spfresh_merge` | Merges SPFresh-managed segments for indexes that use it. | - -## Cache warming {#cache} - -| Job type | What it does | -| --- | --- | -| `prewarm_page_cache` | Loads table data into a query node's page cache ahead of a request needing it. | -| `prewarm_index_cache` | The same, for index structures. | -| `startup_prewarm_idx` | Runs cache prewarming as part of an executor's own startup, rather than on a schedule, when the deployment enables it. | - -## Registry housekeeping {#registry} - -| Job type | What it does | -| --- | --- | -| `job_registry_archive` | Sweeps terminal jobs out of the active registry and into archival storage, on a per-database schedule. | -| `job_events_export` | Copies terminal jobs' event histories into a curated system table for metering. Registry-scoped, like the archive sweep. | - -These two are why an old job you completed weeks ago no longer shows in -`SHOW JOBS`: it was archived, not deleted. Where the deployment enables the -export, its events also survive in the exported table. - -## Object teardown {#teardown} - -| Job type | What it does | -| --- | --- | -| `drop_object` | Deletes a dropped catalog object's content, then clears it from the database's cleanup backlog. Whether a dropped table runs as this job or as [`drop_table`](/management/table#drop), which fences the table's directory with its own marker instead, depends on how the deployment stores its catalog. | - -You trigger it indirectly, by dropping a table, a [view](/sql/ddl/view#drop) or -a [namespace](/management/namespace); the teardown runs as this job rather than -inline with the call. -{/* Draft for the Functions release: Dropping a [function](/management/function#drop) starts it the same way. */} diff --git a/docs/web/maintenance/cleanup.mdx b/docs/web/maintenance/cleanup.mdx index 365eb66e8..21ba079f9 100644 --- a/docs/web/maintenance/cleanup.mdx +++ b/docs/web/maintenance/cleanup.mdx @@ -1,9 +1,9 @@ --- -title: "Cleanup" -sidebarTitle: "Cleanup" +title: "Garbage Collection" +sidebarTitle: "Garbage Collection" description: "Pruning old versions and the files only they referenced." icon: broom -keywords: ["cleanup", "retention", "prune", "delete_unverified", "vacuum"] +keywords: ["cleanup", "garbage collection", "retention", "prune", "delete_unverified", "vacuum"] availability: embedded: available enterprise: available @@ -23,11 +23,13 @@ deployment's configuration enables it. ## Retention {#retention} -```python + +```python Python icon="python" from datetime import timedelta table.optimize(cleanup_older_than=timedelta(days=30)) ``` + `cleanup_older_than` defaults to **7 days**. Versions older than that are removed, along with the files only they referenced. In LanceDB Enterprise, the @@ -35,7 +37,7 @@ retention period comes from its configuration instead. The latest version is never removed, whatever you pass. `timedelta(0)` makes every older version eligible for removal, but cleanup still keeps tagged -versions and the files branches still read, as the warning below describes. +versions{/* Draft until branching reaches early access: restore " and the files branches still read" */}, as the warning below describes. Pruning is what makes [time travel](/management/table#versioning) finite: an @@ -45,12 +47,18 @@ whatever its age, when it is: - the **latest** version; - a **tagged** version. +{/* +Draft until branching reaches early access. + Cleanup also keeps the files a **branch** still reads, and the version the branch was forked from while the branch's remaining versions read the parent's files. That does not keep the fork for good: once the branch has replaced the data it inherited and its own older versions are pruned, cleanup prunes the -fork version like any other. To keep a version recoverable, tag it, subject to -the policy below, or keep the window wide enough to cover it. +fork version like any other. +*/} + +To keep a version recoverable, tag it, subject to the policy below, or keep +the window wide enough to cover it. Under the default policy, a tag can also stop cleanup. When a tagged version is older than the window and is not the latest, cleanup refuses to run: it raises @@ -73,7 +81,7 @@ need before running this, not after. [Managed blobs](/management/table#managed-blobs) store out-of-line payloads under the table's `_blobs/` directory. Cleanup follows the references from -retained snapshots, including protected tags and branches, before selecting +retained snapshots, including protected tags{/* Draft until branching reaches early access: restore " and branches" */}, before selecting objects for deletion. Replacing a blob or deleting a row makes its old payload eligible only after no retained snapshot references it. @@ -90,7 +98,7 @@ them, and reopen handles created before that upgrade. For LanceDB Embedded tables, `optimize()` performs compaction and cleanup. Enterprise runs these as background jobs; Python tables connected to Enterprise do not support `optimize()`. -See [Background jobs](/maintenance/background-jobs) for the Enterprise path. +See [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance#cleanup) for the Enterprise path. ## Disk usage does not drop immediately {#disk} @@ -101,9 +109,11 @@ versions that referenced the superseded files. If you need to reclaim space aggressively in the embedded library, shorten the retention window rather than waiting for the default: -```python + +```python Python icon="python" table.optimize(cleanup_older_than=timedelta(days=1)) ``` + ## Files from failed transactions {#unverified} @@ -111,9 +121,11 @@ A write that fails partway can leave files that look like an operation still in progress. Cleanup will not remove them until they are at least seven days old, because it cannot tell them apart from a live write. -```python + +```python Python icon="python" table.optimize(delete_unverified=True) ``` + This option belongs to `optimize()` in the embedded library. A deployment's cleanup jobs never set it. @@ -131,7 +143,7 @@ the table. Merging small files, the other half of `optimize()`. - - The Enterprise jobs that run without a call from you. + + How Enterprise decides to run cleanup without a call from you. diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 64f18b095..9c8765293 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -39,17 +39,19 @@ partitions. ## Optimize a table {#what-it-does} -```python + +```python Python icon="python" table.optimize() ``` + Three operations, in one call: | | | | --- | --- | | **Compaction** | merges small files into larger ones | -| **Prune** | removes versions older than the retention window (see [Cleanup](/maintenance/cleanup)) | -| **Index** | folds newly added rows into existing indexes (see [Build & Repair](/indexing/reindexing)) | +| **Prune** | removes versions older than the retention window (see [Garbage Collection](/maintenance/cleanup)) | +| **Index** | folds newly added rows into existing indexes (see [Incremental Indexing](/indexing/incremental-indexing)) | Compaction itself is only the first of the three: merging small fragments back into larger ones, which is what keeps a scan from opening more files than it @@ -91,6 +93,10 @@ Frequent small appends are what make it necessary, because each one commits files. A table written in a few large batches needs it rarely; one taking continuous small writes needs it on a schedule. +Opening a table in LanceDB Embedded logs a warning at most once per table per +process when at least 100 fragments have fewer than 100,000 rows each. Set +`LANCEDB_LOG=warn` to surface this log if your logger hides warnings by default. + Compaction rewrites files, which conflicts with a concurrent [computed-column refresh](/feature-engineering/add-computed-column) or @@ -98,8 +104,8 @@ Compaction rewrites files, which conflicts with a concurrent version it replaces. Sequence them rather than running both at once. -See [Cleanup](/maintenance/cleanup) for pruning old versions, and -[Build & Repair](/indexing/reindexing) for the index-folding half of +See [Garbage Collection](/maintenance/cleanup) for pruning old versions, and +[Incremental Indexing](/indexing/incremental-indexing) for the index-folding half of `optimize()`. ## Performance {#performance} @@ -111,13 +117,15 @@ Two things accumulate on a long-lived table as more and more data gets added to In LanceDB Embedded, you run them yourself via `optimize()`, which bundles both into a single call: + ```python Python icon="python" from datetime import timedelta table.optimize() # 7-day default retention table.optimize(cleanup_older_than=timedelta(days=1)) # reclaim space sooner ``` + -The best practice is to run `optimize()` after large writes or on a schedule. It also bundles incremental index updates. See [Build & Repair](/indexing/reindexing) for the breakdown. Updates also move rows out of the vector index, so they remain searchable but unindexed. Update or rebuild the index after large update batches. +The best practice is to run `optimize()` after large writes or on a schedule. It also bundles incremental index updates. See [Incremental Indexing](/indexing/incremental-indexing) for the breakdown. Updates also move rows out of the vector index, so they remain searchable but unindexed. Update or rebuild the index after large update batches. {/* Draft for the Python compaction_options release. Keep this section unpublished @@ -142,9 +150,10 @@ task at a time can also reduce memory use. The Rust example runs compaction only. Run pruning and index optimization separately when needed; Python's `optimize()` includes those steps. -TypeScript's `optimize()` does not currently expose the fragment row target, -scan batch size, or compaction thread count. These tuning examples apply to -Python and Rust tables in LanceDB Embedded. +TypeScript's `optimize()` exposes the fragment row target through +`compactionOptions.targetRowsPerFragment` and the scanner batch size through +`compactionOptions.batchSize`. Compaction thread count is not exposed. The tuning +examples above use Python and Rust tables in LanceDB Embedded. Planning remains row based. The row target bounds later passes after existing oversized fragments have been rewritten; the first pass rewrites those diff --git a/docs/web/management/catalog.mdx b/docs/web/management/catalog.mdx new file mode 100644 index 000000000..da76c6a87 --- /dev/null +++ b/docs/web/management/catalog.mdx @@ -0,0 +1,67 @@ +--- +title: "Catalog" +sidebarTitle: "Catalog" +description: "The unnamed root of an Enterprise deployment: initial access, the superuser bootstrap, and where privileges apply." +icon: sitemap +keywords: ["catalog", "superuser", "bootstrap", "privileges", "initial access", "root"] +availability: + embedded: unavailable + enterprise: available +--- + +The catalog is the unnamed root of one Enterprise deployment, identified by +its endpoint rather than a name -- see +[Catalog Hierarchy](/basics/catalog#hierarchy) for how it relates to the +databases, namespaces and tables beneath it, and +[Connecting to Catalog](/basics/catalog#connecting-to-catalog) for +`connect_catalog(endpoint)` itself. This page covers what it takes to reach +a brand new deployment for the first time. + +## Initial access {#initial-access} + +A newly deployed catalog has no databases and no grants: nobody yet holds +`CREATE_DATABASE` or any other system-level privilege, so there is nothing +for an ordinary principal to do with a catalog connection. Database +administration starts from a **superuser**. + +## Superuser {#superuser} + +A superuser is an identity your deployment operator configures outside the +normal grant system, not a role anyone can be granted. It bypasses +privilege checks entirely, on every object, rather than holding specific +privileges -- the same way `OWNERSHIP` on an object grants full authority +over that one object, a superuser has it over the whole deployment. + +This is what makes a brand new deployment usable. Creating a database or +namespace can fall back to a system or parent-namespace privilege when the +object has no owner yet -- see +[Creating an object you don't own yet](/governance/privileges#creation) -- +but a system-level privilege itself has no such fallback, so a superuser +signs in first and grants `CREATE_DATABASE`, `OPERATE`, or other system +privileges to real principals and roles. Day-to-day administration then +runs through those grants, the same as any other object; reach for the +superuser identity to recover access or bootstrap a new deployment, not as +a standing way to work. + +## Privileges {#privileges} + +The catalog connection itself is gated by privileges on the `system` +object: `CREATE_DATABASE` to create one, `OPERATE` to manage jobs, caches, +server configuration and role membership, and `USAGE` to list jobs and look +up other identities. See [Privileges](/governance/privileges) for the full +table and how a grant is addressed, and +[Principals](/governance/principals) for who a grant can name. + +## What to read next {#next} + + + + How the catalog relates to databases, namespaces and tables. + + + Every privilege, and the grant and revoke syntax that covers each one. + + + Create and manage a database once you can reach the catalog. + + diff --git a/docs/web/management/database.mdx b/docs/web/management/database.mdx index 6651d6409..88e03211a 100644 --- a/docs/web/management/database.mdx +++ b/docs/web/management/database.mdx @@ -21,7 +21,7 @@ objects, and configure how your application reaches the data. | --- | --- | --- | | `./.lancedb` | LanceDB Embedded, with local storage | In your application | | `s3://bucket/path`, `gs://bucket/path`, `az://container/path` | LanceDB Embedded, with object storage | In your application | -| `db://my-database` | LanceDB Enterprise | On the Enterprise service (LanceDB Distributed) | +| `db://my-database` | LanceDB Enterprise | On the Enterprise service | [Connect to LanceDB](/basics/catalog) has examples for each connection type. A connection to object storage still uses the embedded library: your process @@ -63,8 +63,6 @@ tables created through the connection: ```python Python icon="python" -import lancedb - db = lancedb.connect( "s3://bucket/path", storage_options={"new_table_enable_stable_row_ids": "true"}, @@ -84,7 +82,7 @@ Set stable row IDs before creating a table that needs them, such as an ordinary materialized-view source in Python SDK 0.40.0. The option does not change tables that already exist. Enterprise storage settings are managed on the server. -See [Storage](/deployment/storage) for provider credentials and other options. +See [Object storage](/basics/catalog#object-storage) for provider credentials and other options. ## Read consistency {#consistency} @@ -95,8 +93,6 @@ every five seconds: ```python Python icon="python" from datetime import timedelta -import lancedb - db = lancedb.connect( "./.lancedb", read_consistency_interval=timedelta(seconds=5) ) @@ -145,12 +141,12 @@ and `drop_all_tables()` operations remove all tables without a confirmation prom Python's `connect_async` returns an `AsyncConnection`. Await its operations when working in an asynchronous application: -```python -import lancedb - + +```python Python icon="python" db = await lancedb.connect_async("./.lancedb") table = await db.open_table("documents") ``` + TypeScript's connection and table operations already return promises. @@ -158,3 +154,17 @@ An async connection and a background job serve different purposes. Async APIs let other tasks run while your application waits for an operation. A [job](/basics/jobs) represents work that can continue on the server after the submission call returns. + +## Privileges {#privileges} + +A database's `OWNERSHIP`, `USAGE` and `CREATE_NAMESPACE` are granted through +the REST ACL API or SQL `GRANT`/`REVOKE`: + + +```sql SQL icon="database" +GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE readers +``` + + +See [Privileges](/governance/privileges#sql) for the full statement syntax +and every target it reaches. diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 415de7613..c8fa0626c 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -1,9 +1,13 @@ --- title: "Functions" +tag: "Early access" sidebarTitle: "Function" description: "Register a Python function once and apply it as a column, for work SQL cannot express." icon: code keywords: ["udf", "functions", "create_function", "embedding", "feature engineering"] +availability: + embedded: unavailable + enterprise: available --- import { @@ -15,10 +19,13 @@ import { PyFunctionRefresh as FunctionRefresh, PyFunctionInspect as FunctionInspect, PyFunctionClassDefine as FunctionClassDefine, + PyFunctionClassRegister as FunctionClassRegister, PyFunctionClassApply as FunctionClassApply, } from '/snippets/function.mdx'; import { PyConnectEnterprisePlaceholders as FunctionConnect } from '/snippets/connection.mdx'; +Early access + Some columns cannot be written as a SQL expression: an embedding, a model call, an image decode. A function is a Python callable registered with the database, versioned, and then applied as a column. The code runs where the data is @@ -35,14 +42,14 @@ In SQL, a function is registered with [`CREATE FUNCTION`](/sql/ddl/function#crea Functions are the way to fill columns with Python in LanceDB Enterprise. If you -already use [Geneva](/geneva), it remains available; see -[Geneva and Functions](/geneva#functions) for how its concepts map onto these. +already use [Geneva](/geneva), it remains available; see the Geneva docs for +how its concepts map onto these. The steps below take a column of numbers to a filled column of their doubles. ## Define a function {#define} -`@udf` packages a scalar Python callable. Input and output types are inferred +`@function` packages a scalar Python callable. Input and output types are inferred from annotations, so `double` takes one non-nullable `float64` parameter, `value`, and returns a non-nullable `float64`: @@ -91,7 +98,9 @@ deployment's support before using another computed column as an input. ## Register it {#register} -Registration returns a job; the immutable version exists once the job succeeds. +Registration returns a query-backed job; the immutable version exists once the +SQL command finishes and the job succeeds. Its `job_type` is `query`, and its +single `id` is the SQL query UUID. Repeated waits reuse the completed result. {FunctionRegister} @@ -101,10 +110,56 @@ Registration returns a job; the immutable version exists once the job succeeds. with `db.get_function(name, version=...)`. -**Enterprise job type:** `create_function`. Registration returns a job because -the function is baked into an image before the version becomes usable. +The SQL command submits an internal `create_function` image-build job and +waits for publication. The SDK returns the SQL query handle. Query handles +have no registry history and cannot be reopened with `open_job()`. +## List and describe {#list-describe} + +`list_functions` pages through every published version in a namespace, +ordered by name then version; `get_function` opens one exact version by +name and `version`. Both take `namespace_path`, defaulting to the root +namespace, the same as `create_function`. + + +```python Python icon="python" +for version in db.list_functions(): + print(version.name, version.version, version.created_at_millis) + +version = db.get_function("double", version="1") +``` + +```rust +use futures::TryStreamExt; + +# async fn list_and_get(connection: &lancedb::Connection) -> Result<(), Box> { +let mut versions = connection.list_functions(&[], Default::default()); +while let Some(version) = versions.try_next().await? { + println!("{} {} {}", version.name(), version.version(), version.created_at_millis()); +} + +let version = connection.get_function("double", "1", &[]).await?; +# Ok(()) +# } +``` + + + +```sql SQL icon="database" +SHOW FUNCTIONS +SHOW FUNCTIONS IN "analytics" WITH (name = 'double', limit = 100) + +DESCRIBE FUNCTION double WITH (version = '1') +``` + + +`list_functions` returns a lazy iterator: `page_limit` bounds each request, +not the total, and `page_token` resumes from a saved token. Child namespaces +are not included; list each namespace separately. A version's +`created_at_millis`, `metadata`, `disabled` flag, and `secret_bindings` are +all readable this way without applying or calling the function. + ## Try it in SQL {#try-sql} A registered function is callable in SQL by its name, the same as any other @@ -142,11 +197,14 @@ binding, with aliases from `rename(columns=...)`. ### Bind more than one input, or fill more than one column {#multi} Parameters bind by name, so a function that takes several arguments binds -several columns in one call: +several columns in one call. `ratio` divides two existing columns, so give +the table a second one first: ```python Python icon="python" -@udf +table.add_columns({"count": "value + 1"}) + +@function def ratio(numerator: float, denominator: float) -> float: return numerator / denominator @@ -164,7 +222,8 @@ mapping, so both columns come from one atomic binding: ```python Python icon="python" import pyarrow as pa -@udf( +@function( + input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]), output_schema=pa.schema([ pa.field("half", pa.float64(), nullable=False), pa.field("double", pa.float64(), nullable=False), @@ -181,6 +240,12 @@ table.add_columns(application) ``` + +`input_schema` and `output_schema` must be given together on v0.41.0. A +version after it accepts either alone, inferring the other from the +annotations. + + A single refresh fills `value_half` and `value_double` together: there is no state where one is filled and the other is still empty. @@ -215,7 +280,7 @@ and `__call__` handles each row or batch. {FunctionClassDefine} -Registering the class does not construct it. `@udf` reads the signature of +Registering the class does not construct it. `@function` reads the signature of `__init__` and packages the source, so the client never loads the model. On the cluster, each instance of the function calls `__init__` once. It then calls `__call__` for every row or batch it processes, and `close()`, if defined, once @@ -226,6 +291,12 @@ State belongs to one instance. An instance reuses it across every batch it serves, but instances do not share it, so each one holds its own copy of the model. Plan memory, or a GPU, for one copy per instance. +Register it the same way as a plain function: + + +{FunctionClassRegister} + + The annotated parameters of `__init__` are the function's initialization fields. Their values come from each binding rather than from the function, so one registered version can run with different settings on different columns: @@ -244,183 +315,22 @@ credentials out of them: pass `secrets=[EnvVarSecret(...)]` to Calling the decorated class in your own process constructs it, the same as an undecorated class, so local tests can create an instance and call it directly. -## Read and produce blobs {#blobs} +## Blob v2 columns {#blobs} -A Function can bind a [Blob v2 column](/management/table#managed-blobs) and -return another blob. In row mode, a top-level blob parameter arrives as Python -`bytes`, or `None` for a nullable input, after the worker has read the -payload. Return bytes and let the destination table store the Managed -payload and descriptor. +A Function can bind a [Blob v2 column](/management/table#managed-blobs) as +input and return another. In row mode, a top-level blob parameter arrives as +Python `bytes`, or `None` for a nullable input, after the worker has read +the payload; annotate it `BlobReader` instead for seekable, incremental +reads that avoid materializing the whole payload first. Return bytes and let +the destination table store the Managed payload and descriptor -- +`output_schema=lancedb.blob(...)` is what makes the result Blob v2 rather +than plain Arrow `binary`; a bare annotation persists as ordinary binary +instead, skipping the Managed storage path and `fetch_blobs`. -The rest of this section extracts a frame from a stored video and captions -it, continuing as one example across chaining, persisting and incremental -reads below. `videos` holds raw clips in a `video` Blob v2 column; `frames` -names one timestamp per clip to extract, with a `selected` flag to skip some: - - -```python Python icon="python" -import lancedb -import pyarrow as pa - -videos = db.create_table("videos", schema=pa.schema([ - pa.field("id", pa.utf8(), nullable=False), - lancedb.blob("video", nullable=False), -])) -frames = db.create_table("frames", [ - {"frame_id": 1, "video_id": "clip-1", "ts": 0.5, "selected": True}, - {"frame_id": 2, "video_id": "clip-1", "ts": 1.5, "selected": True}, -]) -``` - - -### Produce a blob {#produce-blobs} - -Declare blob inputs and outputs explicitly. `extract_frame` reads one frame -out of a video at a timestamp and returns it as a JPEG, without loading the -whole clip first -- see [Read a blob incrementally](#incremental) below for -how the `video: BlobReader` parameter does that: - - -```python Python icon="python" -from datetime import timedelta - -from lancedb import BlobReader, col -from lancedb.functions import udf - -@udf( - name="extract_frame", - gpu=True, - pip=["av==13.1.0", "pillow==11.0.0"], - input_schema=pa.schema([ - lancedb.blob("video"), - pa.field("ts", pa.float64(), nullable=False), - ]), - output_schema=lancedb.blob("jpeg", nullable=False), -) -def extract_frame(video: BlobReader, ts: float) -> bytes: - ... # decode the frame at ts, encode as JPEG, return its bytes - -version = db.create_function_async(extract_frame).wait(timeout=timedelta(minutes=15)) -``` - - -An empty byte string is a filled result. A scalar output cannot be nullable, -because a physical NULL marks an unfilled computed row. To return a nullable -blob as a value, use a named-struct output schema with a nullable blob field; -the struct itself records whether the result has been filled. Read a nested -blob with `table.fetch_blobs("payload.image", hits)`. - - -`output_schema=lancedb.blob(...)` is what makes a persisted result Blob v2 -rather than plain Arrow `binary`. Returning `bytes` from a function whose -output type is inferred from a bare annotation, with no explicit -`lancedb.blob(...)` output schema, persists as ordinary `binary`: the column -still holds the right bytes, but it skips the Managed storage path, descriptor -reads, and `fetch_blobs`. Declare it explicitly on every function whose output -should be a blob, not just the first one in a chain. - - -### Chain a Function on its output {#chain} - -A second Function can bind a blob another Function produced. Register -`caption` the same way, consuming a blob instead of producing one: - - -```python Python icon="python" -@udf(gpu=True, pip=["transformers==4.47.0"]) -def caption(jpeg: bytes) -> str: - ... # run a vision-language model over the JPEG, return one sentence - -caption_version = db.create_function_async(caption).wait(timeout=timedelta(minutes=15)) -``` - - -Compose both in one SQL statement over a join, instead of applying each as -its own column. The join supplies `video` and `ts` from two different -tables, and `caption` reads `extract_frame`'s result as it is computed, -before anything is written: - - -```sql SQL -SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, - caption(extract_frame(v.video, f.ts)) AS caption -FROM videos v JOIN frames f ON v.id = f.video_id -WHERE f.selected = true -``` - - -[`EXPLAIN`](/sql/dql/explain) on a query like this shows `RemoteTake`: the -blob is read once, where the worker runs, and never pulled into the query -node first. - -### Persist it as a column, or a materialized view {#persist} - -Apply the same chained expression with `add_columns` to persist it as an -ordinary table column: - - -```python Python icon="python" -table.add_columns({"jpeg": extract_frame(video=col("video"), ts=col("ts"))}) -result = table.refresh_column_async("jpeg").wait(timeout=timedelta(minutes=15)) -assert result.rows_failed == 0 - -hits = table.search().select(["frame_id", "jpeg"]).with_row_id(True).to_arrow() -values = table.fetch_blobs("jpeg", hits).to_pylist() -``` - - -Or wrap the join and both Functions in a -[materialized view](/sql/ddl/materialized-view) instead, so the extracted -frame and its caption stay current as new videos and frames arrive. See -[Automatic refresh](/feature-engineering/refresh-column#automatic) for -keeping either one fresh without calling refresh yourself. - -On deployments that support computed-column inputs, another Function can -bind to `col("jpeg")` directly, the same as the SQL join above does through -its own expression. Refresh the producer first, then the consumer. Once -outputs are current, a later refresh fills appended rows. A filtered -refresh preserves payload references for unselected Managed outputs. An -unfiltered refresh can recompute a whole fragment when it cannot establish -that the fragment's outputs are current. - -Function output blobs follow the same compaction and cleanup lifecycle as -ingested Managed blobs. Retained versions continue to own their payloads; -cleanup reclaims an object only after its retained references are gone. - -### Read a blob incrementally {#incremental} - -Annotate a row Function parameter with `BlobReader` to read a Blob v2 input -incrementally, the way `extract_frame` above does, instead of materializing -the whole payload first. The signature selects the access mode without -another registration option. A minimal example, reading only the first MP4 -box type without loading the rest of the video: - - -```python Python icon="python" -from lancedb import BlobReader, udf - - -@udf -def first_box_type(video: BlobReader) -> bytes: - video.seek(4) - return video.read(4) -``` - - -The worker passes a seekable reader backed by the stored blob -- -`video.seekable()` is `True`. `read(size)` reads from the current cursor; -`read_range(offset, length)` reads a byte range without moving it, the same -bytes a `seek(offset)` followed by `read(length)` would read. `size()` -returns the payload size without reading it. Each row call receives its own -reader, which closes when the call returns or raises. Do not retain it for -another invocation. - -Use `video: bytes` when the Function needs the complete payload. Bytes inputs -materialize before invocation and remain subject to eager input limits. -Reader inputs keep the unread payload out of the input batch, but calling -`video.read()` without a size loads all remaining bytes in Python. Reader -inputs are supported in row mode. Return values remain ordinary values such -as `bytes`; this feature does not add streamed outputs. +See [Read and produce blobs](/curation/create-function#blobs) for a full +example: extracting a frame from a stored video, chaining a second Function +onto its output, persisting both as columns or a materialized view, and +reading a blob input incrementally. ## Declare the environment {#environment} @@ -437,7 +347,7 @@ dependencies are part of its definition: ```python Python icon="python" -@udf(gpu=True) +@function(gpu=True) def extract_frame(video: BlobReader, ts: float) -> bytes: ... # runs only on a GPU-capable worker ``` @@ -479,50 +389,76 @@ in the function's source or its `env` map in plain text. A Secret is a database-scoped named credential; `db.create_secret` stores the value once, and an `EnvVarSecret` binds it to the environment variable the function reads. Binding is a registration-time decision, passed to -`create_function_async`, not to `@udf`: +`create_function_async`, not to `@function`. No API returns a Secret's value, +and it never appears in the function's registration: the function reads the +environment variable the way it always did, and the binding is what puts a +value there. A mistyped Secret name is caught at registration; a mistyped +environment variable name surfaces only on the first rows, since nothing +records which variables a function reads. - -```python Python icon="python" -import os - -from lancedb import EnvVarSecret - -db.create_secret("openai-prod", os.environ["OPENAI_API_KEY"]) - -@udf -def embed(text: str) -> list[float]: - import os - - from openai import OpenAI - - client = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) - response = client.embeddings.create(input=text, model="text-embedding-3-small") - return response.data[0].embedding - -version = db.create_function_async( - embed, - secrets=[EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")], -).wait() -``` - - -No API returns a Secret's value, and it never appears in the function's -registration: `embed` reads `OPENAI_API_KEY` the way it always did, and the -binding is what puts a value there. A mistyped Secret name is caught at -registration; a mistyped environment variable name surfaces only on the -first rows, since nothing records which variables a function reads. +See [Vend a Secret to a Function](/curation/vend-secret#specify) for the +full worked example. ## Failure handling {#failures} -A function that raises fails the job. There is no per-row retry or skip policy -in the function definition: `@udf` takes no error-handling parameter, so a -function that calls a flaky external service should handle that itself, inside -the function body. +By default, a Function that raises fails the refresh job. Choose how the +refresh handles row errors with its error policy: + + +```sql SQL icon="database" +REFRESH COLUMN embedding ON documents WITH (error_policy = 'skip') +``` + + +`skip` writes null outputs for failing rows and records their errors. Inspect +them with `SHOW ERRORS` or `table.function_errors()`. Failure limits still +apply, and initialization or infrastructure failures can still fail the job. +See the [SQL refresh options](/sql/dml/refresh-column#options). A Function +that calls a transiently failing external service can handle bounded retries +inside its body. Letting the job fail is the other option: fix the cause and refresh again. The -next refresh [skips rows that are filled and current](/feature-engineering/refresh-column#idempotent), +next unfiltered refresh [skips rows that are filled and current](/feature-engineering/refresh-column#idempotent), but how much of the failed job's work was kept is not guaranteed, so do not -count on the retry costing only the rows that did not complete. +count on the retry costing only the rows that did not complete. A refresh with +`WHERE` recomputes every matching live row, including already-filled outputs. + +{/* +Draft for the Function retry policy release. + +### Retry transient errors + +Native retries require an SDK that exposes `FunctionRetryPolicy` and a +LanceDB Enterprise server that supports Function retry policies. Upgrading +the SDK alone does not enable retries on an older server. If a refresh +override reports that the Function image does not support retry policies, +re-register the Function on a supporting server. + +Import `FunctionRetryPolicy` from `lancedb.functions` and pass a policy to +`@function` through `retry_policy`. For example, +`FunctionRetryPolicy(transient=True, max_attempts=3)` allows up to three +calls for matching transient failures. `max_attempts` includes the first +call; setting it to `1` disables user-error retries. A +[refresh override](/feature-engineering/refresh-column#resources) replaces +the registered policy for that refresh. + +Enable retries only when repeating a failed call's partial work is safe. +An external request may have succeeded before the Function raised, so this +policy does not guarantee exactly-once external effects. Functions declared +with external side effects reject retry policies. Calls that return +successfully are not repeated by this policy; infrastructure recovery and +later refreshes have separate replay behavior. + +Each failed callable invocation has one attempt budget. After exhaustion, +the refresh's `error_policy` applies. With an explicit retry policy, `skip` +on a batch Function writes nulls for every row in the failed call and records +their errors. It does not split that call into smaller retries with new +budgets. A row Function handles each row separately. Error records expose +`attempts` when the server records it; older records may omit the count. + +Worker recovery uses a separate retry budget. Framework deadlines and +cancellation stop execution without consuming further user-error retries. +*/} ## What gets packaged {#packaging} @@ -543,29 +479,64 @@ the surrounding scope. Pass `code=[module, ...]` to ship additional helper modules into the same image, for logic the function imports but that does not belong inlined into it -- a model-loading helper shared by several Functions, for example. -Continuing `caption` from [above](#chain), with its model-loading code -factored into a sibling module instead of inlined: +Continuing the [`caption` Function](/curation/create-function#chain), with +its model-loading code factored into a sibling module instead of inlined: ```python Python icon="python" import caption_worker # a sibling module with the model-loading logic -@udf(gpu=True, code=[caption_worker]) +@function(gpu=True, code=[caption_worker]) def caption(jpeg: bytes) -> str: return caption_worker.run(jpeg) ``` Each module in `code` is captured and shipped the same way the function -itself is: as source, snapshotted at registration. +itself is: as source, snapshotted at registration. Only `.py` source files are +included; package data such as JSON, YAML, prompt, or tokenizer files is not +copied. `@function` warns before registration when it skips such files from a +package in `code`, naming the affected paths. To use a package that includes +the required resources, install it with `pip=` or `conda=` and remove that +package from `code`; otherwise the Python-only copied package shadows the +installed distribution. ## Drop it {#drop} -`db.drop_function(name, version=...)` drops the function's name and the object -it is bound to; `version` must be a version that exists. It returns `False` if -the name was already gone. Deleting the object's content can finish after the -call returns, as a [background job](/maintenance/background-jobs). -`drop_function_async` returns that job with the result, so you can wait for it. + +```python Python icon="python" +db.drop_function("double", version="1") +``` + +```rust +# async fn drop_it(connection: &lancedb::Connection) -> Result<(), Box> { +let dropped = connection.drop_function("double", "1", &[]).await?; +# Ok(()) +# } +``` + +```sql SQL icon="database" +DROP FUNCTION double WITH (version = '1') +``` + + +`db.drop_function(name, version=...)` removes only that published revision from +lookup and listing, preserving other revisions and their grants. It returns +`False` for a repeated drop or a name that is already gone. A revision never +published under an existing name is an error. The last visible revision's drop +releases the name and schedules object cleanup, which can finish after the call +returns as a [background job](/basics/jobs#teardown). +`drop_function_async` returns `(dropped, job)`, where `job` is a query-backed +handle. Waiting confirms the revision's catalog removal; physical cleanup can +continue afterward. + +When a deployment reports dependency warnings for a boolean drop, +`db.drop_function` emits each warning as a `UserWarning`. This also applies to +`await db.drop_function(...)` on an async connection. The warnings are emitted +after catalog removal, and standard Python warnings filters apply. If warnings +are configured as errors, the call can raise after the revision has been +removed; the drop is not rolled back. Servers whose DROP response omits the +warning field remain silent. A deployment refuses the drop unless it also allows changes to a function's lifecycle, which is a separate setting, off by default even where Functions are @@ -574,6 +545,9 @@ enabled. ## What to read next {#next} + + Scalar, batch, stateful, GPU and remote-service examples for common curation tasks. + Refresh semantics, and the SQL alternative. diff --git a/docs/web/management/index.mdx b/docs/web/management/index.mdx index 9fc02ad6b..fbef65756 100644 --- a/docs/web/management/index.mdx +++ b/docs/web/management/index.mdx @@ -79,23 +79,19 @@ it current. enables them; the SDK methods send the view's SQL query to the deployment. See [Views](/management/view). -{/* -Draft for the Functions release. - ### Functions {#functions} | | Python | TypeScript | SQL | | --- | --- | --- | --- | | create | `create_function`, `create_function_async` | -- | `CREATE FUNCTION` | -| get | `get_function` | -- | -- | +| get | `get_function` | -- | `DESCRIBE FUNCTION` | | list | `list_functions` | -- | `SHOW FUNCTIONS` | -| drop | `drop_function` | -- | -- | +| drop | `drop_function` | -- | `DROP FUNCTION` | Enterprise A function runs on the server, and only on a deployment that enables functions, so there is no local form. The TypeScript SDK has no function methods; use Python or SQL. See [Functions](/management/function). -*/} ### Jobs {#jobs} @@ -106,7 +102,7 @@ See [Functions](/management/function). | cancel | `cancel_job` | `cancelJob` | -- | | errors | `job.events` | `job.events` | `SHOW ERRORS` | -See [Jobs](/basics/jobs). +See [Job Framework](/basics/jobs). ### Indexes {#indexes} @@ -142,11 +138,12 @@ const tbl = await db.openTable("clicks", ["prod", "events"]); ``` ```sql SQL -SELECT * FROM prod.events.clicks +SELECT * FROM `prod$events`.clicks ``` -In SQL the path is written as dotted identifiers instead. +In SQL the path is written as a `$`-joined schema instead; see +[Namespace](/basics/catalog#schema) for why it isn't dotted. ## Delete catalog objects {#dropping} diff --git a/docs/web/management/materialized-view.mdx b/docs/web/management/materialized-view.mdx index 90283e198..94f3a6911 100644 --- a/docs/web/management/materialized-view.mdx +++ b/docs/web/management/materialized-view.mdx @@ -25,28 +25,29 @@ In SQL, see [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh-materialized-view) an ## Create a materialized view {#create} +A materialized view is defined by a SQL query: + ```python Python icon="python" -view = db.create_materialized_view( - "frames_captioned", - source="frames", - select=["frame_id", "video_id", "ts", "caption"], - where="selected = true", -) +db.execute_query(""" + CREATE MATERIALIZED VIEW frames_captioned AS + SELECT frame_id, video_id, ts, caption + FROM frames + WHERE selected = true +""").read_all() +view = db.open_materialized_view("frames_captioned") ``` -```typescript TypeScript icon="square-js" -const view = await db.createMaterializedView("frames_captioned", "frames", { - select: ["frame_id", "video_id", "ts", "caption"], - where: "selected = true", -}); +```sql SQL icon="database" +CREATE MATERIALIZED VIEW frames_captioned AS +SELECT frame_id, video_id, ts, caption +FROM frames +WHERE selected = true ``` -`source` names the table the view reads — here, a `frames` table with a -`caption` column, filtered to the frames selected for captioning. See -[Create a materialized view](/feature-engineering/materialized-views#create) -for the full walkthrough. `select`, `where` and `limit` define the query. +See [Create a materialized view](/feature-engineering/materialized-views#create) +for the full walkthrough, including joins and Functions in the query. ## Open, list and drop views {#manage} @@ -56,31 +57,17 @@ for the full walkthrough. `select`, `where` and `limit` define the query. | open | `open_materialized_view` | `openMaterializedView` | -- | | list | `list_materialized_views` | `listMaterializedViews` | `SHOW MATERIALIZED VIEWS` | | refresh | `refresh` | `refresh` | `REFRESH MATERIALIZED VIEW` | -| drop | `drop_table` | `dropTable` | `DROP TABLE` | +| drop | `drop_materialized_view` | `dropMaterializedView` | `DROP MATERIALIZED VIEW` | Enterprise Creating, refreshing and dropping a materialized view each have an async, job-returning counterpart -- `create_materialized_view_async`, `view.refresh_async()`, `drop_materialized_view_async` -- the same pattern as [`refresh_column_async`](/feature-engineering/refresh-column#async): each -returns a [job](/basics/jobs) you `wait()` on instead of blocking. The async -counterpart of the example [above](#create): - - -```python Python icon="python" -from datetime import timedelta - -job = db.create_materialized_view_async( - "frames_captioned", source="frames", - select=["frame_id", "video_id", "ts", "caption"], where="selected = true", -) -view = job.wait(timeout=timedelta(minutes=15)) -``` - - -`create_materialized_view_async` also accepts `auto_refresh_enabled` and -`auto_refresh_interval_seconds`; see -[Automatic refresh](/feature-engineering/refresh-materialized-view#auto-refresh). +returns a [job](/basics/jobs) you `wait()` on instead of blocking, with the +same arguments as its synchronous counterpart, including +`auto_refresh_enabled` and `auto_refresh_interval_seconds`; see +[Auto Refresh](/enterprise/auto-refresh). On a local database, `list_materialized_views` reads table schemas to find @@ -88,14 +75,16 @@ views. On Enterprise, it asks the server for the view listing, as `SHOW MATERIALIZED VIEWS` does. -A view is dropped with `drop_table`, because a materialized view **is** a table. -That also means dropping one removes stored rows, unlike dropping a +A view is dropped with `drop_materialized_view`, a dedicated operation, even +though a materialized view **is** a table underneath. That also means +dropping one removes stored rows, unlike dropping a [view](/management/view), which removes only a saved query. ## Read the view and its definition {#working} `view.table` is the underlying table, for querying, indexing, or search. -`view.definition` contains the query's select list, predicate and limit. Both are properties; on an async view, the definition is read with +`view.definition` has a single field, `query` -- the defining query, in the +canonical spelling the server stores. Both are properties; on an async view, the definition is read with `await view.definition()`. ## Enterprise compatibility {#deployment} @@ -104,6 +93,26 @@ Enterprise supports creating and refreshing materialized views on remote compute. Use the SDK version supported by your deployment, or the [SQL interface](/sql/ddl/materialized-view). +## Privileges {#privileges} + +A materialized view **is** a table (see [Dropping one](/sql/ddl/materialized-view#drop)), +granted through the REST ACL API or SQL `GRANT`/`REVOKE` with the same +privilege names as a table, but two of them mean something different here: +the server refuses a direct `INSERT`, `UPDATE` or `DELETE` on a materialized +view's rows -- only a refresh writes them. `UPDATE` is instead what +authorizes calling refresh, and `OWNERSHIP` is what authorizes `ALTER` +(auto-refresh settings): + + +```sql SQL icon="database" +GRANT SELECT, UPDATE ON MATERIALIZED VIEW daily_rollup TO ROLE analysts +``` + + +That grants `analysts` read access and the ability to refresh `daily_rollup`, +not row-level write access. See [Privileges](/governance/privileges#sql) for +the full statement syntax and every target it reaches. + ## Related guides {#next} diff --git a/docs/web/management/namespace.mdx b/docs/web/management/namespace.mdx index 99e53d793..056d95600 100644 --- a/docs/web/management/namespace.mdx +++ b/docs/web/management/namespace.mdx @@ -34,7 +34,9 @@ language: Python uses `namespace_path`, Rust uses builder methods like `.namespa TypeScript uses `namespacePath` arguments. -In LanceDB Enterprise SQL, a namespaced table is addressed as a [dotted path](/sql/dql/select#namespaces). +In LanceDB Enterprise SQL, a namespaced table is addressed by its +[schema](/basics/catalog#schema) -- the namespace path joined by `$`, not +by `.` -- [before the table name](/sql/dql/select#namespaces). ## Namespace hierarchy {#namespace-hierarchy} @@ -75,12 +77,10 @@ The hierarchy is logical, not a tree of folders: a directory namespace records i As a user of LanceDB Embedded, you might never notice namespaces at first, because a plain connection uses only the root namespace, which is implicit. Connecting to this namespace is as simple as -connecting to the catalog root: +connecting to the namespace root: ```python Python icon="python" -import lancedb - # Connect to the directory namespace root db = lancedb.connect("./local_lancedb") ``` @@ -106,9 +106,7 @@ You can also explicitly connect to a namespace using `lancedb.connect_namespace( ```python Python icon="python" -import lancedb - -# Local namespace-backed catalog root (DirectoryNamespace) +# Local DirectoryNamespace root # See https://lance.org/format/namespace/dir/catalog-spec/ db = lancedb.connect_namespace("dir", {"root": "./local_lancedb"}) @@ -123,7 +121,7 @@ print(f"Created table: {table.name}") ```typescript TypeScript icon="square-js" import * as lancedb from "@lancedb/lancedb"; -// Local namespace-backed catalog root (DirectoryNamespace) +// Local DirectoryNamespace root // See https://lance.org/format/namespace/dir/catalog-spec/ const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" }); @@ -141,7 +139,7 @@ use std::collections::HashMap; use std::sync::Arc; use arrow_schema::{DataType, Field, Schema}; -// Local namespace-backed catalog root (DirectoryNamespace) +// Local DirectoryNamespace root // See https://lance.org/format/namespace/dir/catalog-spec/ let mut properties = HashMap::new(); properties.insert("root".to_string(), "./local_lancedb".to_string()); @@ -185,9 +183,7 @@ application code, load credentials from environment variables or a secrets manag ```python Python icon="python" -import lancedb - -# Remote namespace-backed catalog root (RestNamespace) +# Remote RestNamespace root # See https://lance.org/format/namespace/rest/catalog-spec/ db = lancedb.connect_namespace( "rest", @@ -203,7 +199,7 @@ db = lancedb.connect_namespace( ```typescript TypeScript icon="square-js" import * as lancedb from "@lancedb/lancedb"; -// Remote namespace-backed catalog root (RestNamespace) +// Remote RestNamespace root // See https://lance.org/format/namespace/rest/catalog-spec/ const db = await lancedb.connectNamespace("rest", { uri: "https://.internal..com", @@ -218,7 +214,7 @@ const db = await lancedb.connectNamespace("rest", { ```rust Rust icon="rust" use std::collections::HashMap; -// Remote namespace-backed catalog root (RestNamespace) +// Remote RestNamespace root // See https://lance.org/format/namespace/rest/catalog-spec/ let mut properties = HashMap::new(); properties.insert( @@ -239,7 +235,7 @@ let db = lancedb::connect_namespace("rest", properties) .await?; ``` -[LanceDB Enterprise](/enterprise) operates a REST namespace server on top of the Lance format, so any REST client that can speak the REST namespace API +[LanceDB Enterprise](/index#architecture) operates a REST namespace server on top of the Lance format, so any REST client that can speak the REST namespace API contract can be used to interact with it. It does not serve the contract's `exists` routes, so existence checks made through a direct REST namespace client fail against it. Python remote connections created with `lancedb.connect("db://...")` or @@ -379,3 +375,19 @@ With `forward_header_prefixes = ["X-forward"]`, any incoming header starting wit For the LanceDB REST API itself, requests use `x-api-key` for API-key authentication. If your endpoint serves more than one database, LanceDB can also use headers such as `x-lancedb-database` or `x-lancedb-database-prefix` to route the request to the right database context. + +## Privileges {#privileges} + +A namespace's `USAGE`, and the `CREATE_TABLE`, `CREATE_VIEW`, +`CREATE_MATERIALIZED_VIEW`, `CREATE_NAMESPACE`, `CREATE_SECRET`, +`CREATE_STORAGE_INTEGRATION` and `CREATE_FUNCTION` privileges for what it +can hold, are granted through the REST ACL API or SQL `GRANT`/`REVOKE`: + + +```sql SQL icon="database" +GRANT CREATE NAMESPACE, CREATE TABLE, CREATE VIEW ON SCHEMA platform TO ROLE writers +``` + + +See [Privileges](/governance/privileges#sql) for the full statement syntax +and every target it reaches. diff --git a/docs/web/management/secret.mdx b/docs/web/management/secret.mdx new file mode 100644 index 000000000..66d71afd7 --- /dev/null +++ b/docs/web/management/secret.mdx @@ -0,0 +1,183 @@ +--- +title: "Secret" +tag: "Early access" +sidebarTitle: "Secret" +description: "Create, rotate, list, describe and drop a named credential that Functions bind by reference." +icon: key +keywords: ["secret", "create_secret", "alter_secret", "drop_secret", "credentials", "api key"] +availability: + embedded: unavailable + enterprise: available +--- + +Early access + +A **Secret** is a catalog object, like a table or a namespace: a named +credential, such as a model provider's API key, stored once and addressed by +name. A [Function](/curation/create-function) binds a Secret by reference +when you register it, never by value; see +[Vend a Secret to a Function](/curation/vend-secret) for how that binding +reaches running code. + +The design rule is **bind by reference, resolve late**. A Function records +*which* Secret it reads, never the value, and the value is looked up each +time a job starts. That is what lets a credential be rotated or revoked +without touching the Functions, columns or tables that use it. + +## Create and manage {#manage} + +Every call takes an optional `namespace_path`; the default is the root +namespace. + + + +```python Python +db.create_secret("model-api-key", value, namespace_path=["platform"]) + +db.alter_secret("model-api-key", new_value, namespace_path=["platform"]) + +for name in db.list_secrets(namespace_path=["platform"]): + print(name) + +info = db.describe_secret("model-api-key", namespace_path=["platform"]) +info.created_at_millis, info.updated_at_millis + +db.drop_secret("model-api-key", namespace_path=["platform"]) +``` + +```sql SQL +CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = ''; + +ALTER SECRET platform.`model-api-key` SET SECRET_STRING = ''; + +SHOW SECRETS IN platform; + +DESCRIBE SECRET platform.`model-api-key`; + +DROP SECRET platform.`model-api-key`; +``` + +```rust +use futures::TryStreamExt; + +let namespace = vec!["platform".to_string()]; + +db.create_secret("model-api-key", &value, &namespace).await?; + +db.alter_secret("model-api-key", &new_value, &namespace).await?; + +let mut names = db.list_secrets(&namespace, Default::default()); +while let Some(name) = names.try_next().await? { + println!("{name}"); +} + +let info = db.describe_secret("model-api-key", &namespace).await?; +println!("{} {}", info.created_at_millis, info.updated_at_millis); + +db.drop_secret("model-api-key", &namespace).await?; +``` + + + +A Secret's value is never returned by any interface: `create` and +`alter` take it as input and return nothing, and `describe` reports only +metadata. Python and Rust both expose the full lifecycle shown above; +TypeScript does not yet, and is tracked separately. See the +[SQL reference](/sql/ddl/secret) for the same operations' SQL syntax and +result rows. + + +SQL has no syntax for binding a Secret to a Function. Register Functions that +bind Secrets through the Python SDK; see +[Vend a Secret to a Function](/curation/vend-secret). + + +## Properties and guarantees {#security} + +LanceDB guarantees that: + +- No API returns a Secret's value. +- Values do not appear in Function source, Function versions, jobs, logs, or + error messages. Errors raised by Function code are redacted, within + [limits](#redaction). +- A Function receives only the Secrets bound to it. +- Values are always [encrypted at rest](#encryption). + +Redaction is a safety net, not a boundary: Function code that logs, returns +or sends a credential will leak it. + +### Encryption at rest {#encryption} + +Every Secret's value is encrypted directly with your deployment's key in AWS +KMS, Google Cloud KMS, or Azure Key Vault -- there is no separate application +data key to manage. Storage, backups and replicas hold only ciphertext. +Decryption goes through your KMS, which records it in your cloud's audit +log. + +BYOC You are responsible for the network egress +policy for the jobs that run Functions. + +### Redaction {#redaction} + +If a Function raises an error or skips a row with a message that contains a +bound value, LanceDB replaces each exact occurrence with `[REDACTED]` before +the message is recorded. Redaction matches only the exact value: a value +that is base64-encoded, sliced, or otherwise transformed is not caught. +Function code that prints a credential, writes it into a column, or sends +it elsewhere will leak it, so review a Function bound to a Secret as code +that holds that credential. + +## Limits {#limits} + +| Item | Limit | +| --- | --- | +| Secret name | 1--128 characters from `A-Z a-z 0-9 _ . -`. `$` is reserved as the namespace delimiter. | +| Value | One nonempty UTF-8 string, at most 4,096 bytes. On Azure, at most 158, 286 or 414 bytes for an RSA-2048, RSA-3072 or RSA-4096 key. | +| Bindings per Function | 16 | +| Environment variable name | `[A-Za-z_][A-Za-z0-9_]*`, and not [reserved](#reserved) | +| Variables per Function | Each bound once. Two variables may bind the same Secret. | +| `describe` history | The most recent 100 alterations | + +### Reserved variables {#reserved} + +A Secret cannot be bound to a variable that LanceDB sets for Functions +itself. These names are reserved: + +- Exact names: `HOME`, `PATH`, `TEMP`, `TMP`, `TMPDIR`, `LANG`, `LC_ALL`, + `LC_CTYPE`, `TZ`, `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` (and their + lowercase forms), `SSL_CERT_FILE`, `SSL_CERT_DIR`, `REQUESTS_CA_BUNDLE`, + `UV_CACHE_DIR`, `UV_NATIVE_TLS`, `UV_PYTHON_INSTALL_DIR`, `RUST_BACKTRACE` +- Prefixes: `DYLD_`, `LANCE_`, `LANCEDB_`, `LD_`, `PYTHON`, and a few others + LanceDB reserves for its own use. `create_function` refuses a reserved + name and says which one. + +## Troubleshooting {#troubleshooting} + +**`Secret 'X', bound to VAR, does not exist`** when adding a column or +refreshing one: the Secret was never created in that namespace, was dropped, +or its name is misspelled in the binding. Create it, or register a new +Function version with the right name. + +**501 from a Secret API call**: Secrets aren't enabled for this deployment. +Contact [LanceDB support](/deployment/support). + +## Privileges {#privileges} + +A Secret is its own object in the authorization model, a namespace child +like a table, so a grant names one credential rather than a whole +database. See [Privileges](/governance/privileges#secret-operations) for +the privilege each operation above requires, and +[GRANT and REVOKE](/sql/ddl/secret#grant) for the full SQL statement +syntax. + +## What to read next {#next} + + + + Bind a Secret when you register a Function, and how rotation reaches + code that is already running. + + + Grant and revoke privileges on a Secret. + + diff --git a/docs/web/management/storage-integration.mdx b/docs/web/management/storage-integration.mdx new file mode 100644 index 000000000..a6bc4efbe --- /dev/null +++ b/docs/web/management/storage-integration.mdx @@ -0,0 +1,136 @@ +--- +title: "Storage Integration" +sidebarTitle: "Storage Integration" +description: "A namespace-scoped, reusable credential for reading or importing from storage outside the deployment's own tables." +icon: cloud +keywords: ["storage integration", "s3", "gcs", "azure", "huggingface", "external storage", "credentials"] +availability: + embedded: unavailable + enterprise: available +--- + +A **storage integration** is a namespace-scoped catalog object, like a +[Secret](/management/secret), that names a credential for reading or +importing from one external storage location: an S3, GCS or Azure prefix, +or a HuggingFace dataset repository. A query or import statement that +reads a matching URI uses the integration automatically -- it is never +named in the query itself. + +## Create and manage {#manage} + +Every provider takes a `storage_prefix` and `storage_provider`, plus +provider-specific credential options. Credential options take a +[Secret](/management/secret) reference, never a value directly -- either a +bare name (resolved in the caller's own database, root namespace) or a +`SecretReference` qualified with a database and namespace path: + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION hub + STORAGE_PROVIDER = 'HUGGINGFACE' + STORAGE_PREFIX = 'hf://datasets/owner/private/data/' + HUGGINGFACE_TOKEN_SECRET = bootstrap.credentials.hf_token + +DESCRIBE STORAGE INTEGRATION hub + +SHOW STORAGE INTEGRATIONS + +DROP STORAGE INTEGRATION hub +``` + + +{/* +Draft for the storage-integration SDK release (#4618, #4775). Keep this +section unpublished until create_storage_integration and its siblings ship +in a release; they are not in v0.41.0. + + +```python Python icon="python" +from lancedb.storage_integration import SecretReference + +info = db.create_storage_integration( + "hub", "hf://datasets/owner/private/data/", + storage_provider="HUGGINGFACE", + huggingface_token_secret=SecretReference( + "hf_token", database="bootstrap", namespace_path=("credentials",), + ), +) +print(info.configuration_instructions) + +info = db.describe_storage_integration("hub") +names = list(db.list_storage_integrations()) +db.drop_storage_integration("hub") +``` + +*/} + +See [Storage Integration](/sql/ddl/storage-integration) for every +provider's exact options, S3's two credential modes, and the full output +schema -- this page covers the CRUD operations above at a glance; that one +is the complete reference. + +| Operation | Python (not yet released) | SQL | Notes | +| --- | --- | --- | --- | +| Create | `create_storage_integration` | `CREATE STORAGE INTEGRATION` | Fails if the name is taken, so a create never silently replaces one. | +| Describe | `describe_storage_integration` | `DESCRIBE` / `DESC` | One row: provider, prefix, credential references, and (for an AWS role integration) the generated trust policy. | +| List | `list_storage_integrations` | `SHOW` / `LIST STORAGE INTEGRATIONS` | Optionally scoped to one namespace. | +| Drop | `drop_storage_integration` | `DROP [IF EXISTS]` | Blocked while an attached database still depends on it. | + +The Python column names the methods landing in a future release (see the +draft note above); use SQL today. There is no TypeScript or REST +equivalent yet either. + +There is no `ALTER`. To rotate a credential, rotate the +[Secret](/management/secret#manage) it references -- the integration's +reference does not change, so nothing that reads through it needs updating. + +## The S3 trust workflow {#trust} + +An S3 integration created with `STORAGE_AWS_ROLE_ARN` (instead of a static +access key pair) needs one more step outside LanceDB: `DESCRIBE` returns +`trust_policy` and `permissions_policy`, the IAM policy documents your role +needs, built from `aws_account_id`, `aws_iam_principal_arn` and +`aws_external_id` in the same row. Attach `trust_policy` as the role's +trust relationship and `permissions_policy` as its permissions, then check +`access_verified` on a later `DESCRIBE` to confirm LanceDB can assume the +role and read the prefix. + +## Privileges {#privileges} + +A storage integration is its own object in the authorization model, a +namespace child like a Secret: `CREATE_STORAGE_INTEGRATION` on the +namespace to create one, `USAGE` on the integration for a query to read +through it, `OWNERSHIP` for full control including dropping it. See +[Privileges](/governance/privileges#sql) for the privilege each operation +requires and the full `GRANT`/`REVOKE` syntax. + +## Troubleshooting {#troubleshooting} + +**A query does not use the integration you expected**: integrations match +by the most specific `STORAGE_PREFIX` covering the URI, not by name, and +are scoped to native databases under the catalog root. Two integrations +with equally specific prefixes make the query fail rather than guess; keep +prefixes for the same bucket or dataset family unambiguous. + +**403 or access-denied reading a matching prefix**: confirm `USAGE` on the +integration, and for an S3 role integration, confirm `access_verified` is +`true` on `DESCRIBE` -- `false` usually means the trust policy from +[above](#trust) is missing or misconfigured on the AWS side, not a LanceDB +permission problem. + +**`DROP` refuses with a dependent database**: detach the database that +still uses the integration first, then drop it. + +## What to read next {#next} + + + + The complete SQL reference: every provider's options, output columns, and GRANT syntax. + + + The most common use of a storage integration today: inspecting and importing HuggingFace datasets. + + + The credential a storage integration's `_SECRET` options reference. + + diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 0b71fb315..c229e13f0 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -143,8 +143,8 @@ import { A table stores data in rows and columns and keeps a history of committed versions. Queries read table data, writes update it, and indexes accelerate -searches over its columns. Branches let you make changes separately from the -main table history. +searches over its columns.{/* Draft until branching reaches early access: restore "Branches let you make changes separately from the +main table history." */} This page covers table management, data types, schema changes and version history. For loading records, see [Ingestion](/ingestion). For changes to @@ -161,7 +161,11 @@ In LanceDB Enterprise, tables are also created and dropped in SQL with [`CREATE | **Columns** | including vectors, blobs, and [computed](/feature-engineering/add-computed-column) columns | | **Versions** | every write commits one, so reads can [travel back](/management/table#versioning) | | **Indexes** | vector, full-text and scalar, built over its columns | + +{/* +Draft until branching reaches early access. | **Branches** | isolated lines of change you can [merge or discard](/tables/branching) | +*/} ## Create a table {#create} @@ -228,7 +232,8 @@ has no `tableExists`. ## Rename and clone tables {#rename-clone} -```python + +```python Python icon="python" db.rename_table("documents", "docs") db.clone_table( @@ -238,6 +243,7 @@ db.clone_table( is_shallow=True, ) ``` + Renaming is not supported on a local directory connection. In LanceDB Enterprise, whether a table can be renamed or cloned at all depends on how the deployment @@ -263,7 +269,7 @@ does not support it refuses every clone. the teardown runs as a job: `drop_table`, which fences the table's directory with a marker and deletes its content, or `drop_object`, depending on how the deployment stores its catalog. See -[Background jobs](/maintenance/background-jobs#teardown). +[Object teardown](/basics/jobs#teardown). ## Drop a table {#drop} @@ -324,7 +330,7 @@ as it is to the format. | String and binary | `utf8`, `large_utf8`, `binary`, `large_binary`, `fixed_size_binary(n)` | | Date and time | `date32`, `date64`, `time32`, `time64`, `timestamp`, `duration` | | Nested | `struct`, `list`, `large_list`, `fixed_size_list`, `map` | -| Lance extensions | vectors, [JSON](/sql/data-types#json), [blobs](#multimodal), bfloat16 | +| Lance extensions | vectors, [blobs](#multimodal), bfloat16{/* Draft until JSON columns reach early access: restore "[JSON](/sql/data-types#json), " after "vectors, " */} | A vector column is a `fixed_size_list`, an ordinary Arrow type, which is why it is selectable and joinable but why arithmetic over it is list @@ -343,9 +349,7 @@ file, up to 64 KiB by default, and larger values are stored outside it. ### Blob columns {#multimodal-blob-v2} - -Blob V2 is in early access. - +Early access A `blob` column keeps metadata separate from the payload bytes, so queries can filter rows without loading the blobs. @@ -649,8 +653,8 @@ clients cannot safely maintain a table containing Managed blobs. This example uses a local connection. The same schema, `add`, query, and `fetch_blobs` calls work with an Enterprise database connection: -```python -import lancedb + +```python Python icon="python" import pyarrow as pa db = lancedb.connect("./media") @@ -680,6 +684,7 @@ by_id = dict(zip(hits["id"].to_pylist(), images, strict=True)) assert by_id[1] == b"" assert len(by_id[2]) == 102400 ``` + `fetch_blobs` materializes the selected payloads in memory, so fetch bounded batches when blobs are large. Row IDs belong to their table and snapshot. Keep @@ -694,7 +699,7 @@ LanceDB Embedded tables can also derive blob columns with [SQL computed columns](/feature-engineering/add-computed-column). Deleting a row or replacing its blob does not immediately remove the old -payload: retained table versions may still reference it. [Cleanup](/maintenance/cleanup#managed-blobs) +payload: retained table versions may still reference it. [Garbage Collection](/maintenance/cleanup#managed-blobs) reclaims objects after those references expire. A packed object remains while any of its contained blobs is still referenced. @@ -926,7 +931,10 @@ older version for reads, call `checkout_latest` / `checkoutLatest` before modify You can add new columns to a table with the [`add_columns`](https://lancedb.github.io/lancedb/python/python/#lancedb.table.Table.add_columns) method in Python, [`addColumns`](https://lancedb.github.io/lancedb/js/classes/Table/#addcolumns) in TypeScript/JavaScript, or `add_columns` in Rust. -New columns are populated based on SQL expressions you provide. +New columns are populated based on SQL expressions you provide. On local tables, +the Python SDK also accepts precomputed values from DataFrames and Arrow readers; +see [Create a computed column](/feature-engineering/add-computed-column#computed-vs-transforms) +for the supported inputs and row-order requirements. #### Set up the example table {#schema-set-up-the-example-table} @@ -1116,6 +1124,21 @@ For transformations that are not simple casts (for example, converting `"$100"` #### Alter embedding types and dimensions {#schema-alter-embedding-types-and-dimensions} +{/* +Draft for the embedding schema-evolution protection release. + + +Local tables reject renaming or dropping source and vector columns referenced by +`embedding_functions` schema metadata or native Rust embedding definitions in +`lancedb::column_definitions`. The operation fails before changing any columns, +preserving the configuration used to generate embeddings on later writes. + +The add/drop/rename recipe below applies only to vector columns without a registered +embedding function. To change the dimension of a registered embedding column, create +a new table with the updated embedding configuration and regenerate its embeddings. + +*/} + It's quite common to need to change an embedding column's schema, in case a new model becomes available with a different embedding dimension. - In Python, the example shows an in-place type update when the cast is compatible. - In TypeScript and Rust, the example shows a dimension change (`384 -> 1024`), which cannot be cast in-place. @@ -1469,6 +1492,9 @@ Deleting a tag only removes the label, not the version it points to. After deletion, the underlying table version becomes eligible for cleanup again. +{/* +Draft until branching reaches early access. + ### Branches {#versioning-branches} Beyond linear history, LanceDB also supports **branches**: isolated, writable @@ -1478,6 +1504,7 @@ writable history, making it ideal for experiments, backfills, and migrations that you want to keep separate from production reads on `main`. Branches are covered in their own guide: see [Branches](/tables/branching). +*/} ### Delete Data From the Table {#versioning-delete-data-from-the-table} @@ -1555,3 +1582,17 @@ one by the time cleanup runs; the error then comes after compacting, and the ind update does not run. To let cleanup proceed, [move the tag](#versioning-tag-based-versioning) to a version inside the retention window, delete it, or widen the window. + +## Privileges {#privileges} + +A table's `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE` and `DELETE` are +granted through the REST ACL API or SQL `GRANT`/`REVOKE`: + + +```sql SQL icon="database" +GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl +``` + + +See [Privileges](/governance/privileges#sql) for the full statement syntax +and every target it reaches. diff --git a/docs/web/management/view.mdx b/docs/web/management/view.mdx index e01120034..d061555c9 100644 --- a/docs/web/management/view.mdx +++ b/docs/web/management/view.mdx @@ -30,3 +30,17 @@ Views are created in LanceDB Enterprise, either in SQL over the `createView`, which send the query to the deployment. Either way, the deployment must have views enabled. See [View](/sql/ddl/view) for `CREATE VIEW`, `DROP VIEW`, and listing. + +## Privileges {#privileges} + +A view's `OWNERSHIP` and `SELECT` are granted through the REST ACL API or +SQL `GRANT`/`REVOKE`: + + +```sql SQL icon="database" +GRANT SELECT ON VIEW dashboard TO ROLE analysts +``` + + +See [Privileges](/governance/privileges#sql) for the full statement syntax +and every target it reaches. diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 02ec850bb..5bd9a3efe 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -5,17 +5,11 @@ description: "Install LanceDB, create a table, and run your first vector search. icon: rocket --- import { PyConnect, TsConnect, RsConnect, PyConnectObjectStorage, TsConnectObjectStorage, RsConnectObjectStorage, PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders, RsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; -import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartAddFeature, PyQuickstartComputedFeature, PyQuickstartComputedFeatureEnterprise, PyQuickstartMultimodalBytes, PyQuickstartTraining, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, TsQuickstartCurateWithMetadata, TsQuickstartAddFeature, TsQuickstartQueryFeature, TsQuickstartMultimodalBytes, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1, RsQuickstartCurateWithMetadata, RsQuickstartAddFeature, RsQuickstartQueryFeature, RsQuickstartMultimodalBytes } from '/snippets/quickstart.mdx'; +import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartCurateSample, PyQuickstartCurateDedupeSetup, PyQuickstartCurateDedupe, PyQuickstartCurateDedupeQuery, PyQuickstartFlattenStats, PyQuickstartAddFeature, PyQuickstartAddFeatureEnterprise, PyQuickstartMultimodalBytes, PyQuickstartTraining, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, TsQuickstartMultimodalBytes, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1, RsQuickstartMultimodalBytes } from '/snippets/quickstart.mdx'; This quickstart uses LanceDB Embedded with a local database and works without an account or API key. LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. - -Using LanceDB Enterprise? Only the connection changes. In step 2, use the -[Enterprise](#connect-to-lancedb-enterprise) connection with your deployment's database URI, API key, and endpoint -in place of the local directory. The remaining steps use the same API. - - ## 1\. Install LanceDB {#1-install-lancedb} Choose your language. Python uses Pandas to display the search results. TypeScript needs Node.js 22.18 or later to run the `.mts` example directly. @@ -63,8 +57,10 @@ uv add --prerelease allow --index https://pypi.fury.io/lancedb/ lancedb ``` -If you also need the optional `lance` Python API, install the `pylance` extra and -include the Lance preview index: +Most applications only need `lancedb`. Install the optional `pylance` extra and +include the Lance preview index only when building query engines or connectors, +calling format-level `lance` APIs directly, or converting plain-scan lazy or +legacy blob columns with `to_pandas()`: ```bash Python (pip) icon="terminal" @@ -104,9 +100,11 @@ with `Illegal instruction`. Install `lancedb-compat` instead. It exposes the same API (`import lancedb` still works), is built at the `x86-64-v2` baseline, and uses runtime SIMD dispatch to still use AVX2, FMA, or AVX-512 when available: + ```bash Python (pip) icon="terminal" pip install lancedb-compat ``` + The two packages share the same `lancedb/` namespace and conflict at install time, so pick one. To switch, uninstall the other first (`pip uninstall lancedb && pip install lancedb-compat`). @@ -138,7 +136,7 @@ For Python's async API, see [Connecting to a database](/basics/catalog). ### Object storage {#connect-via-object-storage-uris} -Use an `s3://`, `gs://`, or `az://` URI in place of the local path. See [Configuring storage](/deployment/storage) for credentials and provider-specific options. +Use an `s3://`, `gs://`, or `az://` URI in place of the local path. See [Object storage](/basics/catalog#object-storage) for credentials and provider-specific options. @@ -176,7 +174,7 @@ Use the database URI, API key, and endpoint provided by your administrator or th In application code, load credentials from environment variables or a secrets manager. See [connection settings](/basics/catalog#enterprise) for an example. -Need a deployment? [Contact the LanceDB team](https://www.lancedb.com/contact). For differences between local and server execution, see [LanceDB Enterprise](/enterprise). +Need a deployment? [Contact the LanceDB team](https://www.lancedb.com/contact). For differences between local and server execution, see [LanceDB Enterprise](/index#architecture). ## 3\. Create a table and add data {#3-create-a-new-table} @@ -249,38 +247,85 @@ Find the two embeddings closest to the query embedding. This example uses a fixe Frames 2 and 4 come back first -- the gripper closing on the cup, then lowering it. Python displays a Pandas DataFrame, Rust displays a Polars DataFrame, and TypeScript displays an array of results. The `_distance` column measures how far each result is from your query embedding, with smaller values indicating a closer match. -## 5\. Filter results {#5-curation} +## 5\. Curate data with SQL {#5-curate-with-sql} -Combine vector search with a metadata filter, such as `stats.motion >= 4`, to curate results instead of just ranking them: + +Step 5 needs LanceDB Enterprise: SQL is an Enterprise feature. If you're +using LanceDB Embedded, skip ahead to +[Flatten nested fields](#flatten-nested-fields) below. + + +LanceDB Enterprise accepts SQL over the same connection, for sampling, joins, and +curation tasks that go beyond a single table scan. Draw a quick sample to look +at the data: - {"curated = (\n table.search(query_vector)\n .where(\"stats.motion >= 4\")\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .to_pandas()\n)\nprint(curated)\n"} - - - {TsQuickstartCurateWithMetadata} - - - {RsQuickstartCurateWithMetadata} + {PyQuickstartCurateSample} -Frames 2 and 4 come back again here, since both already have `motion >= 4`; frames 1 and 3 are excluded from ranking entirely, rather than ranked and then dropped. See [SQL filtering](/search/filtering) for the full predicate syntax. +See [SQL](/basics/sql) for the Flight SQL client and CLI alternatives to `execute_query()`. + +Now add a near-duplicate frame -- frame 5 is one video frame after frame 2, with +an almost identical embedding -- and build the vector index that `dedupe` reads: + + + + {PyQuickstartCurateDedupeSetup} + + + +Collapse near-duplicates into a materialized view that stays current as new frames arrive, then read it back: + + + + {PyQuickstartCurateDedupe} + + + + + + {PyQuickstartCurateDedupeQuery} + + + +Frames 2 and 5 collapse into one representative -- five rows become four. +Which of the two ids survives is not guaranteed to stay the same across +appends, so don't treat it as a stable identifier for the cluster. See +[Deduplicate near-duplicate records](/curation/dedupe) for `duplicate_pairs`, +resolution strategies, and tuning `distance_threshold`, and +[Statistical Sampling](/curation/statistical-sampling) for percentage samples, +repeatable draws, and sampling across a join. ## 6\. Add a derived feature {#6-add-a-derived-feature} -Add a column calculated from existing fields with a SQL expression. This fills every existing row once, immediately: +### Flatten nested fields {#flatten-nested-fields} + +A UDF binds to top-level columns, so flatten the fields inside `stats` first. +This is a plain eager `add_columns` call, so it works the same on LanceDB +Embedded and LanceDB Enterprise -- [step 8](#8-train) needs these columns +either way: + + + + {PyQuickstartFlattenStats} + + + + +The rest of this step needs LanceDB Enterprise -- Functions are an +Enterprise feature. If you're using LanceDB Embedded, skip ahead to +[step 7](#7-store-multimodal-data). + + +Register a UDF as a Function, then call it to fill a column computed from +those flattened fields. This fills every existing row once, immediately: {PyQuickstartAddFeature} - - {TsQuickstartAddFeature} - - - {RsQuickstartAddFeature} - Read it back like any other column: @@ -289,37 +334,21 @@ Read it back like any other column: {"features = table.search().select([\"frame_id\", \"video_id\", \"quality_score\"]).limit(10).to_pandas()\nprint(features)\n"} - - {TsQuickstartQueryFeature} - - - {RsQuickstartQueryFeature} - -See [Adding columns](/management/table#schema-add-new-columns) for more on this form. - -## 7\. Set up computed columns {#7-computed-columns} - -A computed column is declared up front and filled -- or refilled -- on demand, instead of being calculated once like step 6's. Declare `caption_length`, then fill it explicitly: +`refresh_column` fills only rows added since the last refresh and recomputes rows whose inputs changed, leaving unchanged rows alone. Run the same refresh as a background job instead, so it doesn't block: - {PyQuickstartComputedFeature} + {PyQuickstartAddFeatureEnterprise} -A later `refresh_column` call fills only rows added since the last refresh and recomputes rows whose inputs changed, leaving unchanged rows alone. On LanceDB Enterprise, the equivalent refresh runs as a background job instead of blocking: +See [Create a Function](/curation/create-function) for UDFs that call external +models or services, and [Computed columns](/feature-engineering/add-computed-column) +for the SQL-expression form that doesn't need a registered Function. - - - {PyQuickstartComputedFeatureEnterprise} - - - -TypeScript and Rust declare and refresh computed columns the same way, through the same `add_columns`/`refresh_column` calls. See [Computed columns](/feature-engineering/add-computed-column) for the full refresh semantics and the automatic-refresh option. - -## 8\. Store multimodal data {#8-store-multimodal-data} +## 7\. Store multimodal data {#7-store-multimodal-data} Store images, audio, or other binary data alongside vectors and metadata, in a column of raw bytes. This creates a new table from one image file -- replace the path with one of your own: @@ -337,7 +366,7 @@ Store images, audio, or other binary data alongside vectors and metadata, in a c See [Multimodal data types](/management/table#multimodal) for larger payloads and the Blob v2 column type, which avoids loading binary data on every scan. -## 9\. Train on your data {#9-train} +## 8\. Train on your data {#8-train} Read table data into PyTorch, projecting and shuffling only the columns a training step needs: @@ -347,7 +376,7 @@ Read table data into PyTorch, projecting and shuffling only the columns a traini -`Permutation` is LanceDB's row-ordering primitive for training reads; `select_columns` projects before reading, so a training step touches only the columns it selects, not unused ones such as `caption` or `embedding`. See [Data loading](/training/data-loading) for the full `StreamingDataset` API, including resuming and multi-worker loading. +`StreamingDataset` wraps a table for PyTorch training reads; `columns` projects before reading, so a training step touches only the columns it selects, not unused ones such as `caption` or `embedding`. It works the same way against LanceDB Embedded and LanceDB Enterprise. See [PyTorch Data Loader](/training/data-loading) for shuffling, transforms, resuming, and multi-worker loading, and [Permutation](/training/permutation) for the lower-level row-ordering primitive it's built on. ## Where to go next {#next-steps} diff --git a/docs/web/reranking/index.mdx b/docs/web/reranking/index.mdx index 1de69a2a8..38efc8843 100644 --- a/docs/web/reranking/index.mdx +++ b/docs/web/reranking/index.mdx @@ -44,7 +44,7 @@ and removes it when finished. - **Python:** Install with `pip install lancedb`, save as `rerank_search.py`, then run `python rerank_search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `rerank_search.mts`, then run `node rerank_search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. diff --git a/docs/web/search/explain.mdx b/docs/web/search/explain.mdx deleted file mode 100644 index 653eecb52..000000000 --- a/docs/web/search/explain.mdx +++ /dev/null @@ -1,550 +0,0 @@ ---- -title: "Explain a query plan" -sidebarTitle: "Query Plans" -description: "Inspect query execution, identify expensive work and compare changes." -icon: "map" -availability: - embedded: available - enterprise: available ---- - -import { PyQueryPlan, TsQueryPlanBody, TsQueryPlanTail } from '/snippets/search_examples.mdx'; -import { RsExampleBody as RsQueryPlanBody, RsExampleTail as RsQueryPlanTail } from '/snippets/search_query_plan.mdx'; - -Use query plans to understand how LanceDB reads data, applies filters and uses -indexes. `explain_plan()` shows the planned operations. `analyze_plan()` runs -the query and adds measurements, including execution time and rows processed. - -## Inspect a plan or measure execution {#inspect-a-query-plan} - -| Operation | Python / Rust | TypeScript | -|:----------|:--------------|:-----------| -| Inspect the plan without executing the query | `explain_plan()` | `explainPlan()` | -| Execute the query and report runtime measurements | `analyze_plan()` | `analyzePlan()` | - -Use the first to inspect query structure and the second to investigate work -actually performed. Operator names and available measurements can differ -between LanceDB Embedded and LanceDB Enterprise. SQL provides [EXPLAIN and EXPLAIN ANALYZE](/sql/dql/explain). - - - - - -These examples use three sample records and hand-written vectors, so no -embedding service is needed. Each program creates a temporary local table -and removes it when finished. - -- **Python:** Install with `pip install lancedb`, save as `query_plan.py`, then run `python query_plan.py`. -- **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `query_plan.mts`, then run `node query_plan.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin query_plan` from the extracted directory. - - - -{PyQueryPlan} - - -{TsQueryPlanBody + "\n" + TsQueryPlanTail} - - -{RsQueryPlanBody + "\n" + RsQueryPlanTail} - - - -This tiny table demonstrates the API, not a performance benchmark. The plan -uses a scan because the example has no vector index. The following larger -example illustrates how to read scans, filters and index operations. - - - -## Read scans, filters and result retrieval {#reading-the-execution-plan} - -The recorded example below uses 1.2 million rows sampled from the -[Wikipedia dataset](https://huggingface.co/datasets/wikimedia/wikipedia). -The counts describe that run. The table initially has no indexes, so the plan -shows a scan. This Enterprise plan includes `RemoteTake` and hides storage paths -as `uri=***`. A local plan shows the dataset path instead, and fetches the result -rows with Lance's `Take` or, depending on the library version, a second -`LanceRead` whose `source` is `stream(_rowid)`. - -Let's examine a vector search query that: - -- Filters rows where `identifier` is between 0 and 1,000,000 -- Returns the top 100 matches -- Projects specific columns: `chunk_index`, `title`, and `identifier` - - -```python Python icon="python" -# explain_plan -query_explain_plan = ( - table.search(query_embed) - .where("identifier > 0 AND identifier < 1000000") - .select(["chunk_index", "title", "identifier"]) - .limit(100) - .explain_plan(True) -) -``` - -```typescript TypeScript icon="square-js" -// explain_plan -const explainPlan = await table - .search(queryEmbed) - .where("identifier > 0 AND identifier < 1000000") - .select(["chunk_index", "title", "identifier"]) - .limit(100) - .explainPlan(true); -``` - - -### Execution Plan Components {#execution-plan-components} - - - - -The execution plan reveals the sequence of operations performed to execute your query. Let's examine each component: - -``` -ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance] - RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title" - CoalesceBatchesExec: target_batch_size=1024 - GlobalLimitExec: skip=0, fetch=100 - FilterExec: _distance@3 IS NOT NULL - SortExec: TopK(fetch=100), expr=[_distance@3 ASC NULLS LAST], preserve_partitioning=[false] - KNNVectorDistance: metric=l2 - FilterExec: identifier@1 > 0 AND identifier@1 < 1000000 - LanceScan: uri=***, projection=[vector, identifier], row_id=true, row_addr=false, ordered=false -``` - -#### 1\. Base Layer (LanceScan) {#1-base-layer-lancescan} - -- Initial data scan loading only specified columns to minimize I/O -- Unordered scan enabling parallel processing - -``` -LanceScan: -- projection=[vector, identifier] -- row_id=true, row_addr=false, ordered=false -``` - -#### 2\. First Filter {#2-first-filter} - -- Apply requested filter on `identifier` column -- Reduces the number of vectors that need KNN computation - -``` -FilterExec: identifier@1 > 0 AND identifier@1 < 1000000 -``` - -#### 3\. Vector Search {#3-vector-search} - -- Computes squared L2 distances between query vector and all vectors that passed the filter - -``` -KNNVectorDistance: metric=l2 -``` - -#### 4\. Results Processing {#4-results-processing} - -- Filters out null distance results -- Sorts by distance and takes top 100 results -- Coalesces output into batches targeting 1,024 rows in this plan - -``` -SortExec: TopK(fetch=100) -- expr=[_distance@3 ASC NULLS LAST] -- preserve_partitioning=[false] -FilterExec: _distance@3 IS NOT NULL -GlobalLimitExec: skip=0, fetch=100 -CoalesceBatchesExec: target_batch_size=1024 -``` - -#### 5\. Data Retrieval {#5-data-retrieval} - -- `RemoteTake` is the deployment's operator for this step; a LanceDB Embedded plan shows Lance's `Take` or a `LanceRead` over the selected row IDs, depending on the library version -- Handles efficient data retrieval from remote storage locations -- Fetches specific rows and columns needed for the final output -- Optimizes network bandwidth by only retrieving required data - -``` -RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title" -``` - -#### 6\. Final Output {#6-final-output} - -- Returns only requested columns and maintains column ordering - -```text -ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance] -``` - -This plan demonstrates a basic search without index optimizations: it performs a full scan and filter before vector search. - - - - -## Non-vector queries {#analyzing-non-vector-queries} - -Query plans also cover filters and full-text search. Python can show both -sub-plans of a hybrid query. Check where a filter runs and how many rows flow -through each operator; a separate `FilterExec` does not by itself establish -that the plan is inefficient or that an index is missing. - -### FTS queries {#fts-queries} - - -```python Python icon="python" -plan = ( - table.search("puppy", query_type="fts") - .where("category = 'animals'", prefilter=True) - .limit(10) - .explain_plan(True) -) -print(plan) -``` - -```typescript TypeScript icon="square-js" -const plan = await table - .query() - .fullTextSearch("puppy") - .where("category = 'animals'") - .limit(10) - .explainPlan(true); -``` - - -Look for the text-index operation and any scan of unindexed rows. A scan can -be needed to include records written after the index was built. Use index -coverage and execution measurements to determine whether that extra work -matters. Check filter placement separately from text-index use. - -### Hybrid queries {#hybrid-queries} - -For hybrid queries, `explain_plan` returns the reranker label followed by the vector and FTS sub-plans, indented for readability: - - -```python Python icon="python" -plan = ( - table.search("flower moon", query_type="hybrid") - .where("category = 'film'", prefilter=True) - .limit(10) - .explain_plan(True) -) -print(plan) -# RRFReranker(...) -# -# -``` - - -`analyze_plan` executes both sub-queries and labels them `Vector Search Plan:` -and `FTS Search Plan:`. Compare their filter placement and execution measurements. - -`analyze_plan` executes the query and returns the physical plan annotated with -runtime metrics such as elapsed time, rows produced, bytes read and index comparisons. -Where [`explain_plan`](#inspect-a-query-plan) tells you what a query intends to do, -analysis shows the work performed. - - -The SQL equivalent is [`EXPLAIN ANALYZE`](/sql/dql/explain). - - -## Read execution measurements {#analyze-a-query-plan} - -Executes the query and provides detailed runtime metrics, including: - -- Operation duration (`_elapsed_compute_`) -- Data processing statistics (`_output_rows_`, `_bytes_read_`) -- Index effectiveness (`_index_comparisons_`, `_indices_loaded_`) -- Resource utilization (`_iops_`, `_requests_`) - -## Measure the example query {#performance-analysis} - -Let's use `analyze_plan` to run the query and analyze the query performance, which will help us identify potential bottlenecks: - - -```python Python icon="python" -# analyze_plan -query_analyze_plan = ( - table.search(query_embed) - .where("identifier > 0 AND identifier < 1000000") - .select(["chunk_index", "title", "identifier"]) - .limit(100) - .analyze_plan() -) -``` - -```typescript TypeScript icon="square-js" -// analyze_plan -const analyzePlan = await table - .search(queryEmbed) - .where("identifier > 0 AND identifier < 1000000") - .select(["chunk_index", "title", "identifier"]) - .limit(100) - .analyzePlan(); -``` - - -### Performance Metrics Analysis {#performance-metrics-analysis} - - - - -``` -ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance], metrics=[output_rows=100, elapsed_compute=1.424µs] - RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title", metrics=[output_rows=100, elapsed_compute=175.53097ms, output_batches=1, remote_takes=100] - CoalesceBatchesExec: target_batch_size=1024, metrics=[output_rows=100, elapsed_compute=2.748µs] - GlobalLimitExec: skip=0, fetch=100, metrics=[output_rows=100, elapsed_compute=1.819µs] - FilterExec: _distance@3 IS NOT NULL, metrics=[output_rows=100, elapsed_compute=10.275µs] - SortExec: TopK(fetch=100), expr=[_distance@3 ASC NULLS LAST], preserve_partitioning=[false], metrics=[output_rows=100, elapsed_compute=39.259451ms, row_replacements=546] - KNNVectorDistance: metric=l2, metrics=[output_rows=1099508, elapsed_compute=56.783526ms, output_batches=1076] - FilterExec: identifier@1 > 0 AND identifier@1 < 1000000, metrics=[output_rows=1099508, elapsed_compute=17.136819ms] - LanceScan: uri=***, projection=[vector, identifier], row_id=true, row_addr=false, ordered=false, metrics=[output_rows=1200000, elapsed_compute=21.348178ms, bytes_read=1852931072, iops=78, requests=78] -``` - -#### 1\. Data Loading (LanceScan) {#1-data-loading-lancescan} - -- Scanned 1,200,000 rows from the LanceDB table -- Read 1.86GB of data in 78 I/O operations -- Only loaded necessary columns (`vector` and `identifier`) -- Unordered scan for parallel processing - -#### 2\. Filtering and Search {#2-filtering-and-search} - -- Applied prefilter condition (`identifier > 0 AND identifier < 1000000`) -- Reduced dataset from 1.2M to 1,099,508 rows -- KNN search used L2 (Euclidean) distance metric -- Vector comparisons processed in 1076 batches - -#### 3\. Results Processing {#3-results-processing} - -- KNN results sorted by distance (TopK with fetch=100) -- Null distances filtered out -- Batches coalesced to target size of 1024 rows -- Additional columns fetched for final results -- Remote take operation for 100 results -- Final projection of required columns - - - - -### Distributed metrics on LanceDB Enterprise {#distributed-metrics-on-remote-tables} - -Enterprise - -When you call `analyze_plan` against a LanceDB Enterprise deployment that distributes its queries across a pool of workers, the query runs on those workers. By default the returned plan aggregates each operator's metrics into a single value, matching the single-node output of LanceDB Embedded. Pass a `distributed_metrics` mode when you need to see how work was split across workers: - -| Mode | What it shows | When to use it | -| :------------ | :---------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------ | -| `aggregate` | One summary value per operator (default). Same shape as Embedded `analyze_plan`. | Everyday performance checks and comparisons against an Embedded plan. | -| `per_worker` | Metrics reported separately for each worker that participated in the query. | Diagnosing stragglers or uneven work distribution across the cluster. | -| `full` | Both the aggregate summary and the per-worker breakdown. | Deep investigations where you need the totals *and* the per-worker detail in a single output. | - -Python exposes this option through `distributed_metrics`. In TypeScript, pass -the same mode to `analyzePlan()` as its `distributedMetrics` argument. Python -queries on LanceDB Embedded ignore the distributed mode and return single-node -measurements. - - -```python Python icon="python" -# Show a per-worker breakdown for a query on LanceDB Enterprise -plan = ( - table.search(query_embed) - .where("identifier > 0 AND identifier < 1000000") - .limit(100) - .analyze_plan(distributed_metrics="per_worker") -) -print(plan) -``` - - - - - -Use `per_worker` or `full` sparingly; the plan output grows with the size of your worker pool. Stick with the default `aggregate` mode for routine tuning. - - -### Identify expensive operations {#key-observations} - -- The query computes distances for 1,099,508 vectors; inspect timings to assess its contribution to latency -- The scan reads 1.86 GB in this recorded run -- Full table scan due to lack of indices -- Compare this scan with an indexed plan using the same query - -## Compare the query after adding indexes {#optimized-query-execution} - - - - -The recorded query after adding vector and scalar indexes produced this plan: - -``` -ProjectionExec: expr=[chunk_index@3 as chunk_index, title@4 as title, identifier@2 as identifier, _distance@0 as _distance] - RemoteTake: columns="_distance, _rowid, identifier, chunk_index, title" - CoalesceBatchesExec: target_batch_size=1024 - GlobalLimitExec: skip=0, fetch=100 - SortExec: TopK(fetch=100), expr=[_distance@0 ASC NULLS LAST], preserve_partitioning=[false] - ANNSubIndex: name=vector_idx, k=100, deltas=1 - ANNIvfPartition: uuid=83916fd5-fc45-4977-bad9-1f0737539bb9, nprobes=20, deltas=1 - ScalarIndexQuery: query=AND(identifier > 0,identifier < 1000000) -``` - -### Optimized Plan Analysis {#optimized-plan-analysis} - -#### 1\. Scalar Index Query {#1-scalar-index-query} - -``` -ScalarIndexQuery: query=AND(identifier > 0,identifier < 1000000) -metrics=[ - output_rows=2 - index_comparisons=2,301,824 - indices_loaded=2 - output_batches=1 - parts_loaded=562 - elapsed_compute=86.979354ms -] -``` - -- Range filter using scalar index -- Only 2 index files and 562 scalar index parts loaded -- 2.3M index comparisons for matches - -#### 2\. Vector Search {#2-vector-search} - -``` -ANNSubIndex: name=vector_idx, k=100, deltas=1 -metrics=[ - output_rows=2,000 - index_comparisons=25,893 - indices_loaded=0 - output_batches=20 - parts_loaded=20 - elapsed_compute=111.849043ms -] -``` - -- IVF index with 20 probes -- Only 20 index parts loaded -- 25,893 vector comparisons -- 2,000 matching vectors - -#### 3\. Results Processing {#3-results-processing-2} - -``` -SortExec: TopK(fetch=100), expr=[_distance@0 ASC NULLS LAST], preserve_partitioning=[false] -GlobalLimitExec: skip=0, fetch=100 -CoalesceBatchesExec: target_batch_size=1024 -``` - -- Sorts by distance -- Limits to top 100 results -- Batches into groups of 1024 - -#### 4\. Data Fetching {#4-data-fetching} - -``` -RemoteTake: columns="_distance, _rowid, identifier, chunk_index, title" -metrics=[output_rows=100, elapsed_compute=113.491859ms, output_batches=1, remote_takes=100] -``` - -- Single output batch -- One remote take per row - -#### 5\. Final Projection {#5-final-projection} - -``` -ProjectionExec: expr=[chunk_index@3 as chunk_index, title@4 as title, identifier@2 as identifier, _distance@0 as _distance] -``` - -- Returns specified columns: chunk_index, title, identifier, and distance - -### Performance Improvements {#performance-improvements} - -#### 1\. Initial Data Access {#1-initial-data-access} - -``` -ScalarIndexQuery metrics: -- indices_loaded=2 -- parts_loaded=562 -- output_batches=1 -``` - -- Before: Full table scan of 1.2M rows, 1.86GB data -- After: Only 2 indices and 562 scalar index parts loaded -- Benefit: Eliminated table scans for prefilter - -#### 2\. Vector Search Efficiency {#2-vector-search-efficiency} - -``` -ANNSubIndex: -- index_comparisons=25,893 -- indices_loaded=0 -- parts_loaded=20 -- output_batches=20 -``` - -- Before: L2 calculations on 1,099,508 vectors -- After: - - About 97.6% fewer vector comparisons (25,893 versus 1,099,508) - - Decreased output batches from 1,076 to 20 - -#### 3\. Data Retrieval Optimization {#3-data-retrieval-optimization} - -``` -RemoteTake: -- remote_takes=100 -- output_batches=1 -``` - -- RemoteTake operation remains consistent - - - - -## Choose a change to measure {#performance-optimization-guide} - -### 1\. Index Implementation {#1-index-implementation} - -#### When to Create Indices {#when-to-create-indices} - -- Columns used in WHERE clauses -- Vector columns for similarity searches -- Join columns used in `merge_insert` - -#### Index Type Selection {#index-type-selection} - -| Data Type | Recommended Index | Use Case | -| ----------- | ------------------ | ---------------------------------------- | -| Vector | IVF_PQ/IVF_HNSW_SQ/IVF_HNSW_FLAT | Approximate nearest neighbor search | -| Scalar | B-Tree | Equality and range filters | -| Categorical | Bitmap | Multi-value filters and set operations | -| `List` | Label_list | Multi-label classification and filtering | - - -Use `table.index_stats()` to monitor index coverage. -Unindexed rows can add scan work. Use their count alongside query measurements -to decide when index maintenance is needed. - - -### 2\. Query Plan Optimization {#2-query-plan-optimization} - -#### Common Patterns and Fixes {#common-patterns-and-fixes} - -| Plan Pattern | Optimization | -| ------------------------------------------ | -------------------------------------------- | -| Scan with high bytes read or I/O count | Check index coverage and whether the query can use an index | -| | Use `select()` to limit returned columns | -| | Check whether the dataset has been compacted | -| Multiple filters | Check their placement and row counts; compare the plan after changing the query | - - -Regularly analyze your query plans to identify and address performance -bottlenecks. The `analyze_plan` output provides detailed metrics to guide -optimization efforts. - - -### 3\. Getting Started with Optimization {#3-getting-started-with-optimization} - -Keep the query, data and result limit fixed while changing one factor. Compare -rows processed, bytes read, timings and returned results. For ANN changes, -measure recall too: doing less work is useful only if retrieval quality meets -your application's needs. See [vector indexes](/indexing/vector-index) and -[scalar indexes](/indexing/scalar-index) for index choices. diff --git a/docs/web/search/filtering.mdx b/docs/web/search/filtering.mdx index 099aea73c..58c974614 100644 --- a/docs/web/search/filtering.mdx +++ b/docs/web/search/filtering.mdx @@ -25,7 +25,7 @@ and removes it when finished. - **Python:** Install with `pip install lancedb`, save as `filtered_search.py`, then run `python filtered_search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `filtered_search.mts`, then run `node filtered_search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin filter_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin filter_search` from the extracted directory. @@ -239,10 +239,12 @@ If your column name contains special characters, upper-case characters, or is a you can use backtick (`` ` ``) to escape it. For nested fields, each segment of the path must be wrapped in backticks. -```sql + +```sql SQL icon="database" `CUBE` = 10 AND `UpperCaseName` = '3' AND `column name with space` IS NOT NULL AND `nested with space`.`inner with space` < 2 ``` + Periods separate nested fields. LanceDB does not allow a literal period in a @@ -312,4 +314,4 @@ For a recall comparison, run the same query and predicate while bypassing the vector index on a suitably sized test table. Then compare the indexed query's results and latency while changing probe or refinement settings. Increasing those settings does not guarantee a full result set. See -[vector search](/search/vector-search) and [query plans](/search/explain). +[vector search](/search/vector-search) and [query plans](/basics/sql#query-plans). diff --git a/docs/web/search/full-text-search.mdx b/docs/web/search/full-text-search.mdx index 0f9930dc3..9c17fc50b 100644 --- a/docs/web/search/full-text-search.mdx +++ b/docs/web/search/full-text-search.mdx @@ -34,7 +34,7 @@ table when finished. No embedding model is needed for a text query. - **Python:** Install with `pip install lancedb`, save as `text_search.py`, then run `python text_search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `text_search.mts`, then run `node text_search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin text_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin text_search` from the extracted directory. @@ -65,7 +65,6 @@ First, open or create the table you want to search: ```python Python icon="python" -import lancedb from lancedb.index import FTS uri = "data/sample-lancedb" @@ -225,7 +224,7 @@ on an Enterprise table. Use a metadata predicate to restrict qualifying records. See [filtering options](#filtering-options) for prefiltering and postfiltering. -Enterprise SQL provides [`fts()`](/sql/functions#fts) for scored text retrieval. +Enterprise SQL provides [`fts()`](/sql/dql/fts) for scored text retrieval. ## Configure tokenization and matching {#advanced-usage} @@ -280,9 +279,11 @@ table.create_fts_index( Model-backed tokenizers require tokenizer model files in Lance's language model home. Lance looks under the default platform data directory for `lance/language_models`, or you can set `LANCE_LANGUAGE_MODEL_HOME` to point to a different model root: -```bash + +```bash Bash icon="terminal" export LANCE_LANGUAGE_MODEL_HOME=/path/to/lance/language_models ``` + For example, `jieba/default` is resolved under `/jieba/default/...`, `lindera/ipadic` under `/lindera/ipadic/...`, and `lindera/ko-dic` under `/lindera/ko-dic/...`. @@ -418,6 +419,17 @@ LanceDB supports searching for substrings in the text column, you can set the `b | ngram_max_length | int | 3 | Maximum length of the n-grams to search for | | prefix_only | bool | false | Whether to only search for prefixes of the n-grams | +## Expected performance at scale {#expected-performance} + +Enterprise + +At 1 billion rows, LanceDB Enterprise reaches p50 62 ms and p99 274 ms on +fully cached data with no custom tuning -- a representative floor to plan +around, not a ceiling. Measured under a mixed workload of phrase, +match-any and match-all queries, with an ICU-tokenized FTS v3 index +(positions and lowercasing enabled, stemming disabled). The exact numbers +depend on your deployment's shape (cluster size, storage class, dataset); +for higher performance, talk to the sales team. ## Fuzzy Search and Boosting Example {#fuzzy-search-and-boosting-example} @@ -432,7 +444,6 @@ Run the following steps in order. They use a temporary local database with four ```python Python icon="python" from tempfile import TemporaryDirectory -import lancedb import pandas as pd from lancedb.index import FTS from lancedb.query import MatchQuery, PhraseQuery, BoostQuery, MultiMatchQuery @@ -901,8 +912,6 @@ First, create a table with sample text data and configure n-gram tokenization: ```python Python icon="python" import pyarrow as pa -import lancedb - from tempfile import TemporaryDirectory from lancedb.index import FTS @@ -980,9 +989,11 @@ assert set(r["text"] for r in results) == {"lance database", "lance is cool"} + ```python Python icon="python" directory.cleanup() ``` + @@ -1001,7 +1012,6 @@ This example uses a temporary local database. Run the steps in order. ```python Python icon="python" from tempfile import TemporaryDirectory -import lancedb import pyarrow as pa from lancedb.index import FTS from lancedb.query import MatchQuery, PhraseQuery diff --git a/docs/web/search/hybrid-search.mdx b/docs/web/search/hybrid-search.mdx index 6b769b6a8..b94d9e460 100644 --- a/docs/web/search/hybrid-search.mdx +++ b/docs/web/search/hybrid-search.mdx @@ -33,7 +33,7 @@ and removes it when finished. - **Python:** Install with `pip install lancedb`, save as `hybrid_search.py`, then run `python hybrid_search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `hybrid_search.mts`, then run `node hybrid_search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. @@ -67,7 +67,6 @@ Run the steps for your chosen language in order, choosing one connection option. ```python Python icon="python" -import lancedb from lancedb.index import FTS from lancedb.rerankers import RRFReranker from lancedb.embeddings import get_registry @@ -378,7 +377,7 @@ await table.query() ``` -In Python, use [`explain_plan`](/search/explain#analyzing-non-vector-queries) on a hybrid query to see whether the filter pushed into the scan or ran as a separate `FilterExec` step. +In Python, use [`explain_plan`](/basics/sql#analyzing-non-vector-queries) on a hybrid query to see whether the filter pushed into the scan or ran as a separate `FilterExec` step. ## Choose and evaluate a reranker {#more-on-reranking} diff --git a/docs/web/search/index.mdx b/docs/web/search/index.mdx index 86a0b1b17..3503954e6 100644 --- a/docs/web/search/index.mdx +++ b/docs/web/search/index.mdx @@ -50,7 +50,7 @@ and removes it when finished. - **Python:** Install with `pip install lancedb`, save as `search.py`, then run `python search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `search.mts`, then run `node search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. @@ -110,7 +110,7 @@ both LanceDB Embedded and LanceDB Enterprise. ## Investigate a slow query {#diagnostics} -Use [query plans](/search/explain) to see the scans, filters and indexes selected +Use [query plans](/basics/sql#query-plans) to see the scans, filters and indexes selected for a query. `explain_plan()` inspects the plan; `analyze_plan()` executes the query and reports measurements. Compare one change at a time, such as adding an index, returning fewer columns, or adjusting search parameters. diff --git a/docs/web/search/realtime-read.mdx b/docs/web/search/realtime-read.mdx index 8f51995d3..19c5bc2ab 100644 --- a/docs/web/search/realtime-read.mdx +++ b/docs/web/search/realtime-read.mdx @@ -1,18 +1,20 @@ --- -title: "Real Time reads" -sidebarTitle: "Real Time Read" +title: "RTE reads" +sidebarTitle: "RTE Read" description: "Query a table with the real time engine enabled and get writes back within milliseconds of being written, merged transparently with the base table." icon: "magnifying-glass" keywords: ["rte", "real time engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"] availability: - embedded: unavailable + embedded: available enterprise: available --- A table with the [real time engine](/tables/realtime-engine) enabled queries the same way as any other table — nothing about `search`, filtering, or SQL -changes. This page covers what you get back and how it performs; for enabling -RTE and writing to a table, see [Real Time writes](/ingestion/realtime-write). +changes. This page covers what you get back; for enabling RTE and writing to +a table, see [RTE writes](/ingestion/realtime-write). For how Enterprise +combines these results across machines, see +[Distributed RTE Read](/enterprise/distributed-real-time-read). ## Query a real time table {#query} @@ -23,7 +25,7 @@ moment ago is already reflected: ```python Python icon="python" -# continuing the `frames` table connected and written to in Real Time writes +# continuing the `frames` table connected and written to in RTE writes import numpy as np query_vector = np.random.rand(frames.schema.field("embedding").type.list_size).astype("float32") @@ -33,42 +35,50 @@ frames.search("gripper closing on a cup", fts_columns="caption").limit(10).to_li ``` -Vector, full-text, BTree, bitmap, and most other scalar indexes are maintained -on the memtable, so new rows are searchable through the index as soon as -they're written — not just after the next compaction. +By default every index on the table is RTE-maintained, re-read as the table +changes, so a new index is picked up automatically; pin a smaller set with +`RTEWriteSpec.with_maintained_indexes`. For full-text and scalar (BTree, +bitmap) indexes, a maintained index covers every tier -- base table, +SSTables, and the active memtable -- so a query rejects outright rather than +silently skipping un-compacted rows if a resident memtable predates the +index. Vector (ANN) search is maintained on the base table and SSTables the +same way, and the active memtable builds its own in-memory HNSW graph as +rows land, so writes stay vector-searchable within milliseconds too, +without waiting on a freeze into an SSTable. That graph search steps aside +for a full scan of the memtable only when it can't honor the query through +a graph -- a prefilter, a primary-key override, a distance lower bound, or +before the memtable has any index yet on a cold start. -## Read performance {#read-performance} +## Embedded: one process, one dataset {#embedded} -Reads on an RTE table stay close to those on a fully compacted table, even -with the fresh tier at its fullest before compaction. +LanceDB Embedded runs this same LSM scanner directly against the local Lance +dataset, in-process -- the identical merge-by-primary-key logic, the same +maintained-index rules for vector, full-text, and scalar search, just with no +network hop to a separate serving tier. There is no WAL node to route to and +nothing to combine across machines: a query against an RTE-enabled Embedded +table already reads the fresh tier together with the base table in one call. +See [Distributed RTE Read](/enterprise/distributed-real-time-read) for +what Enterprise adds on top when that fresh tier is served by a separate +machine from the one answering the rest of the query. -The table below compares a 5M-row table with a 128-dimension IVF-PQ index plus -BTree and FTS indexes, with and without RTE. The RTE table holds one -unflushed memtable and three SSTables, each from a 100k-row write wave, half of -which are updates to existing rows. Latencies are p50 in milliseconds. +Not every query shape runs through the LSM scanner -- a query that asks for +`with_row_id`, time travel, multiple query vectors, hybrid search, or a +handful of other combinations is rejected with a clear error asking you to +set `use_rte(False)` and read the base table only, rather than silently +returning a result that omits un-compacted rows. -| Query | Without RTE | With RTE | -| --- | --: | --: | -| Primary-key lookup | 62 | 63 | -| Vector search | 68 | 71 | -| Vector search with prefilter | 90 | 91 | -| Full-text term | 63 | 64 | -| Full-text phrase | 68 | 82 | -| Hybrid search (RRF) | 68 | 83 | -| SQL point lookup | 189 | 187 | - -Most queries are within a few milliseconds of the base table. Hybrid and phrase -queries add roughly 15 ms to merge the two tiers. +## Limitations {#limitations} -Support for all table operations on RTE tables is coming soon. Time travel, -branching, `count_rows`, row IDs (`with_row_id`), and `TABLESAMPLE` are not yet +Support for all table operations on RTE tables is coming soon. Time travel,{/* Draft until branching reaches early access: restore " branching," */} +`count_rows`, row IDs (`with_row_id`), and `TABLESAMPLE` are not yet available. ## Next steps {#next-steps} -- [Real Time writes](/ingestion/realtime-write) — enable RTE and write to a table -- [How the real time engine works](/tables/realtime-engine#how-it-works) +- [RTE writes](/ingestion/realtime-write) — enable RTE and write to a table +- [Distributed RTE Read](/enterprise/distributed-real-time-read) — combining results across machines in Enterprise +- [How the real time engine works](/tables/realtime-engine#memwal-format) - [Hybrid search](/search/hybrid-search) - [Vector search](/search/vector-search) diff --git a/docs/web/search/vector-search.mdx b/docs/web/search/vector-search.mdx index 8c43fd0e6..2c37fef43 100644 --- a/docs/web/search/vector-search.mdx +++ b/docs/web/search/vector-search.mdx @@ -48,6 +48,7 @@ import { import { PyVectorSearch, TsVectorSearchBody, TsVectorSearchTail } from '/snippets/search_examples.mdx'; import { RsExampleBody as RsVectorSearchBody, RsExampleTail as RsVectorSearchTail } from '/snippets/search_vector_search.mdx'; +import { PyVectorIndexAuto, PyVectorIndexSearchEffort, PyVectorIndexFixedProbes } from '/snippets/indexing.mdx'; Vector search finds similar items by comparing their embeddings: numerical representations of text, images, audio or other data. An embedding model maps @@ -73,7 +74,7 @@ an embedding model. The temporary table is removed when the program finishes. - **Python:** Install with `pip install lancedb`, save as `vector_search.py`, then run `python vector_search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `vector_search.mts`, then run `node vector_search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. @@ -205,7 +206,7 @@ When a vector index is used, `_distance` is not always the true distance between ### Exact vs Approximate Distances When doing vector search, the meaning of "distance" depends on whether you are using an index and whether `refine_factor` is specified as part of your query. -`nprobes` controls how many partitions are searched to find candidates, `approx_mode` controls the query-time speed/recall trade-off for RQ-quantized indexes, and `refine_factor` controls how many candidates are rescored on full vectors for better distance fidelity and reranking quality. +`nprobes` controls how many partitions are searched to find candidates, `approx_mode` controls the query-time speed/recall trade-off for RQ-quantized and filtered HNSW indexes, and `refine_factor` controls how many candidates are rescored on full vectors for better distance fidelity and reranking quality. The table below summarizes the behavior of `_distance` in search results based on your query configuration: @@ -235,33 +236,116 @@ following sections cover query-time settings. ### Tuning `approx_mode` {#tuning-approx-mode} -Use `approx_mode` when you want to adjust the speed/recall trade-off for approximate vector search at query time. This setting currently applies only to RQ-quantized indexes, such as `IVF_RQ`; other index types ignore it. +Use `approx_mode` when you want to adjust the speed/recall trade-off for approximate vector search at query time. It applies to RQ-quantized indexes, such as `IVF_RQ`, and to filtered searches on HNSW indexes. Other index types, and queries that bypass the index, ignore it. The supported values are: | Value | Behavior | | :--- | :--- | | `fast` | Prefer lower query latency, which can reduce recall. | -| `normal` | Use the default balance between query latency and recall. This only has an effect for RQ indexes built with `num_bits > 1`. | +| `normal` | Use the default balance between query latency and recall. For RQ indexes built with `num_bits=1`, this uses the same one-bit scoring path as `fast`. | | `accurate` | Prefer higher recall, which can increase query latency. | -Only the Rust SDK sets `approx_mode`; the Python and TypeScript SDKs do not expose it. You can change `approx_mode` per query without rebuilding the index. For RQ indexes built with `num_bits=1`, `normal` uses the same one-bit scoring path as `fast`. If you also set `refine_factor`, LanceDB first uses `approx_mode` while finding candidates, then reranks the selected candidates on full vectors. +`approx_mode` defaults to `normal` and can change per query without rebuilding the index. The Python and Rust APIs call it `approx_mode`, and the TypeScript API calls it `approxMode`. On HNSW, `fast` enables ACORN traversal only when a filter leaves a non-trivial subset of rows; unfiltered or all-row searches use the regular traversal, and very selective filters may use an exact scan instead. If you also set `refine_factor`, LanceDB first uses `approx_mode` while finding candidates, then reranks the selected candidates on full vectors. -### Tuning `nprobes` +### Tuning `nprobes` {#tuning-nprobes} -- `nprobes` controls how many partitions are searched at query time. -- `nprobes` improves candidate recall, but does not by itself make `_distance` exact. -- The default probe selection is a starting point. Measure recall and latency for your data before overriding it. -- In most cases, leave `nprobes` unset and use the auto-tuned value. -- Only tune `nprobes` manually when recall is below your target, or when you need even higher performance for your workload. -- If recall is too low, increase `nprobes` gradually, but after a certain threshold, increasing `nprobes` yields only marginal accuracy gains. -- If you need higher performance and have recall headroom, decrease `nprobes` gradually. +For IVF vector indices, start with **Auto** by leaving the probe settings unset. +LanceDB chooses how many partitions to search to balance recall and latency. It +can search further if a filter leaves too few results, within any limits you set. -For filtered ANN searches, you can also set `minimum_nprobes` and `maximum_nprobes`. LanceDB starts -with the minimum and can scan more partitions up to the maximum if the filter leaves too few -candidates. Calling `nprobes(n)` fixes both values to `n`, which disables that adaptive behavior. -Whether a deployment honors this range depends on its version; one that does not searches exactly -`minimum_nprobes` partitions. +The examples below assume `table` has an IVF index and `query_vector` uses the +same embedding model and dimension as its vectors. + + +{PyVectorIndexAuto} + + +#### Adjust speed and recall {#search-effort-and-probe-bounds} + +Use `search_effort` to tune how much work a search does. It accepts values from +`0` to `1`; `0.5` uses Auto. Increase it to search more partitions when recall is +too low, or decrease it when you can trade some recall for lower latency. +`search_effort(0.95)` does **not** mean 95% recall. + +SDK builds using Lance 15.0.0-beta.11 or later provide these calibrated tiers: + +| Effort | Empirical mean partition-routing target | +| :--- | :--- | +| `0.1` | 80% | +| `0.25` | 90% | +| `0.5` (default) | Approximately 95%; existing Auto behavior | + +The probe budget adapts to the distance metric and requested `k`, so you can +keep the same effort when changing the result count. The lower tiers were +calibrated for `l2`, `cosine` and `dot` through `k=100000`. This is the tested +range, not a limit on `k`; Hamming and larger requests remain uncalibrated. + +These are average routing objectives, not guarantees for each query or final +Recall@k. Quantization, filtering and explicit probe bounds can lower final +recall. Remote queries require a server with the corresponding Lance version; +upgrading only the client does not change server-side routing. + + +{PyVectorIndexSearchEffort} + + +Measure the effect on your queries. Higher effort may add latency without +improving recall. With no maximum set, `search_effort(1)` searches all partitions +and can be expensive. In TypeScript, the method is named `searchEffort`. + +#### Set probe limits {#probes-per-segment} + +Use explicit probe counts when you have measured a suitable range for your +workload: + +| Parameter | When to use it | +| :--- | :--- | +| `minimum_nprobes` | Set a lower bound on how many partitions to search. Auto may search more from the start. | +| `maximum_nprobes` | Cap the number of partitions searched, including additional searches needed to fill the result count. A low cap can reduce recall or return fewer results than requested. | +| `nprobes` | Search a fixed number of partitions instead of using Auto. Useful for comparing settings in a benchmark. | + +Counts apply **per index segment**, not to the entire query. With many segments, +more probes can mean substantially more data reads and cache-fill writes. A +probe cap is not a limit on total latency or I/O. + +Use positive counts and keep the minimum no larger than the maximum. Leave the +maximum unset to allow further searching as needed. If filtered queries return +too few results, raise or remove that cap; see the +[bounded-search example](/indexing/vector-index#probe-limits-example). + + +{PyVectorIndexFixedProbes} + + +Prefer choosing either effort or a fixed count. If both are set, explicit +`search_effort` overrides `nprobes`. Explicit min/max bounds still apply; +setting them equal fixes the count. + +#### Check result quality {#measure-auto-probe-recall} + +Auto was tuned toward roughly **95% average recall** in benchmark tests. That +is a starting point, not a guarantee for your data or every query. Returning +`k` results also does not mean they are the true nearest `k` neighbors. + +[Measure recall](/indexing/vector-index#measuring-vector-recall) on representative +queries against an exact search with the same metric and filter. Test the settings +you intend to use: an Auto search capped at 50 probes can search fewer partitions +than fixed `nprobes(50)`, so the two can have different recall. + +If more probes stop improving quality, try increasing `refine_factor` or using +a higher-precision index. More probes do not remove quantization error, and +refinement can only rerank the candidates the search finds. + + +The Python examples use APIs available in LanceDB 0.41.0. Remote queries need +server support too. Older clients may send fixed probe settings by default; +upgrading the server alone does not switch those requests to Auto. + +Auto's calibration covers `l2`, `cosine` and `dot` searches up to `k=100000`. +For Hamming or larger requests, measure quality and latency on your workload +before relying on the defaults. + ### Vector Search with Prefiltering @@ -317,9 +401,6 @@ the filter condition after obtaining the nearest neighbors based on vector simil Use multivector search when your documents contain multiple embeddings and you need sophisticated matching between query and document vector pairs. The late interaction approach finds the most relevant combinations across all available embeddings and provides nuanced similarity scoring. -Only `cosine` similarity is supported as the distance metric for multivector search operations. -Every query vector must match the inner dimension of the multivector column. - {MultivectorSearch} @@ -328,7 +409,8 @@ Every query vector must match the inner dimension of the multivector column. Here you can see how to take 2 query vectors and find the best matching pairs between them and document vectors using late interaction. The `np.random.random(size=(2, 256))` creates a 2×256 array with two random query vectors, `.limit(5)` returns the top 5 best document-query combinations, and `.to_pandas()` provides results in a DataFrame format. -**Read more:** [Multivector search walkthrough](#multivector) +For the supported metric, how scoring works and a complete example, see the +[multivector search walkthrough](#multivector). ## Advanced Search Scenarios @@ -433,6 +515,18 @@ scan, which can reduce query time but omit recent records. Use this option only when results from indexed data are sufficient. +### Expected performance at scale {#expected-performance} + +Enterprise + +At 1 billion rows, LanceDB Enterprise reaches p50 28 ms and p99 58 ms on +fully cached data with no custom tuning -- a representative floor to plan +around, not a ceiling. Measured with 1,536-dimensional embeddings, an +IVF-RQ index, `nprobe=8`, `k=100`, on the best-performing configuration +tested at that scale. The exact numbers depend on your deployment's shape +(cluster size, storage class, dataset); for higher performance, talk to +the sales team. + ## Search without a vector index {#brute-force-search} ### Search With No Index @@ -495,7 +589,7 @@ This approach is particularly useful when: - Calculating recall metrics to tune index parameters - Ensuring exact results for critical applications -## Multi-vector search {#multivector} +## Multivector search walkthrough {#multivector} LanceDB's multivector support enables you to store and search multiple vector embeddings for a single item. @@ -537,25 +631,26 @@ $Q$ represents the query embeddings, and $D = \{d_1, d_2, ..., d_{|D|}\}$ repres ### Using Multivector Search -#### 1. Setup +#### 1\. Setup -Connect to LanceDB and import the required libraries. +Connect to a local LanceDB database and import the required libraries. ```python Python icon="python" -import lancedb import numpy as np import pyarrow as pa -db = lancedb.connect( - uri="db://your-project-slug", - api_key="your-api-key", - region="your-region" -) +db = lancedb.connect("data/multivector_demo") ``` -#### 2. Define Schema + +To run this walkthrough on LanceDB Enterprise, connect with +`lancedb.connect(uri="db://your-database", api_key="your-api-key", region="your-region")` +instead. The remaining steps are the same. + + +#### 2\. Define Schema Define a schema that specifies a multivector field. A multivector field is a nested list structure in which each document contains multiple vectors. In this case, we'll create a schema with: @@ -567,7 +662,6 @@ Define a schema that specifies a multivector field. A multivector field is a nes ```python Python icon="python" -db = lancedb.connect("data/multivector_demo") schema = pa.schema( [ pa.field("id", pa.int64()), @@ -578,7 +672,7 @@ schema = pa.schema( ``` -#### 3. Generate Multivectors +#### 3\. Generate Multivectors Generate sample data where each document contains multiple vector embeddings, which can represent different aspects or views of the same document. @@ -596,7 +690,7 @@ data = [ ``` -#### 4. Create a Table +#### 4\. Create a Table Create a table with the defined schema and sample data, which will store multiple vectors per document for similarity search. @@ -606,7 +700,7 @@ tbl = db.create_table("multivector_example", data=data, schema=schema) ``` -#### 5. Build an Index +#### 5\. Build an Index Only cosine similarity is supported for multivector search operations. For faster search, build the standard `IVF_PQ` index over your vectors: @@ -626,7 +720,7 @@ In LanceDB Embedded, the query will just run, so a large unindexed multivector t On LanceDB Cloud, the brute-force KNN safety check applies a stricter row threshold to multivector columns; roughly 10× lower than for single-vector columns. So an unindexed multivector table can be rejected with a "vector search would use brute-force KNN" error well before a comparable single-vector table would. LanceDB Enterprise doesn't have the limit. Build the index before you start hitting it from production traffic, even if the dataset is small enough that you'd skip indexing for a single-vector workload. -#### 6. Query a Single Vector +#### 6\. Query a Single Vector When searching with a single query vector, it will be compared against all vectors in each document, and the similarity scores will be aggregated to find the most relevant documents. @@ -637,7 +731,7 @@ results_single = tbl.search(query).limit(5).to_pandas() ``` -#### 7. Query Multiple Vectors +#### 7\. Query Multiple Vectors With multiple query vectors, LanceDB calculates similarity using late interaction, a late-interaction technique that computes relevance by finding the best-matching pairs between query and document vectors. This approach provides more nuanced matching while maintaining fast retrieval speeds. @@ -649,7 +743,7 @@ results_multi = tbl.search(query_multi).limit(5).to_pandas() -Visit the [Hugging Face embedding integration](/integrations/embedding/huggingface/) page for information on embedding models. +Visit the [HuggingFace embedding integration](/integrations/embedding/huggingface/) page for information on embedding models. ### Simple Example: ColBERT Embeddings @@ -659,15 +753,16 @@ token-to-token similarities (MaxSim) across them. Install the dependencies before running this example: -```bash + +```bash Bash icon="terminal" pip install pylate lancedb pandas ``` + ```python Python icon="python" import numpy as np import pyarrow as pa -import lancedb from pylate import models ## 1) Load a late-interaction model via PyLate diff --git a/docs/web/snippets/build_with_ai_agents.mdx b/docs/web/snippets/build_with_ai_agents.mdx deleted file mode 100644 index 1a82d6fb6..000000000 --- a/docs/web/snippets/build_with_ai_agents.mdx +++ /dev/null @@ -1,7 +0,0 @@ -{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} - -export const PyCamelotBatches = "import json\nfrom collections.abc import Iterator\nfrom pathlib import Path\n\n\ndef validated_batches(\n input_path: Path, batch_size: int\n) -> Iterator[list[dict]]:\n raw_records = json.loads(input_path.read_text())\n asset_root = input_path.parent.parent\n batch: list[dict] = []\n\n for raw in raw_records:\n payload = dict(raw)\n image_path = asset_root / payload.pop(\"img\")\n payload[\"image_filename\"] = image_path.name\n payload[\"image\"] = image_path.read_bytes()\n\n character = Character.model_validate(payload)\n batch.append(character.model_dump(mode=\"python\"))\n\n if len(batch) == batch_size:\n yield batch\n batch = []\n\n if batch:\n yield batch\n"; - -export const PyCamelotOssIngestion = "import lancedb\n\n\ndef ingest_oss(\n input_path: Path,\n uri: str = \"data/camelot.lancedb\",\n table_name: str = \"camelot_multimodal\",\n batch_size: int = 64,\n):\n db = lancedb.connect(uri)\n if table_name in db.list_tables():\n raise ValueError(\n f\"Table {table_name!r} already exists. Choose a fresh table name.\"\n )\n\n table = db.create_table(table_name, schema=Character)\n for batch in validated_batches(input_path, batch_size):\n table.add(batch)\n\n table.optimize()\n return table\n\n\nif __name__ == \"__main__\":\n ingest_oss(Path(\"data/camelot.json\"))\n"; - -export const PyCamelotSchema = "from lancedb.pydantic import LanceModel\nfrom pydantic import ConfigDict\n\n\nclass Stats(LanceModel):\n model_config = ConfigDict(strict=True, extra=\"forbid\")\n\n strength: int\n courage: int\n magic: int\n wisdom: int\n\n\nclass Character(LanceModel):\n model_config = ConfigDict(strict=True, extra=\"forbid\")\n\n id: int\n name: str\n role: str\n description: str\n stats: Stats\n image_filename: str\n image: bytes\n"; diff --git a/docs/web/snippets/connection.mdx b/docs/web/snippets/connection.mdx index c145c1fb6..fd8164ecf 100644 --- a/docs/web/snippets/connection.mdx +++ b/docs/web/snippets/connection.mdx @@ -4,9 +4,9 @@ export const PyConnect = "import lancedb\n\nuri = \"ex_lancedb\"\ndb = lancedb.c export const PyConnectAsync = "import lancedb\n\nuri = \"ex_lancedb\"\nasync_db = await lancedb.connect_async(uri)\n"; -export const PyConnectEnterprisePlaceholders = "import lancedb\n\ndb = lancedb.connect(\n uri=\"db://your-database\",\n api_key=\"your-api-key\",\n region=\"us-east-1\",\n host_override=\"https://your-endpoint\",\n)\n"; +export const PyConnectEnterprisePlaceholders = "import lancedb\n\ndb = lancedb.connect(\n uri=\"db://your-database\",\n api_key=\"your-api-key\",\n region=\"us-east-1\",\n host_override=\"https://your-endpoint\",\n sql_host_override=\"grpc+tls://your-sql-endpoint:10026\",\n)\n"; -export const PyConnectEnterpriseQuickstart = "import os\n\nimport lancedb\n\ndb = lancedb.connect(\n uri=os.environ[\"LANCEDB_URI\"], # db://your-database\n api_key=os.environ[\"LANCEDB_API_KEY\"],\n region=os.environ.get(\"LANCEDB_REGION\", \"us-east-1\"),\n host_override=os.environ[\"LANCEDB_HOST_OVERRIDE\"], # https://your-endpoint\n)\n"; +export const PyConnectEnterpriseQuickstart = "import os\n\nimport lancedb\n\ndb = lancedb.connect(\n uri=os.environ[\"LANCEDB_URI\"], # db://your-database\n api_key=os.environ[\"LANCEDB_API_KEY\"],\n region=os.environ.get(\"LANCEDB_REGION\", \"us-east-1\"),\n host_override=os.environ[\"LANCEDB_HOST_OVERRIDE\"], # https://your-endpoint\n sql_host_override=os.environ[\"LANCEDB_SQL_HOST_OVERRIDE\"],\n)\n"; export const PyConnectObjectStorage = "import lancedb\n\nuri = \"s3://your-bucket/path\"\n# You can also use \"gs://your-bucket/path\" or \"az://your-container/path\".\ndb = lancedb.connect(uri)\n"; @@ -24,9 +24,9 @@ export const TsConnectEnterpriseQuickstart = "const setting = (name: string) => export const TsConnectObjectStorage = "const uri = \"s3://your-bucket/path\";\n// You can also use \"gs://your-bucket/path\" or \"az://your-container/path\".\nconst db = await lancedb.connect(uri);\n"; -export const TsNamespaceAdminOps = "const db = await lancedb.connectNamespace(\"dir\", { root: \"./local_lancedb\" });\nconst namespace = [\"prod\", \"search\"];\n\nawait db.createNamespace([\"prod\"]);\nawait db.createNamespace([\"prod\", \"search\"]);\n\nconst childNamespaces = (await db.listNamespaces([\"prod\"])).namespaces;\nconsole.log(`Child namespaces under ${JSON.stringify(namespace)}:`, childNamespaces);\n// Child namespaces under [\"prod\",\"search\"]: [ 'search' ]\n\nconst metadata = await db.describeNamespace([\"prod\", \"search\"]);\nconsole.log(`Metadata for namespace ${JSON.stringify(namespace)}:`, metadata);\n\nawait db.dropNamespace([\"prod\", \"search\"], { mode: \"skip\" });\nawait db.dropNamespace([\"prod\"], { mode: \"skip\" });\n"; +export const TsNamespaceAdminOps = "async function collectNames(items: AsyncIterable): Promise {\n const names: string[] = [];\n for await (const name of items) names.push(name);\n return names;\n}\n\nconst db = await lancedb.connectNamespace(\"dir\", { root: \"./local_lancedb\" });\nconst namespace = [\"prod\", \"search\"];\n\nawait db.createNamespace([\"prod\"]);\nawait db.createNamespace([\"prod\", \"search\"]);\n\nconst childNamespaces = await collectNames(db.listNamespaces([\"prod\"]));\nconsole.log(\n `Child namespaces under ${JSON.stringify(namespace)}:`,\n childNamespaces,\n);\n// Child namespaces under [\"prod\",\"search\"]: [ 'search' ]\n\nconst metadata = await db.describeNamespace([\"prod\", \"search\"]);\nconsole.log(`Metadata for namespace ${JSON.stringify(namespace)}:`, metadata);\n\nawait db.dropNamespace([\"prod\", \"search\"], { mode: \"skip\" });\nawait db.dropNamespace([\"prod\"], { mode: \"skip\" });\n"; -export const TsNamespaceTableOps = "const db = await lancedb.connectNamespace(\"dir\", { root: \"./local_lancedb\" });\n\n// Create namespace tree: prod/search and prod/recommendations\nawait db.createNamespace([\"prod\"], { mode: \"exist_ok\" });\nawait db.createNamespace([\"prod\", \"search\"], { mode: \"exist_ok\" });\nawait db.createNamespace([\"prod\", \"recommendations\"], { mode: \"exist_ok\" });\n\nawait db.createTable(\n \"user\",\n [{ id: 1, vector: [0.1, 0.2], name: \"alice\" }],\n [\"prod\", \"search\"],\n { mode: \"create\" }, // use \"overwrite\" only if you want to replace existing table\n);\n\nawait db.createTable(\n \"user\",\n [{ id: 2, vector: [0.3, 0.4], name: \"bob\" }],\n [\"prod\", \"recommendations\"],\n { mode: \"create\" },\n);\n\n// Verify\nconsole.log((await db.listNamespaces()).namespaces); // [\"prod\"]\nconsole.log((await db.listNamespaces([\"prod\"])).namespaces); // [\"recommendations\", \"search\"]\nconsole.log(await db.tableNames([\"prod\", \"search\"])); // [\"user\"]\nconsole.log(await db.tableNames([\"prod\", \"recommendations\"])); // [\"user\"]\n"; +export const TsNamespaceTableOps = "async function collectNames(items: AsyncIterable): Promise {\n const names: string[] = [];\n for await (const name of items) names.push(name);\n return names;\n}\n\nconst db = await lancedb.connectNamespace(\"dir\", { root: \"./local_lancedb\" });\n\n// Create namespace tree: prod/search and prod/recommendations\nawait db.createNamespace([\"prod\"], { mode: \"exist_ok\" });\nawait db.createNamespace([\"prod\", \"search\"], { mode: \"exist_ok\" });\nawait db.createNamespace([\"prod\", \"recommendations\"], { mode: \"exist_ok\" });\n\nawait db.createTable(\n \"user\",\n [{ id: 1, vector: [0.1, 0.2], name: \"alice\" }],\n [\"prod\", \"search\"],\n { mode: \"create\" }, // use \"overwrite\" only if you want to replace existing table\n);\n\nawait db.createTable(\n \"user\",\n [{ id: 2, vector: [0.3, 0.4], name: \"bob\" }],\n [\"prod\", \"recommendations\"],\n { mode: \"create\" },\n);\n\n// Verify\nconsole.log(await collectNames(db.listNamespaces())); // [\"prod\"]\nconsole.log(await collectNames(db.listNamespaces([\"prod\"]))); // [\"recommendations\", \"search\"]\nconsole.log(await db.tableNames([\"prod\", \"search\"])); // [\"user\"]\nconsole.log(await db.tableNames([\"prod\", \"recommendations\"])); // [\"user\"]\n"; export const RsConnect = "let db = connect(\"ex_lancedb\").execute().await?;\n"; diff --git a/docs/web/snippets/curation_sampling.mdx b/docs/web/snippets/curation_sampling.mdx index 9c3d482b8..62af48e18 100644 --- a/docs/web/snippets/curation_sampling.mdx +++ b/docs/web/snippets/curation_sampling.mdx @@ -1,4 +1,4 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PySampleDataset = "from tempfile import TemporaryDirectory\n\nimport lancedb\nfrom lancedb.permutation import Permutation, permutation_builder\n\nwith TemporaryDirectory(prefix=\"lancedb-sampling-\") as uri:\n db = lancedb.connect(uri)\n table = db.create_table(\"records\", [{\"id\": i} for i in range(10)])\n splits = (\n permutation_builder(table).split_random(counts=[3, 7], seed=42).execute()\n )\n sample = Permutation.from_tables(table, splits, split=0).with_format(\"arrow\")\n selected_ids = []\n for batch in sample.iter(batch_size=3):\n selected_ids.extend(batch.column(\"id\").to_pylist())\n print(f\"Selected {len(selected_ids)} rows: {selected_ids}\")\n"; +export const PySampleDataset = "table = db.create_table(\"records\", [{\"id\": i} for i in range(10)])\nsplits = (\n permutation_builder(table).split_random(counts=[3, 7], seed=42).execute()\n)\nsample = Permutation.from_tables(table, splits, split=0).with_format(\"arrow\")\nselected_ids = []\nfor batch in sample.iter(batch_size=3):\n selected_ids.extend(batch.column(\"id\").to_pylist())\nprint(f\"Selected {len(selected_ids)} rows: {selected_ids}\")\n"; diff --git a/docs/web/snippets/embedding.mdx b/docs/web/snippets/embedding.mdx index da3388ea7..b7971a0f7 100644 --- a/docs/web/snippets/embedding.mdx +++ b/docs/web/snippets/embedding.mdx @@ -1,6 +1,6 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyAsyncOpenaiEmbeddings = "db = await lancedb.connect_async(uri)\nfunc = get_registry().get(\"openai\").create(name=\"text-embedding-ada-002\")\n\nclass Words(LanceModel):\n text: str = func.SourceField()\n vector: Vector(func.ndims()) = func.VectorField()\n\ntable = await db.create_table(\"words\", schema=Words, mode=\"overwrite\")\nawait table.add([{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}])\n\nquery = \"greetings\"\nactual = await (await table.search(query)).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n"; +export const PyAsyncOpenaiEmbeddings = "import lancedb\n\ndb = await lancedb.connect_async(uri)\nfunc = get_registry().get(\"openai\").create(name=\"text-embedding-ada-002\")\n\nclass Words(LanceModel):\n text: str = func.SourceField()\n vector: Vector(func.ndims()) = func.VectorField()\n\ntable = await db.create_table(\"words\", schema=Words, mode=\"overwrite\")\nawait table.add([{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}])\n\nquery = \"greetings\"\nactual = await (await table.search(query)).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n"; export const PyCreateEmbeddingFunction = "func = get_registry().get(\"openai\").create(\n name=\"text-embedding-3-small\",\n max_retries=7,\n)\n"; @@ -8,11 +8,11 @@ export const PyEmbeddingFunction = "from functools import cached_property\n\nfro export const PyImports = "from lancedb.pydantic import LanceModel, Vector\nfrom lancedb.embeddings import get_registry\n"; -export const PyManualQueryEmbeddings = "db = lancedb.connect(\"/tmp/db\")\nfunc = get_registry().get(\"openai\").create(name=\"text-embedding-ada-002\")\n\nclass Words(LanceModel):\n text: str = func.SourceField()\n vector: Vector(func.ndims()) = func.VectorField()\n\ntable = db.create_table(\"words\", schema=Words, mode=\"overwrite\")\ntable.add([{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}])\n\nquery_vector = func.generate_embeddings([\"greetings\"])[0]\n# --8<-- [start:manual_query_search]\n# query_vector is assumed to already be generated by your embedding function\nactual = table.search(query_vector).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n# --8<-- [end:manual_query_search]\n"; +export const PyManualQueryEmbeddings = "import lancedb\n\ndb = lancedb.connect(\"/tmp/db\")\nfunc = get_registry().get(\"openai\").create(name=\"text-embedding-ada-002\")\n\nclass Words(LanceModel):\n text: str = func.SourceField()\n vector: Vector(func.ndims()) = func.VectorField()\n\ntable = db.create_table(\"words\", schema=Words, mode=\"overwrite\")\ntable.add([{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}])\n\nquery_vector = func.generate_embeddings([\"greetings\"])[0]\n# --8<-- [start:manual_query_search]\n# query_vector is assumed to already be generated by your embedding function\nactual = table.search(query_vector).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n# --8<-- [end:manual_query_search]\n"; export const PyManualQuerySearch = "# query_vector is assumed to already be generated by your embedding function\nactual = table.search(query_vector).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n"; -export const PyOpenaiEmbeddings = "db = lancedb.connect(\"/tmp/db\")\nfunc = get_registry().get(\"openai\").create(name=\"text-embedding-ada-002\")\n\nclass Words(LanceModel):\n text: str = func.SourceField()\n vector: Vector(func.ndims()) = func.VectorField()\n\ntable = db.create_table(\"words\", schema=Words, mode=\"overwrite\")\ntable.add([{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}])\n\nquery = \"greetings\"\nactual = table.search(query).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n"; +export const PyOpenaiEmbeddings = "import lancedb\n\ndb = lancedb.connect(\"/tmp/db\")\nfunc = get_registry().get(\"openai\").create(name=\"text-embedding-ada-002\")\n\nclass Words(LanceModel):\n text: str = func.SourceField()\n vector: Vector(func.ndims()) = func.VectorField()\n\ntable = db.create_table(\"words\", schema=Words, mode=\"overwrite\")\ntable.add([{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}])\n\nquery = \"greetings\"\nactual = table.search(query).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n"; export const PyRegisterDevice = "import torch\n\nregistry = get_registry()\nif torch.cuda.is_available():\n registry.set_var(\"device\", \"cuda\")\n\nfunc = registry.get(\"huggingface\").create(device=\"$var:device:cpu\")\n"; diff --git a/docs/web/snippets/function.mdx b/docs/web/snippets/function.mdx index fb7f907c3..ec1ad2820 100644 --- a/docs/web/snippets/function.mdx +++ b/docs/web/snippets/function.mdx @@ -4,13 +4,15 @@ export const PyFunctionApply = "from lancedb import col\n\ntable.add_columns({\" export const PyFunctionClassApply = "from lancedb import col\n\napplication = embedder(text=col(\"text\"), model=\"all-mpnet-base-v2\")\n"; -export const PyFunctionClassDefine = "@udf(pip=[\"sentence-transformers\"])\nclass embed:\n def __init__(self, model: str = \"all-MiniLM-L6-v2\"):\n # Runs on the worker, once per instance: only the worker needs the package.\n from sentence_transformers import SentenceTransformer\n\n self.model = SentenceTransformer(model)\n\n def __call__(self, text: str) -> list[float]:\n return self.model.encode(text).tolist()\n\n def close(self):\n del self.model\n"; +export const PyFunctionClassDefine = "@function(pip=[\"sentence-transformers\"])\nclass embed:\n def __init__(self, model: str = \"all-MiniLM-L6-v2\"):\n # Runs on the worker, once per instance: only the worker needs the package.\n from sentence_transformers import SentenceTransformer\n\n self.model = SentenceTransformer(model)\n\n def __call__(self, text: str) -> list[float]:\n return self.model.encode(text).tolist()\n\n def close(self):\n del self.model\n"; -export const PyFunctionConnect = "import os\n\nimport lancedb\n\ndb = lancedb.connect(\n uri=os.environ[\"LANCEDB_URI\"], # db://your-database\n api_key=os.environ[\"LANCEDB_API_KEY\"],\n region=os.environ.get(\"LANCEDB_REGION\", \"us-east-1\"),\n host_override=os.environ[\"LANCEDB_HOST_OVERRIDE\"],\n)\n"; +export const PyFunctionClassRegister = "embedder = db.create_function_async(embed).wait()\n"; + +export const PyFunctionConnect = "import os\n\nimport lancedb\n\ndb = lancedb.connect(\n uri=os.environ[\"LANCEDB_URI\"], # db://your-database\n api_key=os.environ[\"LANCEDB_API_KEY\"],\n region=os.environ.get(\"LANCEDB_REGION\", \"us-east-1\"),\n host_override=os.environ[\"LANCEDB_HOST_OVERRIDE\"],\n sql_host_override=os.environ[\"LANCEDB_SQL_HOST_OVERRIDE\"],\n)\n"; export const PyFunctionCreateTable = "import pyarrow as pa\n\nschema = pa.schema([pa.field(\"value\", pa.float64(), nullable=False)])\ntable = db.create_table(\n \"function_demo\",\n [{\"value\": 1.0}, {\"value\": 2.0}, {\"value\": 3.0}],\n schema=schema,\n)\n"; -export const PyFunctionDefine = "from lancedb import udf\n\n\n@udf\ndef double(value: float) -> float:\n return value * 2\n"; +export const PyFunctionDefine = "from lancedb import function\n\n\n@function\ndef double(value: float) -> float:\n return value * 2\n"; export const PyFunctionInspect = "rows = table.search().select([\"value\", \"doubled\"]).to_list()\nprint(sorted((row[\"value\"], row[\"doubled\"]) for row in rows))\n# [(1.0, 2.0), (2.0, 4.0), (3.0, 6.0)]\n"; diff --git a/docs/web/snippets/indexing.mdx b/docs/web/snippets/indexing.mdx index 34e9b72f7..dfa43b6ce 100644 --- a/docs/web/snippets/indexing.mdx +++ b/docs/web/snippets/indexing.mdx @@ -40,11 +40,13 @@ export const PyScalarIndexWait = "index_name = \"label_idx\"\ntable.wait_for_ind export const PyVectorIndexAsyncConfig = "import lancedb\nimport numpy as np\nfrom lancedb.index import IvfPq\n\nasync def main():\n data = [\n {\"id\": i, \"vector\": np.random.random(8).astype(np.float32).tolist()}\n for i in range(512)\n ]\n\n db = await lancedb.connect_async(\"ex_lancedb\")\n table = await db.create_table(\n \"vector_index_async\", data=data, mode=\"overwrite\"\n )\n\n await table.create_index(\n \"vector\",\n config=IvfPq(\n distance_type=\"cosine\",\n num_partitions=16,\n num_sub_vectors=4,\n ),\n )\n return await table.list_indices()\n"; +export const PyVectorIndexAuto = "# Start with Auto.\nauto = table.search(query_vector).limit(10).to_arrow()\n"; + export const PyVectorIndexBinaryAddData = "table.add(data)\n"; export const PyVectorIndexBinaryBuildIndex = "table.create_index(\n metric=\"hamming\",\n vector_column_name=\"vector\",\n index_type=\"IVF_FLAT\",\n)\n"; -export const PyVectorIndexBinarySchema = "table = tmp_db.create_table(table_name, schema=schema, mode=\"overwrite\")\n"; +export const PyVectorIndexBinarySchema = "table = db.create_table(table_name, schema=schema, mode=\"overwrite\")\n"; export const PyVectorIndexBinarySearch = "query = np.random.randint(0, 2, size=ndim)\nquery = np.packbits(query)\ndf = table.search(query).metric(\"hamming\").limit(10).to_pandas()\ndf.vector = df.vector.apply(np.unpackbits)\n"; @@ -62,13 +64,17 @@ export const PyVectorIndexCustomName = "# Override the default `{column}_idx` co export const PyVectorIndexDistanceRange = "# Only return results whose distance falls within [0.0, 0.5).\n# Useful for near-duplicate detection or thresholded similarity search.\n(\n table.search(np.random.random(128))\n .distance_range(lower_bound=0.0, upper_bound=0.5)\n .limit(10)\n .to_pandas()\n)\n"; +export const PyVectorIndexFixedProbes = "# Use a fixed probe count.\nfixed = table.search(query_vector).nprobes(20).limit(10).to_arrow()\n"; + export const PyVectorIndexNestedField = "# The vector column `embedding` is nested inside the `image` struct.\n# Pass its full dotted path as `vector_column_name`; the same path is used\n# at query time and is what `list_indices()` reports under `columns`.\ntable.create_index(\n vector_column_name=\"image.embedding\",\n num_partitions=1,\n num_sub_vectors=1,\n name=\"image_embedding_idx\",\n)\n\nresults = (\n table.search([0.0, 1.0], vector_column_name=\"image.embedding\")\n .limit(1)\n .to_list()\n)\n"; -export const PyVectorIndexNprobes = "# Always scan 10 partitions; scan up to 50 only if the initial pass\n# returns fewer than `limit` results (common with narrow filters).\n(\n table.search(np.random.random(128))\n .minimum_nprobes(10)\n .maximum_nprobes(50)\n .where(\"id > 100\")\n .limit(5)\n .to_pandas()\n)\n"; +export const PyVectorIndexNprobes = "# Let Auto choose between 10 and 50 partitions per segment, if available.\nfiltered = (\n table.search(query_vector)\n .minimum_nprobes(10)\n .maximum_nprobes(50)\n .where(\"id > 100\")\n .limit(5)\n .to_arrow()\n)\n"; export const PyVectorIndexQueryHnsw = "tbl = table\ntbl.search(np.random.random((16))).limit(2).to_pandas()\n"; export const PyVectorIndexQueryIvf = "tbl = table\ntbl.search(np.random.random((1536))).limit(2).nprobes(20).refine_factor(\n 10\n).to_pandas()\n"; +export const PyVectorIndexSearchEffort = "# Search more partitions to try to improve recall.\nhigher_effort = table.search(query_vector).search_effort(0.75).limit(10).to_arrow()\n"; + export const PyVectorIndexSetup = "table_name = \"vector-index-tbl\"\ntable = db.open_table(table_name)\n"; diff --git a/docs/web/snippets/ingestion_examples.mdx b/docs/web/snippets/ingestion_examples.mdx index 0268a906a..f6169de52 100644 --- a/docs/web/snippets/ingestion_examples.mdx +++ b/docs/web/snippets/ingestion_examples.mdx @@ -1,52 +1,52 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyAddFromDataset = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n from pathlib import Path\n\n import pyarrow as pa\n import pyarrow.parquet as pq\n\n data_path = str(Path(uri) / \"input.parquet\")\n pq.write_table(pa.table({\"id\": [1, 2], \"name\": [\"Alice\", \"Bob\"]}), data_path)\n import pyarrow.dataset as ds\n\n dataset = ds.dataset(data_path, format=\"parquet\")\n table = db.create_table(\"my_table\", schema=dataset.schema, mode=\"overwrite\")\n table.add(dataset)\n\n print(\"Rows:\", table.count_rows())\n"; +export const PyAddFromDataset = "import pyarrow as pa\nimport pyarrow.parquet as pq\n\ndata_path = \"input.parquet\"\npq.write_table(pa.table({\"id\": [1, 2], \"name\": [\"Alice\", \"Bob\"]}), data_path)\nimport pyarrow.dataset as ds\n\ndataset = ds.dataset(data_path, format=\"parquet\")\ntable = db.create_table(\"my_table\", schema=dataset.schema, mode=\"overwrite\")\ntable.add(dataset)\n\nprint(\"Rows:\", table.count_rows())\n"; -export const PyAddProgress = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\ndef report_progress(progress):\n print(f\"Rows written: {progress['output_rows']}\")\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n table = db.create_table(\"users\", [{\"id\": 1, \"name\": \"Alice\"}])\n table.add(\n [{\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}],\n progress=report_progress,\n )\n rows = sorted(table.search().to_list(), key=lambda row: row[\"id\"])\n print(\"After insertion:\", rows)\n"; +export const PyAddProgress = "table = db.create_table(\"users\", [{\"id\": 1, \"name\": \"Alice\"}])\ntable.add(\n [{\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}],\n progress=report_progress,\n)\nrows = sorted(table.search().to_list(), key=lambda row: row[\"id\"])\nprint(\"After insertion:\", rows)\n"; -export const PyAppendRows = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n table = db.create_table(\"users\", [{\"id\": 1, \"name\": \"Alice\"}])\n table.add([{\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}])\n rows = sorted(table.search().to_list(), key=lambda row: row[\"id\"])\n print(rows)\n"; +export const PyAppendRows = "table = db.create_table(\"users\", [{\"id\": 1, \"name\": \"Alice\"}])\ntable.add([{\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}])\nrows = sorted(table.search().to_list(), key=lambda row: row[\"id\"])\nprint(rows)\n"; -export const PyCreateEmptyTable = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pyarrow as pa\n\n schema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 2)),\n pa.field(\"item\", pa.string()),\n pa.field(\"price\", pa.float32()),\n ]\n )\n tbl = db.create_table(\"test_empty_table\", schema=schema, mode=\"overwrite\")\n\n print(\"Rows:\", tbl.count_rows())\n"; +export const PyCreateEmptyTable = "import pyarrow as pa\n\nschema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 2)),\n pa.field(\"item\", pa.string()),\n pa.field(\"price\", pa.float32()),\n ]\n)\ntbl = db.create_table(\"test_empty_table\", schema=schema, mode=\"overwrite\")\n\nprint(\"Rows:\", tbl.count_rows())\n"; -export const PyCreateEmptyTablePydantic = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n from lancedb.pydantic import LanceModel, Vector\n\n class Item(LanceModel):\n vector: Vector(2)\n item: str\n price: float\n\n tbl = db.create_table(\n \"test_empty_table_new\", schema=Item.to_arrow_schema(), mode=\"overwrite\"\n )\n\n print(\"Rows:\", tbl.count_rows())\n"; +export const PyCreateEmptyTablePydantic = "from lancedb.pydantic import LanceModel, Vector\n\nclass Item(LanceModel):\n vector: Vector(2)\n item: str\n price: float\n\ntbl = db.create_table(\n \"test_empty_table_new\", schema=Item.to_arrow_schema(), mode=\"overwrite\"\n)\n\nprint(\"Rows:\", tbl.count_rows())\n"; -export const PyCreateTableConflictHandling = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n data = [{\"vector\": [1.1, 1.2], \"lat\": 45.5, \"long\": -122.7}]\n db.create_table(\"conflict_table\", data)\n # Idempotent open: reuse the existing table if it exists.\n # The provided data is ignored; the schema is validated against the\n # existing table and a mismatch raises an error.\n tbl = db.create_table(\"conflict_table\", data, exist_ok=True)\n\n # Overwrite: replace the contents with the provided data.\n tbl = db.create_table(\"conflict_table\", data, mode=\"overwrite\")\n print(\"Rows:\", tbl.count_rows())\n"; +export const PyCreateTableConflictHandling = "data = [{\"vector\": [1.1, 1.2], \"lat\": 45.5, \"long\": -122.7}]\ndb.create_table(\"conflict_table\", data)\n# Idempotent open: reuse the existing table if it exists.\n# The provided data is ignored; the schema is validated against the\n# existing table and a mismatch raises an error.\ntbl = db.create_table(\"conflict_table\", data, exist_ok=True)\n\n# Overwrite: replace the contents with the provided data.\ntbl = db.create_table(\"conflict_table\", data, mode=\"overwrite\")\nprint(\"Rows:\", tbl.count_rows())\n"; -export const PyCreateTableCustomSchema = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pyarrow as pa\n\n custom_schema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 4)),\n pa.field(\"lat\", pa.float32()),\n pa.field(\"long\", pa.float32()),\n ]\n )\n\n data = [\n {\"vector\": [1.1, 1.2, 1.3, 1.4], \"lat\": 45.5, \"long\": -122.7},\n {\"vector\": [0.2, 1.8, 0.4, 3.6], \"lat\": 40.1, \"long\": -74.1},\n ]\n tbl = db.create_table(\n \"my_table_custom_schema\", data, schema=custom_schema, mode=\"overwrite\"\n )\n\n print(\"Rows:\", tbl.count_rows())\n"; +export const PyCreateTableCustomSchema = "import pyarrow as pa\n\ncustom_schema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 4)),\n pa.field(\"lat\", pa.float32()),\n pa.field(\"long\", pa.float32()),\n ]\n)\n\ndata = [\n {\"vector\": [1.1, 1.2, 1.3, 1.4], \"lat\": 45.5, \"long\": -122.7},\n {\"vector\": [0.2, 1.8, 0.4, 3.6], \"lat\": 40.1, \"long\": -74.1},\n]\ntbl = db.create_table(\n \"my_table_custom_schema\", data, schema=custom_schema, mode=\"overwrite\"\n)\n\nprint(\"Rows:\", tbl.count_rows())\n"; -export const PyCreateTableFromArrow = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import numpy as np\n import pyarrow as pa\n\n dim = 16\n total = 2\n schema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float16(), dim)),\n pa.field(\"text\", pa.string()),\n ]\n )\n data = pa.Table.from_arrays(\n [\n pa.array(\n [np.random.randn(dim).astype(np.float16) for _ in range(total)],\n pa.list_(pa.float16(), dim),\n ),\n pa.array([\"foo\", \"bar\"]),\n ],\n [\"vector\", \"text\"],\n )\n tbl = db.create_table(\"f16_tbl\", data, schema=schema, mode=\"overwrite\")\n\n print(\"Rows:\", tbl.count_rows())\n"; +export const PyCreateTableFromArrow = "import numpy as np\nimport pyarrow as pa\n\ndim = 16\ntotal = 2\nschema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float16(), dim)),\n pa.field(\"text\", pa.string()),\n ]\n)\ndata = pa.Table.from_arrays(\n [\n pa.array(\n [np.random.randn(dim).astype(np.float16) for _ in range(total)],\n pa.list_(pa.float16(), dim),\n ),\n pa.array([\"foo\", \"bar\"]),\n ],\n [\"vector\", \"text\"],\n)\ntbl = db.create_table(\"f16_tbl\", data, schema=schema, mode=\"overwrite\")\n\nprint(\"Rows:\", tbl.count_rows())\n"; -export const PyCreateTableFromDicts = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n data = [\n {\"vector\": [1.1, 1.2], \"lat\": 45.5, \"long\": -122.7},\n {\"vector\": [0.2, 1.8], \"lat\": 40.1, \"long\": -74.1},\n ]\n db.create_table(\"test_table\", data, mode=\"overwrite\")\n tbl = db[\"test_table\"]\n tbl.head()\n\n print(\"Rows:\", tbl.count_rows())\n"; +export const PyCreateTableFromDicts = "data = [\n {\"vector\": [1.1, 1.2], \"lat\": 45.5, \"long\": -122.7},\n {\"vector\": [0.2, 1.8], \"lat\": 40.1, \"long\": -74.1},\n]\ndb.create_table(\"test_table\", data, mode=\"overwrite\")\ntbl = db[\"test_table\"]\ntbl.head()\n\nprint(\"Rows:\", tbl.count_rows())\n"; -export const PyCreateTableFromIterator = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pyarrow as pa\n\n schema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 4)),\n pa.field(\"item\", pa.utf8()),\n pa.field(\"price\", pa.float32()),\n ]\n )\n\n def make_batches():\n for i in range(5):\n yield pa.RecordBatch.from_arrays(\n [\n pa.array(\n [[3.1, 4.1, 5.1, 6.1], [5.9, 26.5, 4.7, 32.8]],\n pa.list_(pa.float32(), 4),\n ),\n pa.array([\"foo\", \"bar\"]),\n pa.array([10.0, 20.0]),\n ],\n [\"vector\", \"item\", \"price\"],\n )\n\n table = db.create_table(\"batched_table\", schema=schema)\n table.add(make_batches())\n\n print(\"Rows:\", table.count_rows())\n"; +export const PyCreateTableFromIterator = "import pyarrow as pa\n\nschema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 4)),\n pa.field(\"item\", pa.utf8()),\n pa.field(\"price\", pa.float32()),\n ]\n)\n\ndef make_batches():\n for i in range(5):\n yield pa.RecordBatch.from_arrays(\n [\n pa.array(\n [[3.1, 4.1, 5.1, 6.1], [5.9, 26.5, 4.7, 32.8]],\n pa.list_(pa.float32(), 4),\n ),\n pa.array([\"foo\", \"bar\"]),\n pa.array([10.0, 20.0]),\n ],\n [\"vector\", \"item\", \"price\"],\n )\n\ntable = db.create_table(\"batched_table\", schema=schema)\ntable.add(make_batches())\n\nprint(\"Rows:\", table.count_rows())\n"; -export const PyCreateTableFromPandas = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pandas as pd\n\n data = pd.DataFrame(\n {\n \"vector\": [[1.1, 1.2, 1.3, 1.4], [0.2, 1.8, 0.4, 3.6]],\n \"lat\": [45.5, 40.1],\n \"long\": [-122.7, -74.1],\n }\n )\n db.create_table(\"my_table_pandas\", data, mode=\"overwrite\")\n db[\"my_table_pandas\"].head()\n"; +export const PyCreateTableFromPandas = "import pandas as pd\n\ndata = pd.DataFrame(\n {\n \"vector\": [[1.1, 1.2, 1.3, 1.4], [0.2, 1.8, 0.4, 3.6]],\n \"lat\": [45.5, 40.1],\n \"long\": [-122.7, -74.1],\n }\n)\ndb.create_table(\"my_table_pandas\", data, mode=\"overwrite\")\ndb[\"my_table_pandas\"].head()\n"; -export const PyCreateTableFromPolars = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import polars as pl\n\n data = pl.DataFrame(\n {\n \"vector\": [[3.1, 4.1], [5.9, 26.5]],\n \"item\": [\"foo\", \"bar\"],\n \"price\": [10.0, 20.0],\n }\n )\n tbl = db.create_table(\"my_table_pl\", data, mode=\"overwrite\")\n\n print(\"Rows:\", tbl.count_rows())\n"; +export const PyCreateTableFromPolars = "import polars as pl\n\ndata = pl.DataFrame(\n {\n \"vector\": [[3.1, 4.1], [5.9, 26.5]],\n \"item\": [\"foo\", \"bar\"],\n \"price\": [10.0, 20.0],\n }\n)\ntbl = db.create_table(\"my_table_pl\", data, mode=\"overwrite\")\n\nprint(\"Rows:\", tbl.count_rows())\n"; -export const PyCreateTableFromPydantic = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n from lancedb.pydantic import LanceModel, Vector\n\n class Content(LanceModel):\n movie_id: int\n vector: Vector(128)\n genres: str\n title: str\n imdb_id: int\n\n @property\n def imdb_url(self) -> str:\n return f\"https://www.imdb.com/title/tt{self.imdb_id}\"\n\n tbl = db.create_table(\"movielens_small\", schema=Content, mode=\"overwrite\")\n\n print(\"Rows:\", tbl.count_rows())\n"; +export const PyCreateTableFromPydantic = "from lancedb.pydantic import LanceModel, Vector\n\nclass Content(LanceModel):\n movie_id: int\n vector: Vector(128)\n genres: str\n title: str\n imdb_id: int\n\n @property\n def imdb_url(self) -> str:\n return f\"https://www.imdb.com/title/tt{self.imdb_id}\"\n\ntbl = db.create_table(\"movielens_small\", schema=Content, mode=\"overwrite\")\n\nprint(\"Rows:\", tbl.count_rows())\n"; -export const PyCreateTableNestedSchema = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n from lancedb.pydantic import LanceModel, Vector\n from pydantic import BaseModel\n\n class Document(BaseModel):\n content: str\n source: str\n\n class NestedSchema(LanceModel):\n id: str\n vector: Vector(1536)\n document: Document\n\n tbl = db.create_table(\"nested_table\", schema=NestedSchema, mode=\"overwrite\")\n\n print(\"Rows:\", tbl.count_rows())\n"; +export const PyCreateTableNestedSchema = "from lancedb.pydantic import LanceModel, Vector\nfrom pydantic import BaseModel\n\nclass Document(BaseModel):\n content: str\n source: str\n\nclass NestedSchema(LanceModel):\n id: str\n vector: Vector(1536)\n document: Document\n\ntbl = db.create_table(\"nested_table\", schema=NestedSchema, mode=\"overwrite\")\n\nprint(\"Rows:\", tbl.count_rows())\n"; -export const PyDeleteRows = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n table = db.create_table(\n \"users\",\n [\n {\"id\": 1, \"name\": \"Alice\"},\n {\"id\": 2, \"name\": \"Bob\"},\n {\"id\": 3, \"name\": \"Charlie\"},\n ],\n )\n predicate = \"id = 3\"\n print(\"Selected:\", table.search().where(predicate).to_list())\n table.delete(predicate)\n rows = sorted(table.search().to_list(), key=lambda row: row[\"id\"])\n print(\"Remaining:\", rows)\n"; +export const PyDeleteRows = "table = db.create_table(\n \"users\",\n [\n {\"id\": 1, \"name\": \"Alice\"},\n {\"id\": 2, \"name\": \"Bob\"},\n {\"id\": 3, \"name\": \"Charlie\"},\n ],\n)\npredicate = \"id = 3\"\nprint(\"Selected:\", table.search().where(predicate).to_list())\ntable.delete(predicate)\nrows = sorted(table.search().to_list(), key=lambda row: row[\"id\"])\nprint(\"Remaining:\", rows)\n"; -export const PyDropTable = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n # Create a table first\n data = [{\"vector\": [1.1, 1.2], \"lat\": 45.5}]\n db.create_table(\"my_table\", data, mode=\"overwrite\")\n\n # Drop the table\n db.drop_table(\"my_table\")\n"; +export const PyDropTable = "# Create a table first\ndata = [{\"vector\": [1.1, 1.2], \"lat\": 45.5}]\ndb.create_table(\"my_table\", data, mode=\"overwrite\")\n\n# Drop the table\ndb.drop_table(\"my_table\")\n"; -export const PyInsertIfNotExists = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pyarrow as pa\n\n table = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n )\n\n incoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n \"login_count\": [21, 5],\n }\n )\n\n (table.merge_insert(\"id\").when_not_matched_insert_all().execute(incoming_users))\n\n print(\"Rows:\", table.count_rows())\n"; +export const PyInsertIfNotExists = "import pyarrow as pa\n\ntable = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n)\n\nincoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n \"login_count\": [21, 5],\n }\n)\n\n(table.merge_insert(\"id\").when_not_matched_insert_all().execute(incoming_users))\n\nprint(\"Rows:\", table.count_rows())\n"; -export const PyMergeDeleteMissingBySource = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pyarrow as pa\n\n table = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2, 3],\n \"name\": [\"Alice\", \"Bob\", \"Charlie\"],\n \"login_count\": [10, 20, 5],\n }\n ),\n mode=\"overwrite\",\n )\n\n incoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n \"login_count\": [21, 5],\n }\n )\n\n (\n table.merge_insert(\"id\")\n .when_matched_update_all()\n .when_not_matched_insert_all()\n .when_not_matched_by_source_delete()\n .execute(incoming_users)\n )\n\n print(\"Rows:\", table.count_rows())\n"; +export const PyMergeDeleteMissingBySource = "import pyarrow as pa\n\ntable = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2, 3],\n \"name\": [\"Alice\", \"Bob\", \"Charlie\"],\n \"login_count\": [10, 20, 5],\n }\n ),\n mode=\"overwrite\",\n)\n\nincoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n \"login_count\": [21, 5],\n }\n)\n\n(\n table.merge_insert(\"id\")\n .when_matched_update_all()\n .when_not_matched_insert_all()\n .when_not_matched_by_source_delete()\n .execute(incoming_users)\n)\n\nprint(\"Rows:\", table.count_rows())\n"; -export const PyMergeMatchedUpdateOnly = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pyarrow as pa\n\n table = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n )\n\n incoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n \"login_count\": [21, 5],\n }\n )\n\n (table.merge_insert(\"id\").when_matched_update_all().execute(incoming_users))\n\n print(\"Rows:\", table.count_rows())\n"; +export const PyMergeMatchedUpdateOnly = "import pyarrow as pa\n\ntable = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n)\n\nincoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n \"login_count\": [21, 5],\n }\n)\n\n(table.merge_insert(\"id\").when_matched_update_all().execute(incoming_users))\n\nprint(\"Rows:\", table.count_rows())\n"; -export const PyMergePartialColumns = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pyarrow as pa\n\n table = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n )\n\n incoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n }\n )\n\n (\n table.merge_insert(\"id\")\n .when_matched_update_all()\n .when_not_matched_insert_all()\n .execute(incoming_users)\n )\n\n print(\"Rows:\", table.count_rows())\n"; +export const PyMergePartialColumns = "import pyarrow as pa\n\ntable = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n)\n\nincoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n }\n)\n\n(\n table.merge_insert(\"id\")\n .when_matched_update_all()\n .when_not_matched_insert_all()\n .execute(incoming_users)\n)\n\nprint(\"Rows:\", table.count_rows())\n"; -export const PyMergeUpdateInsert = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pyarrow as pa\n\n table = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n )\n\n incoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n \"login_count\": [21, 5],\n }\n )\n\n (\n table.merge_insert(\"id\")\n .when_matched_update_all()\n .when_not_matched_insert_all()\n .execute(incoming_users)\n )\n\n print(\"Rows:\", table.count_rows())\n"; +export const PyMergeUpdateInsert = "import pyarrow as pa\n\ntable = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n)\n\nincoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n \"login_count\": [21, 5],\n }\n)\n\n(\n table.merge_insert(\"id\")\n .when_matched_update_all()\n .when_not_matched_insert_all()\n .execute(incoming_users)\n)\n\nprint(\"Rows:\", table.count_rows())\n"; -export const PyOpenExistingTable = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n # Create a table first\n data = [{\"vector\": [1.1, 1.2], \"lat\": 45.5, \"long\": -122.7}]\n db.create_table(\"test_table\", data, mode=\"overwrite\")\n\n # List table names\n print(db.list_tables().tables)\n\n # Open existing table\n tbl = db.open_table(\"test_table\")\n\n print(\"Rows:\", tbl.count_rows())\n"; +export const PyOpenExistingTable = "# Create a table first\ndata = [{\"vector\": [1.1, 1.2], \"lat\": 45.5, \"long\": -122.7}]\ndb.create_table(\"test_table\", data, mode=\"overwrite\")\n\n# List table names\nprint(db.list_tables().tables)\n\n# Open existing table\ntbl = db.open_table(\"test_table\")\n\nprint(\"Rows:\", tbl.count_rows())\n"; -export const PyUpdateOperation = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pyarrow as pa\n\n table = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n )\n table.update(where=\"id = 2\", values={\"name\": \"Bobby\"})\n\n print(\"Rows:\", table.count_rows())\n"; +export const PyUpdateOperation = "import pyarrow as pa\n\ntable = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n)\ntable.update(where=\"id = 2\", values={\"name\": \"Bobby\"})\n\nprint(\"Rows:\", table.count_rows())\n"; -export const PyUpdateUsingSql = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n import pyarrow as pa\n\n table = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n )\n table.update(where=\"id = 2\", values_sql={\"login_count\": \"login_count + 1\"})\n\n print(\"Rows:\", table.count_rows())\n"; +export const PyUpdateUsingSql = "import pyarrow as pa\n\ntable = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n)\ntable.update(where=\"id = 2\", values_sql={\"login_count\": \"login_count + 1\"})\n\nprint(\"Rows:\", table.count_rows())\n"; export const PyWriteWorkflow = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-ingestion-\") as uri:\n db = lancedb.connect(uri)\n table = db.create_table(\n \"users\",\n [\n {\"id\": 1, \"name\": \"Alice\", \"login_count\": 10},\n {\"id\": 2, \"name\": \"Bob\", \"login_count\": 20},\n ],\n )\n table.add([{\"id\": 3, \"name\": \"Charlie\", \"login_count\": 5}])\n table.update(where=\"id = 2\", values={\"name\": \"Bobby\"})\n table.update(where=\"id = 2\", values_sql={\"login_count\": \"login_count + 1\"})\n (\n table.merge_insert(\"id\")\n .when_matched_update_all()\n .when_not_matched_insert_all()\n .execute(\n [\n {\"id\": 3, \"name\": \"Charlie\", \"login_count\": 6},\n {\"id\": 4, \"name\": \"Dana\", \"login_count\": 1},\n ]\n )\n )\n print(\"Rows selected for deletion:\", table.search().where(\"id = 4\").to_list())\n table.delete(\"id = 4\")\n rows = sorted(table.search().to_list(), key=lambda row: row[\"id\"])\n print(rows)\n"; diff --git a/docs/web/snippets/integrations.mdx b/docs/web/snippets/integrations.mdx index dca2d0c1f..00f8bb02e 100644 --- a/docs/web/snippets/integrations.mdx +++ b/docs/web/snippets/integrations.mdx @@ -40,7 +40,7 @@ export const PyEmbeddingOpenclipTextSearch = "actual = table.search(\"man's best export const PyEmbeddingSentenceTransformersBaai = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"sentence-transformers\"))\nmodel = (\n get_registry()\n .get(\"sentence-transformers\")\n .create(name=\"BAAI/bge-small-en-v1.5\", device=\"cpu\")\n)\n\nclass Words(LanceModel):\n text: str = model.SourceField()\n vector: Vector(model.ndims()) = model.VectorField()\n\ntable = db.create_table(\"words\", schema=Words)\ntable.add(\n [\n {\"text\": \"hello world\"},\n {\"text\": \"goodbye world\"},\n ]\n)\n\nquery = \"greetings\"\nactual = table.search(query).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n"; -export const PyEmbeddingVoyageaiMultimodal = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import EmbeddingFunctionRegistry\nfrom lancedb.pydantic import LanceModel, Vector\n\n# Create multimodal embedding function with custom dimension\nvoyageai = (\n EmbeddingFunctionRegistry.get_instance()\n .get(\"voyageai\")\n .create(name=\"voyage-multimodal-3.5\", output_dimension=512)\n)\n\nclass ImageModel(LanceModel):\n image_uri: str = voyageai.SourceField()\n vector: Vector(voyageai.ndims()) = voyageai.VectorField()\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"voyageai-multimodal\"))\ntbl = db.create_table(\"images\", schema=ImageModel, mode=\"overwrite\")\n\n# Add images using URLs\ntbl.add(\n [\n {\"image_uri\": \"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/300px-PNG_transparency_demonstration_1.png\"},\n ]\n)\n\n# Search with text query\nresults = tbl.search(\"dice\").limit(1).to_list()\nprint(results)\n"; +export const PyEmbeddingVoyageaiMultimodal = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import EmbeddingFunctionRegistry\nfrom lancedb.pydantic import LanceModel, Vector\n\n# Create multimodal embedding function with custom dimension\nvoyageai = (\n EmbeddingFunctionRegistry.get_instance()\n .get(\"voyageai\")\n .create(name=\"voyage-multimodal-3.5\", output_dimension=512)\n)\n\nclass ImageModel(LanceModel):\n image_uri: str = voyageai.SourceField()\n vector: Vector(voyageai.ndims()) = voyageai.VectorField()\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"voyageai-multimodal\"))\ntbl = db.create_table(\"images\", schema=ImageModel, mode=\"overwrite\")\n\n# Add images using URLs\ntbl.add(\n [\n {\n \"image_uri\": \"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/300px-PNG_transparency_demonstration_1.png\"\n },\n ]\n)\n\n# Search with text query\nresults = tbl.search(\"dice\").limit(1).to_list()\nprint(results)\n"; export const PyEmbeddingVoyageaiUsage = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import EmbeddingFunctionRegistry\nfrom lancedb.pydantic import LanceModel, Vector\n\nvoyageai = (\n EmbeddingFunctionRegistry.get_instance().get(\"voyageai\").create(name=\"voyage-3\")\n)\n\nclass TextModel(LanceModel):\n text: str = voyageai.SourceField()\n vector: Vector(voyageai.ndims()) = voyageai.VectorField()\n\ndata = [{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}]\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"voyageai-demo\"))\ntbl = db.create_table(\"test\", schema=TextModel, mode=\"overwrite\")\n\ntbl.add(data)\n"; @@ -74,11 +74,9 @@ export const PyFrameworksLangchainVectorStoreConfig = "db_url = \"db://lang_test export const PyFrameworksLerobotFilterFrames = "frame_rows = (\n frames.search()\n .where(\"episode_index = 0 AND frame_index < 10\", prefilter=True)\n .select([\"episode_index\", \"frame_index\", \"timestamp\", \"action\"])\n .limit(10)\n .to_list()\n)\n\nfor row in frame_rows:\n print(row[\"episode_index\"], row[\"frame_index\"], row[\"timestamp\"])\n"; -export const PyFrameworksLerobotLoad = "from lerobot.datasets import LeRobotDataset\n\n# Hub dataset repo: storage_format in meta/info.json routes to the Lance reader\ndataset = LeRobotDataset(\"lance-format/pusht-lance\")\n\n# HF Storage Bucket, read in place, nothing downloaded\ndataset = LeRobotDataset(\"lance-format/lerobot-tests/pusht-lance\", repo_type=\"bucket\")\n\nsample = dataset[100]\nprint(sample[\"observation.state\"].shape)\nprint(sample[\"observation.image\"].shape)\n"; +export const PyFrameworksLerobotLancedbDataset = "from lerobot_lancedb import LanceDBDataset, lance_mp_context\nfrom torch.utils.data import DataLoader\n\ndataset = LanceDBDataset(root=\"hf://datasets/lance-format/pusht-lance\")\nsample = dataset[0]\nprint(sample[\"observation.state\"].shape)\nprint(sample[\"action\"].shape)\n\nloader = DataLoader(\n dataset,\n batch_size=32,\n num_workers=8,\n multiprocessing_context=lance_mp_context(),\n)\n"; -export const PyFrameworksLerobotOpenLanceTables = "import lancedb\n\ndb = lancedb.connect(\"hf://datasets/lance-format/pusht-lance\")\nframes = db.open_table(\"frames\")\nvideos = db.open_table(\"videos\")\n\nprint(frames.count_rows(), videos.count_rows())\nprint(frames.schema)\n"; - -export const PyFrameworksLerobotTrainReady = "import torch\n\ndataset = LeRobotDataset(\n \"lance-format/pusht-lance\",\n delta_timestamps={\"observation.image\": [-0.2, -0.1, 0.0]},\n return_uint8=True,\n)\nloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)\nbatch = next(iter(loader))\nprint(batch[\"observation.image\"].shape) # [32, 3, C, H, W]\n"; +export const PyFrameworksLerobotOpenLanceTables = "import lancedb\n\ndb = lancedb.connect(\"hf://datasets/lance-format/pusht-lance\")\nframes = db.open_table(\"frames\")\nvideos = db.open_table(\"videos\")\n\nprint(len(frames), len(videos))\nprint(frames.schema)\n"; export const PyFrameworksLlamaindexAddReranker = "from lancedb.rerankers import ColbertReranker\n\nreranker = ColbertReranker()\nvector_store._add_reranker(reranker)\n"; @@ -94,7 +92,7 @@ export const PyFrameworksPydanticBaseModel = "class LanceDocs(LanceModel):\n export const PyFrameworksPydanticImports = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.pydantic import LanceModel, Vector\n"; -export const PyFrameworksPydanticSetUrl = "db = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"pydantic-docs\"))\n"; +export const PyFrameworksPydanticSetUrl = "import lancedb\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"pydantic-docs\"))\n"; export const PyFrameworksPydanticTypeConversion = "from typing import List, Optional\n\nimport pyarrow as pa\nimport pydantic\nfrom lancedb.pydantic import Vector, pydantic_to_schema\n\nclass FooModel(pydantic.BaseModel):\n id: int\n s: str\n vec: Vector(1536) # fixed_size_list[1536]\n li: List[int]\n\nschema = pydantic_to_schema(FooModel)\nassert schema == pa.schema(\n [\n pa.field(\"id\", pa.int64(), False),\n pa.field(\"s\", pa.utf8(), False),\n pa.field(\"vec\", pa.list_(pa.float32(), 1536)),\n pa.field(\"li\", pa.list_(pa.int64()), False),\n ]\n)\n"; @@ -120,15 +118,15 @@ export const PyPlatformsDuckdbMeanPrice = "duckdb.query(\"SELECT mean(price) FRO export const PyPlatformsDuckdbQueryTable = "import duckdb\n\narrow_table = table.to_lance()\n\nduckdb.query(\"SELECT * FROM arrow_table\")\n"; -export const PyPlatformsPandasAsyncExample = "async def run_pandas_async_example() -> pd.DataFrame:\n async_db = await lancedb.connect_async(\n str(Path(tempfile.mkdtemp()) / \"pandas-async\")\n )\n async_df = pd.DataFrame(\n [\n {\"id\": \"10\", \"text\": \"sage\", \"vector\": [0.6, 0.4, 0.8]},\n {\"id\": \"11\", \"text\": \"bard\", \"vector\": [0.2, 0.7, 0.3]},\n ]\n )\n async_table = await async_db.create_table(\n \"creatures_async\", data=async_df, mode=\"overwrite\"\n )\n # An async search returns its query builder from an await\n query = await async_table.search([0.6, 0.4, 0.8])\n async_results = await query.select([\"text\", \"_distance\"]).limit(1).to_pandas()\n print(async_results)\n return async_results\n\nasync_results = asyncio.run(run_pandas_async_example())\n"; +export const PyPlatformsPandasAsyncExample = "import lancedb\n\nasync def run_pandas_async_example() -> pd.DataFrame:\n async_db = await lancedb.connect_async(\n str(Path(tempfile.mkdtemp()) / \"pandas-async\")\n )\n async_df = pd.DataFrame(\n [\n {\"id\": \"10\", \"text\": \"sage\", \"vector\": [0.6, 0.4, 0.8]},\n {\"id\": \"11\", \"text\": \"bard\", \"vector\": [0.2, 0.7, 0.3]},\n ]\n )\n async_table = await async_db.create_table(\n \"creatures_async\", data=async_df, mode=\"overwrite\"\n )\n # An async search returns its query builder from an await\n query = await async_table.search([0.6, 0.4, 0.8])\n async_results = await query.select([\"text\", \"_distance\"]).limit(1).to_pandas()\n print(async_results)\n return async_results\n\nasync_results = asyncio.run(run_pandas_async_example())\n"; -export const PyPlatformsPandasCreateTable = "pandas_df = pd.DataFrame(\n [\n {\"id\": \"1\", \"text\": \"dragon\", \"vector\": [0.9, 0.1, 0.3]},\n {\"id\": \"2\", \"text\": \"griffin\", \"vector\": [0.4, 0.5, 0.2]},\n {\"id\": \"3\", \"text\": \"phoenix\", \"vector\": [0.7, 0.3, 0.6]},\n ]\n)\npandas_db = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"pandas-demo\"))\npandas_table = pandas_db.create_table(\"creatures\", data=pandas_df, mode=\"overwrite\")\n"; +export const PyPlatformsPandasCreateTable = "import lancedb\n\npandas_df = pd.DataFrame(\n [\n {\"id\": \"1\", \"text\": \"dragon\", \"vector\": [0.9, 0.1, 0.3]},\n {\"id\": \"2\", \"text\": \"griffin\", \"vector\": [0.4, 0.5, 0.2]},\n {\"id\": \"3\", \"text\": \"phoenix\", \"vector\": [0.7, 0.3, 0.6]},\n ]\n)\npandas_db = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"pandas-demo\"))\npandas_table = pandas_db.create_table(\"creatures\", data=pandas_df, mode=\"overwrite\")\n"; export const PyPlatformsPandasImports = "import asyncio\nimport tempfile\nfrom pathlib import Path\n\nimport lancedb\nimport pandas as pd\n"; export const PyPlatformsPandasVectorSearch = "pandas_results = (\n pandas_table.search([0.9, 0.1, 0.3])\n .select([\"text\", \"_distance\"])\n .limit(1)\n .to_pandas()\n)\nprint(pandas_results)\n"; -export const PyPlatformsPolarsCreateTable = "birds = pl.DataFrame(\n {\n \"text\": [\"phoenix\", \"sparrow\"],\n \"vector\": [\n [0.1, 0.2, 0.3],\n [0.8, 0.6, 0.5],\n ],\n }\n)\npolars_db = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"polars-demo\"))\npolars_table = polars_db.create_table(\n \"birds\", data=birds.to_arrow(), mode=\"overwrite\"\n)\n"; +export const PyPlatformsPolarsCreateTable = "import lancedb\n\nbirds = pl.DataFrame(\n {\n \"text\": [\"phoenix\", \"sparrow\"],\n \"vector\": [\n [0.1, 0.2, 0.3],\n [0.8, 0.6, 0.5],\n ],\n }\n)\npolars_db = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"polars-demo\"))\npolars_table = polars_db.create_table(\n \"birds\", data=birds.to_arrow(), mode=\"overwrite\"\n)\n"; export const PyPlatformsPolarsImports = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nimport polars as pl\nfrom lancedb.pydantic import LanceModel, Vector\n"; @@ -172,8 +170,6 @@ export const PyRerankingRrfUsage = "import tempfile\nfrom pathlib import Path\n\ export const PyRerankingVoyageaiUsage = "import os\n\nimport lancedb\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\nfrom lancedb.rerankers import VoyageAIReranker\n\nembedder = get_registry().get(\"sentence-transformers\").create()\ndb = lancedb.connect(\"~/.lancedb\")\n\nclass Schema(LanceModel):\n text: str = embedder.SourceField()\n vector: Vector(embedder.ndims()) = embedder.VectorField()\n\ndata = [\n {\"text\": \"hello world\"},\n {\"text\": \"goodbye world\"},\n]\ntbl = db.create_table(\"test\", schema=Schema, mode=\"overwrite\")\ntbl.add(data)\nreranker = VoyageAIReranker(model_name=\"rerank-2\")\n\n# Run vector search with a reranker\nresult = tbl.search(\"hello\").rerank(reranker=reranker).to_list()\n\n# Run FTS search with a reranker\nresult = tbl.search(\"hello\", query_type=\"fts\").rerank(reranker=reranker).to_list()\n\n# Run hybrid search with a reranker\ntbl.create_fts_index(\"text\", replace=True)\nresult = (\n tbl.search(\"hello\", query_type=\"hybrid\").rerank(reranker=reranker).to_list()\n)\n"; -export const PyRerankingWatsonxUsage = "import os\n\nimport lancedb\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\nfrom lancedb.rerankers import WatsonxReranker\n\nembedder = get_registry().get(\"sentence-transformers\").create()\ndb = lancedb.connect(\"~/.lancedb\")\n\nclass Schema(LanceModel):\n text: str = embedder.SourceField()\n vector: Vector(embedder.ndims()) = embedder.VectorField()\n\ndata = [\n {\"text\": \"hello world\"},\n {\"text\": \"goodbye world\"},\n]\ntbl = db.create_table(\"test\", schema=Schema, mode=\"overwrite\")\ntbl.add(data)\n\n# Credentials pulled from WATSONX_API_KEY and WATSONX_PROJECT_ID (or WATSONX_SPACE_ID)\nreranker = WatsonxReranker(\n api_key=os.environ[\"WATSONX_API_KEY\"],\n project_id=os.environ[\"WATSONX_PROJECT_ID\"],\n)\n\n# Run vector search with a reranker\nresult = tbl.search(\"hello\").rerank(reranker=reranker).to_list()\n\n# Run FTS search with a reranker\nresult = tbl.search(\"hello\", query_type=\"fts\").rerank(reranker=reranker).to_list()\n\n# Run hybrid search with a reranker\ntbl.create_fts_index(\"text\", replace=True)\nresult = (\n tbl.search(\"hello\", query_type=\"hybrid\").rerank(reranker=reranker).to_list()\n)\n"; - export const TsFrameworksGenkitCustomIndexer = "export const menuPdfIndexer = lancedbIndexerRef({\n // Using all defaults, for dbUri, tableName, and embedder, etc\n});\n\nconst chunkingConfig = {\n minLength: 1000,\n maxLength: 2000,\n splitter: \"sentence\",\n overlap: 100,\n delimiters: \"\",\n} as any;\n\nasync function extractTextFromPdf(filePath: string) {\n const pdfFile = path.resolve(filePath);\n const dataBuffer = await readFile(pdfFile);\n const data = await pdf(dataBuffer);\n return data.text;\n}\n\nexport const indexMenu = ai.defineFlow(\n {\n name: \"indexMenu\",\n inputSchema: z.string().describe(\"PDF file path\"),\n outputSchema: z.void(),\n },\n async (filePath: string) => {\n filePath = path.resolve(filePath);\n\n // Read the pdf.\n const pdfTxt = await ai.run(\"extract-text\", () => extractTextFromPdf(filePath));\n\n // Divide the pdf text into segments.\n const chunks = await ai.run(\"chunk-it\", async () => chunk(pdfTxt, chunkingConfig));\n\n // Convert chunks of text into documents to store in the index.\n const documents = chunks.map((text) => {\n return Document.fromText(text, { filePath });\n });\n\n // Add documents to the index.\n await ai.index({\n indexer: menuPdfIndexer,\n documents,\n options: {\n writeMode: WriteMode.Overwrite,\n } as any,\n });\n },\n);\n"; export const TsFrameworksGenkitCustomRetriever = "export const menuRetriever = lancedbRetrieverRef({\n tableName: \"table\", // Use the same table name as the indexer.\n displayName: \"Menu\", // Use a custom display name.\n});\n\nexport const menuQAFlow = ai.defineFlow(\n { name: \"Menu\", inputSchema: z.string(), outputSchema: z.string() },\n async (input: string) => {\n // retrieve relevant documents\n const docs = await ai.retrieve({\n retriever: menuRetriever,\n query: input,\n options: {\n k: 3,\n },\n });\n\n const extractedContent = docs.map((doc) => {\n if (doc.content && Array.isArray(doc.content) && doc.content.length > 0) {\n if (doc.content[0].media && doc.content[0].media.url) {\n return doc.content[0].media.url;\n }\n }\n return \"No content found\";\n });\n\n console.log(\"Extracted content:\", extractedContent);\n\n const { text } = await ai.generate({\n model: gemini(\"gemini-2.0-flash\"),\n prompt: `\nYou are acting as a helpful AI assistant that can answer \nquestions about the food available on the menu at Genkit Grub Pub.\n\nUse only the context provided to answer the question.\nIf you don't know, do not make up an answer.\nDo not add or change items on the menu.\n\nContext:\n${extractedContent.join(\"\\n\\n\")}\n\nQuestion: ${input}`,\n docs,\n });\n\n return text;\n },\n);\n"; diff --git a/docs/web/snippets/quickstart.mdx b/docs/web/snippets/quickstart.mdx index cd8976768..94746f2d1 100644 --- a/docs/web/snippets/quickstart.mdx +++ b/docs/web/snippets/quickstart.mdx @@ -2,65 +2,59 @@ export const PyQuickstartAddData = "table.add(\n [\n {\n \"frame_id\": \"4\",\n \"video_id\": \"clip-2\",\n \"caption\": \"a gripper lowering a cup onto the table\",\n \"stats\": {\"motion\": 5, \"sharpness\": 4, \"exposure\": 4, \"framing\": 2},\n \"embedding\": [0.3, 0.9, 0.6, 0.8],\n }\n ]\n)\n"; -export const PyQuickstartAddFeature = "table.add_columns(\n {\n \"quality_score\": \"cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)\"\n }\n)\n"; +export const PyQuickstartAddFeature = "from lancedb import col, udf\n\n@udf\ndef quality_score(\n motion: float, sharpness: float, exposure: float, framing: float\n) -> float:\n return (motion + sharpness + exposure + framing) / 4.0\n\nversion = db.create_function_async(quality_score).wait()\ntable.add_columns(\n {\n \"quality_score\": version(\n motion=col(\"motion\"),\n sharpness=col(\"sharpness\"),\n exposure=col(\"exposure\"),\n framing=col(\"framing\"),\n )\n }\n)\ntable.refresh_column(\"quality_score\")\n"; -export const PyQuickstartComputedFeature = "table.add_columns(computed={\"caption_length\": \"length(caption)\"})\ntable.refresh_column(\"caption_length\")\n"; - -export const PyQuickstartComputedFeatureEnterprise = "table.add_columns(computed={\"caption_length\": \"length(caption)\"})\njob = table.refresh_column_async(\"caption_length\")\njob.wait()\n"; +export const PyQuickstartAddFeatureEnterprise = "job = table.refresh_column_async(\"quality_score\")\njob.wait()\n"; export const PyQuickstartCreateTable = "table = db.create_table(\"frames\", data=data, mode=\"overwrite\")\n"; export const PyQuickstartCreateTableAsync = "async_table = await async_db.create_table(\n \"frames\",\n data=data,\n mode=\"overwrite\",\n)\n"; -export const PyQuickstartCurateWithMetadata = "curated = (\n table.search(query_vector)\n .where(\"stats.motion >= 4\")\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .to_polars()\n)\nprint(curated)\n"; +export const PyQuickstartCurateDedupe = "db.execute_query(\"\"\"\n CREATE MATERIALIZED VIEW frames_deduped AS\n SELECT * FROM dedupe(\n 'frames',\n 'embedding',\n distance_threshold => 0.03\n )\n\"\"\")\n"; + +export const PyQuickstartCurateDedupeQuery = "deduped = db.execute_query(\n \"SELECT frame_id FROM frames_deduped ORDER BY frame_id\"\n).read_all()\nprint(deduped.to_pylist())\n"; + +export const PyQuickstartCurateDedupeSetup = "# Frame 5 is a near-duplicate of frame 2: the gripper is still closing,\n# one video frame later, with an almost identical embedding.\ntable.add(\n [\n {\n \"frame_id\": \"5\",\n \"video_id\": \"clip-1\",\n \"caption\": \"the two-finger gripper still closing on the cup\",\n \"stats\": {\"motion\": 5, \"sharpness\": 4, \"exposure\": 5, \"framing\": 2},\n \"embedding\": [0.2, 0.9, 0.4, 0.89],\n }\n ]\n)\nfrom lancedb.index import IvfFlat\n\ntable.create_index(\n \"embedding\", config=IvfFlat(num_partitions=1, distance_type=\"l2\")\n)\ntable.wait_for_index([\"embedding_idx\"])\n"; + +export const PyQuickstartCurateSample = "sample = db.execute_query(\n \"SELECT frame_id FROM frames TABLESAMPLE (2 ROWS)\"\n).read_all()\nprint(sample.to_pylist())\n"; export const PyQuickstartData = "data = [\n {\n \"frame_id\": \"1\",\n \"video_id\": \"clip-1\",\n \"caption\": \"a robot arm reaching toward a cup\",\n \"stats\": {\"motion\": 3, \"sharpness\": 4, \"exposure\": 4, \"framing\": 3},\n \"embedding\": [0.7, 0.1, 0.9, 0.7],\n },\n {\n \"frame_id\": \"2\",\n \"video_id\": \"clip-1\",\n \"caption\": \"a two-finger gripper closing on a cup\",\n \"stats\": {\"motion\": 5, \"sharpness\": 4, \"exposure\": 5, \"framing\": 2},\n \"embedding\": [0.2, 0.9, 0.4, 0.9],\n },\n {\n \"frame_id\": \"3\",\n \"video_id\": \"clip-2\",\n \"caption\": \"a robot arm holding a cup steady\",\n \"stats\": {\"motion\": 2, \"sharpness\": 3, \"exposure\": 3, \"framing\": 4},\n \"embedding\": [0.9, 0.1, 0.5, 0.4],\n },\n]\n"; +export const PyQuickstartFlattenStats = "table.add_columns(\n {\n \"motion\": \"cast(stats.motion as float)\",\n \"sharpness\": \"cast(stats.sharpness as float)\",\n \"exposure\": \"cast(stats.exposure as float)\",\n \"framing\": \"cast(stats.framing as float)\",\n }\n)\n"; + export const PyQuickstartMultimodalBytes = "from pathlib import Path\n\nimage_bytes = Path(\"data/sample-frame.jpg\").read_bytes()\n\nmultimodal_table = db.create_table(\n \"frame_images\",\n data=[\n {\n \"frame_id\": \"thumb-1\",\n \"caption\": \"Sample frame thumbnail\",\n \"image\": image_bytes,\n \"embedding\": [0.9, 0.1, 0.5, 0.4],\n }\n ],\n mode=\"overwrite\",\n)\n"; export const PyQuickstartOutputPandas = "# Ensure you run `pip install pandas` beforehand\nresult = table.search(query_vector).limit(2).to_pandas()\nprint(result)\n"; -export const PyQuickstartQueryFeature = "features = table.search().select([\"frame_id\", \"video_id\", \"quality_score\"]).to_polars()\nprint(features)\n"; +export const PyQuickstartQueryFeature = "features = (\n table.search().select([\"frame_id\", \"video_id\", \"quality_score\"]).to_polars()\n)\nprint(features)\n"; -export const PyQuickstartTraining = "import torch\nfrom lancedb.permutation import Permutation\n\ntable.add_columns(\n {\n \"motion\": \"cast(stats.motion as float)\",\n \"sharpness\": \"cast(stats.sharpness as float)\",\n }\n)\ndataset = Permutation.identity(table).select_columns([\"motion\", \"sharpness\"])\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, shuffle=True)\n"; +export const PyQuickstartTraining = "import torch\nfrom lancedb.streaming import StreamingDataset\n\ndataset = StreamingDataset(table, columns=[\"motion\", \"sharpness\"], shuffle_seed=42)\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, num_workers=0)\n"; export const PyQuickstartVectorSearch1 = "# Search for frames similar to \"a gripper closing on an object\"\nquery_vector = [0.2, 0.8, 0.4, 0.9]\n\n# Ensure you run `pip install polars` beforehand\nresult = (\n table.search(query_vector)\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .to_polars()\n)\nprint(result)\n"; -export const PyQuickstartVectorSearch1Async = "# Search for frames similar to \"a gripper closing on an object\"\nquery_vector = [0.2, 0.8, 0.4, 0.9]\n\n# Ensure you run `pip install polars` beforehand\nasync_result = await (\n await async_table.search(query_vector)\n).select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"]).limit(2).to_polars()\nprint(async_result)\n"; +export const PyQuickstartVectorSearch1Async = "# Search for frames similar to \"a gripper closing on an object\"\nquery_vector = [0.2, 0.8, 0.4, 0.9]\n\n# Ensure you run `pip install polars` beforehand\nasync_result = (\n await (await async_table.search(query_vector))\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .to_polars()\n)\nprint(async_result)\n"; export const TsQuickstartAddData = "await table.add([\n {\n frame_id: \"4\",\n video_id: \"clip-2\",\n caption: \"a gripper lowering a cup onto the table\",\n stats: { motion: 5, sharpness: 4, exposure: 4, framing: 2 },\n embedding: [0.3, 0.9, 0.6, 0.8],\n },\n]);\n"; -export const TsQuickstartAddFeature = "await table.addColumns([\n {\n name: \"quality_score\",\n valueSql:\n \"cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)\",\n },\n]);\n"; - export const TsQuickstartCreateTable = "const table = await db.createTable(\"frames\", data, { mode: \"overwrite\" });\n"; -export const TsQuickstartCurateWithMetadata = "const curated = await table\n .search(queryVector)\n .where(\"stats.motion >= 4\")\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .toArray();\nconsole.table(curated);\n"; - export const TsQuickstartData = "const data = [\n {\n frame_id: \"1\",\n video_id: \"clip-1\",\n caption: \"a robot arm reaching toward a cup\",\n stats: { motion: 3, sharpness: 4, exposure: 4, framing: 3 },\n embedding: [0.7, 0.1, 0.9, 0.7],\n },\n {\n frame_id: \"2\",\n video_id: \"clip-1\",\n caption: \"a two-finger gripper closing on a cup\",\n stats: { motion: 5, sharpness: 4, exposure: 5, framing: 2 },\n embedding: [0.2, 0.9, 0.4, 0.9],\n },\n {\n frame_id: \"3\",\n video_id: \"clip-2\",\n caption: \"a robot arm holding a cup steady\",\n stats: { motion: 2, sharpness: 3, exposure: 3, framing: 4 },\n embedding: [0.9, 0.1, 0.5, 0.4],\n },\n];\n"; export const TsQuickstartMultimodalBytes = "const arrow = await import(\"apache-arrow\");\nconst { readFile } = await import(\"node:fs/promises\");\n\nconst imageBytes = await readFile(\"data/sample-frame.jpg\");\nconst imageSchema = new arrow.Schema([\n new arrow.Field(\"frame_id\", new arrow.Utf8()),\n new arrow.Field(\"caption\", new arrow.Utf8()),\n new arrow.Field(\"image\", new arrow.Binary()),\n new arrow.Field(\n \"embedding\",\n new arrow.FixedSizeList(\n 4,\n new arrow.Field(\"item\", new arrow.Float32(), true),\n ),\n ),\n]);\nconst imageData = lancedb.makeArrowTable(\n [\n {\n frame_id: \"thumb-1\",\n caption: \"Sample frame thumbnail\",\n image: imageBytes,\n embedding: [0.9, 0.1, 0.5, 0.4],\n },\n ],\n { schema: imageSchema },\n);\nconst multimodalTable = await db.createTable(\n \"frame_images\",\n imageData,\n { mode: \"overwrite\" },\n);\n"; -export const TsQuickstartQueryFeature = "const features = await table\n .query()\n .select([\"frame_id\", \"video_id\", \"quality_score\"])\n .toArray();\nconsole.table(features);\n"; - export const TsQuickstartVectorSearch1 = "// Search for frames similar to \"a gripper closing on an object\"\nconst queryVector = [0.2, 0.8, 0.4, 0.9];\n\nconst result = await table\n .search(queryVector)\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .toArray();\nconsole.table(result);\n"; export const RsQuickstartAddData = "let more_data = vec![Frame {\n frame_id: \"4\".to_string(),\n video_id: \"clip-2\".to_string(),\n caption: \"a gripper lowering a cup onto the table\".to_string(),\n stats: Stats {\n motion: 5,\n sharpness: 4,\n exposure: 4,\n framing: 2,\n },\n embedding: [0.3, 0.9, 0.6, 0.8],\n}];\ntable\n .add(frames_to_reader(schema.clone(), &more_data))\n .execute()\n .await\n .unwrap();\n"; -export const RsQuickstartAddFeature = "table\n .add_columns(\n NewColumnTransform::SqlExpressions(vec![(\n \"quality_score\".to_string(),\n \"cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)\"\n .to_string(),\n )]),\n None,\n )\n .await\n .unwrap();\n"; - export const RsQuickstartCreateTable = "use lancedb::database::CreateTableMode;\n\nlet schema = frames_schema();\nlet table = db\n .create_table(\"frames\", frames_to_reader(schema.clone(), &data))\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; -export const RsQuickstartCurateWithMetadata = "let curated = table\n .query()\n .nearest_to(&query_vector)\n .unwrap()\n .only_if(\"stats.motion >= 4\")\n .select(Select::Columns(vec![\n \"frame_id\".to_string(),\n \"video_id\".to_string(),\n \"caption\".to_string(),\n \"_distance\".to_string(),\n ]))\n .limit(2)\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{curated:?}\");\n"; - export const RsQuickstartData = "let data = vec![\n Frame {\n frame_id: \"1\".to_string(),\n video_id: \"clip-1\".to_string(),\n caption: \"a robot arm reaching toward a cup\".to_string(),\n stats: Stats {\n motion: 3,\n sharpness: 4,\n exposure: 4,\n framing: 3,\n },\n embedding: [0.7, 0.1, 0.9, 0.7],\n },\n Frame {\n frame_id: \"2\".to_string(),\n video_id: \"clip-1\".to_string(),\n caption: \"a two-finger gripper closing on a cup\".to_string(),\n stats: Stats {\n motion: 5,\n sharpness: 4,\n exposure: 5,\n framing: 2,\n },\n embedding: [0.2, 0.9, 0.4, 0.9],\n },\n Frame {\n frame_id: \"3\".to_string(),\n video_id: \"clip-2\".to_string(),\n caption: \"a robot arm holding a cup steady\".to_string(),\n stats: Stats {\n motion: 2,\n sharpness: 3,\n exposure: 3,\n framing: 4,\n },\n embedding: [0.9, 0.1, 0.5, 0.4],\n },\n];\n"; -export const RsQuickstartDefineStruct = "use std::sync::Arc;\n\nuse lancedb::arrow::arrow_array::types::Float32Type;\nuse lancedb::arrow::arrow_array::{\n FixedSizeListArray, Int8Array, LargeStringArray, RecordBatch, RecordBatchIterator,\n RecordBatchReader, StructArray,\n};\nuse lancedb::arrow::arrow_schema::{DataType, Field, FieldRef, Fields, Schema};\n\n// Define structs representing the data schema\n#[derive(Debug, Clone)]\nstruct Stats {\n motion: i8,\n sharpness: i8,\n exposure: i8,\n framing: i8,\n}\n\n#[derive(Debug, Clone)]\nstruct Frame {\n frame_id: String,\n video_id: String,\n caption: String,\n stats: Stats,\n embedding: [f32; 4],\n}\n\nfn frames_schema() -> Arc {\n Arc::new(Schema::new(vec![\n Field::new(\"frame_id\", DataType::LargeUtf8, false),\n Field::new(\"video_id\", DataType::LargeUtf8, false),\n Field::new(\"caption\", DataType::LargeUtf8, false),\n Field::new(\n \"stats\",\n DataType::Struct(Fields::from(vec![\n Arc::new(Field::new(\"motion\", DataType::Int8, false)),\n Arc::new(Field::new(\"sharpness\", DataType::Int8, false)),\n Arc::new(Field::new(\"exposure\", DataType::Int8, false)),\n Arc::new(Field::new(\"framing\", DataType::Int8, false)),\n ])),\n false,\n ),\n Field::new(\n \"embedding\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 4),\n false,\n ),\n ]))\n}\n\nfn frames_to_reader(\n schema: Arc,\n rows: &[Frame],\n) -> Box {\n let frame_ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.frame_id.as_str()));\n let video_ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.video_id.as_str()));\n let captions =\n LargeStringArray::from_iter_values(rows.iter().map(|row| row.caption.as_str()));\n\n let motion = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.motion));\n let sharpness = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.sharpness));\n let exposure = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.exposure));\n let framing = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.framing));\n let stats_fields: Vec = vec![\n Arc::new(Field::new(\"motion\", DataType::Int8, false)),\n Arc::new(Field::new(\"sharpness\", DataType::Int8, false)),\n Arc::new(Field::new(\"exposure\", DataType::Int8, false)),\n Arc::new(Field::new(\"framing\", DataType::Int8, false)),\n ];\n let stats = StructArray::new(\n stats_fields.into(),\n vec![\n Arc::new(motion),\n Arc::new(sharpness),\n Arc::new(exposure),\n Arc::new(framing),\n ],\n None,\n );\n\n let embeddings = FixedSizeListArray::from_iter_primitive::(\n rows.iter()\n .map(|row| Some(row.embedding.iter().copied().map(Some).collect::>())),\n 4,\n );\n\n let batch = RecordBatch::try_new(\n schema.clone(),\n vec![\n Arc::new(frame_ids),\n Arc::new(video_ids),\n Arc::new(captions),\n Arc::new(stats),\n Arc::new(embeddings),\n ],\n )\n .unwrap();\n\n Box::new(RecordBatchIterator::new(\n vec![Ok(batch)].into_iter(),\n schema,\n ))\n}\n"; +export const RsQuickstartDefineStruct = "use std::sync::Arc;\n\nuse lancedb::arrow::arrow_array::types::Float32Type;\nuse lancedb::arrow::arrow_array::{\n FixedSizeListArray, Int8Array, LargeStringArray, RecordBatch, RecordBatchIterator,\n RecordBatchReader, StructArray,\n};\nuse lancedb::arrow::arrow_schema::{DataType, Field, FieldRef, Fields, Schema};\n\n// Define structs representing the data schema\n#[derive(Debug, Clone)]\nstruct Stats {\n motion: i8,\n sharpness: i8,\n exposure: i8,\n framing: i8,\n}\n\n#[derive(Debug, Clone)]\nstruct Frame {\n frame_id: String,\n video_id: String,\n caption: String,\n stats: Stats,\n embedding: [f32; 4],\n}\n\nfn frames_schema() -> Arc {\n Arc::new(Schema::new(vec![\n Field::new(\"frame_id\", DataType::LargeUtf8, false),\n Field::new(\"video_id\", DataType::LargeUtf8, false),\n Field::new(\"caption\", DataType::LargeUtf8, false),\n Field::new(\n \"stats\",\n DataType::Struct(Fields::from(vec![\n Arc::new(Field::new(\"motion\", DataType::Int8, false)),\n Arc::new(Field::new(\"sharpness\", DataType::Int8, false)),\n Arc::new(Field::new(\"exposure\", DataType::Int8, false)),\n Arc::new(Field::new(\"framing\", DataType::Int8, false)),\n ])),\n false,\n ),\n Field::new(\n \"embedding\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 4),\n false,\n ),\n ]))\n}\n\nfn frames_to_reader(schema: Arc, rows: &[Frame]) -> Box {\n let frame_ids =\n LargeStringArray::from_iter_values(rows.iter().map(|row| row.frame_id.as_str()));\n let video_ids =\n LargeStringArray::from_iter_values(rows.iter().map(|row| row.video_id.as_str()));\n let captions = LargeStringArray::from_iter_values(rows.iter().map(|row| row.caption.as_str()));\n\n let motion = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.motion));\n let sharpness = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.sharpness));\n let exposure = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.exposure));\n let framing = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.framing));\n let stats_fields: Vec = vec![\n Arc::new(Field::new(\"motion\", DataType::Int8, false)),\n Arc::new(Field::new(\"sharpness\", DataType::Int8, false)),\n Arc::new(Field::new(\"exposure\", DataType::Int8, false)),\n Arc::new(Field::new(\"framing\", DataType::Int8, false)),\n ];\n let stats = StructArray::new(\n stats_fields.into(),\n vec![\n Arc::new(motion),\n Arc::new(sharpness),\n Arc::new(exposure),\n Arc::new(framing),\n ],\n None,\n );\n\n let embeddings = FixedSizeListArray::from_iter_primitive::(\n rows.iter()\n .map(|row| Some(row.embedding.iter().copied().map(Some).collect::>())),\n 4,\n );\n\n let batch = RecordBatch::try_new(\n schema.clone(),\n vec![\n Arc::new(frame_ids),\n Arc::new(video_ids),\n Arc::new(captions),\n Arc::new(stats),\n Arc::new(embeddings),\n ],\n )\n .unwrap();\n\n Box::new(RecordBatchIterator::new(\n vec![Ok(batch)].into_iter(),\n schema,\n ))\n}\n"; export const RsQuickstartMultimodalBytes = "use lancedb::arrow::arrow_array::BinaryArray;\n\nlet image_bytes = std::fs::read(\"data/sample-frame.jpg\").unwrap();\n\nlet image_schema = Arc::new(Schema::new(vec![\n Field::new(\"frame_id\", DataType::LargeUtf8, false),\n Field::new(\"caption\", DataType::LargeUtf8, false),\n Field::new(\"image\", DataType::Binary, false),\n Field::new(\n \"embedding\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 4),\n false,\n ),\n]));\nlet image_embeddings = [[0.9_f32, 0.1, 0.5, 0.4]];\nlet image_batch = RecordBatch::try_new(\n image_schema.clone(),\n vec![\n Arc::new(LargeStringArray::from_iter_values([\"thumb-1\"])),\n Arc::new(LargeStringArray::from_iter_values([\n \"Sample frame thumbnail\",\n ])),\n Arc::new(BinaryArray::from_iter_values([image_bytes.as_slice()])),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::(\n image_embeddings\n .iter()\n .map(|vector| Some(vector.iter().copied().map(Some).collect::>())),\n 4,\n ),\n ),\n ],\n)\n.unwrap();\nlet image_reader: Box = Box::new(RecordBatchIterator::new(\n vec![Ok(image_batch)].into_iter(),\n image_schema,\n));\nlet multimodal_table = db\n .create_table(\"frame_images\", image_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; export const RsQuickstartOutputArray = "let result = table\n .query()\n .nearest_to(&query_vector)\n .unwrap()\n .select(Select::Columns(vec![\n \"frame_id\".to_string(),\n \"video_id\".to_string(),\n \"caption\".to_string(),\n \"_distance\".to_string(),\n ]))\n .limit(2)\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{result:?}\");\n"; -export const RsQuickstartQueryFeature = "let features = table\n .query()\n .select(Select::Columns(vec![\n \"frame_id\".to_string(),\n \"video_id\".to_string(),\n \"quality_score\".to_string(),\n ]))\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{features:?}\");\n"; - export const RsQuickstartVectorSearch1 = "use lancedb::arrow::IntoPolars;\nuse lancedb::query::{ExecutableQuery, QueryBase, Select};\n\n// Search for frames similar to \"a gripper closing on an object\"\nlet query_vector = [0.2, 0.8, 0.4, 0.9];\n\nlet result = table\n .query()\n .nearest_to(&query_vector)\n .unwrap()\n .select(Select::Columns(vec![\n \"frame_id\".to_string(),\n \"video_id\".to_string(),\n \"caption\".to_string(),\n \"_distance\".to_string(),\n ]))\n .limit(2)\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{result:?}\");\n"; diff --git a/docs/web/snippets/read_consistency.mdx b/docs/web/snippets/read_consistency.mdx index f99521a4d..82f9f06c6 100644 --- a/docs/web/snippets/read_consistency.mdx +++ b/docs/web/snippets/read_consistency.mdx @@ -1,4 +1,4 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyReadConsistency = "from datetime import timedelta\nfrom tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-consistency-\") as uri:\n writer = lancedb.connect(uri)\n table = writer.create_table(\"documents\", [{\"id\": 1, \"text\": \"first\"}])\n\n default_reader = lancedb.connect(uri).open_table(\"documents\")\n latest_reader = lancedb.connect(\n uri, read_consistency_interval=timedelta(0)\n ).open_table(\"documents\")\n\n table.add([{\"id\": 2, \"text\": \"second\"}])\n\n default_count = default_reader.count_rows()\n latest_count = latest_reader.count_rows()\n print(f\"Default reader: {default_count} rows\") # 1\n print(f\"Zero-interval reader: {latest_count} rows\") # 2\n\n default_reader.checkout_latest()\n refreshed_count = default_reader.count_rows()\n print(f\"After explicit refresh: {refreshed_count} rows\") # 2\n"; +export const PyReadConsistency = "from datetime import timedelta\n\nimport lancedb\n\nwriter = lancedb.connect(uri)\ntable = writer.create_table(\"documents\", [{\"id\": 1, \"text\": \"first\"}])\n\ndefault_reader = lancedb.connect(uri).open_table(\"documents\")\nlatest_reader = lancedb.connect(\n uri, read_consistency_interval=timedelta(0)\n).open_table(\"documents\")\n\ntable.add([{\"id\": 2, \"text\": \"second\"}])\n\ndefault_count = default_reader.count_rows()\nlatest_count = latest_reader.count_rows()\nprint(f\"Default reader: {default_count} rows\") # 1\nprint(f\"Zero-interval reader: {latest_count} rows\") # 2\n\ndefault_reader.checkout_latest()\nrefreshed_count = default_reader.count_rows()\nprint(f\"After explicit refresh: {refreshed_count} rows\") # 2\n"; diff --git a/docs/web/snippets/search.mdx b/docs/web/snippets/search.mdx index 4d9f0eccb..0ac02f0f1 100644 --- a/docs/web/snippets/search.mdx +++ b/docs/web/snippets/search.mdx @@ -1,12 +1,12 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyBasicFts = "uri = \"data/sample-lancedb\"\ndb = lancedb.connect(uri)\n\ntable = db.create_table(\n \"my_table_fts\",\n data=[\n {\"vector\": [3.1, 4.1], \"text\": \"Frodo was a happy puppy\"},\n {\"vector\": [5.9, 26.5], \"text\": \"There are several kittens playing\"},\n ],\n mode=\"overwrite\",\n)\n\ntable.create_fts_index(\"text\")\ntable.search(\"puppy\").limit(10).select([\"text\"]).to_list()\n# [{'text': 'Frodo was a happy puppy', '_score': 0.6931471824645996}]\n# ...\n"; +export const PyBasicFts = "import lancedb\n\nuri = \"data/sample-lancedb\"\ndb = lancedb.connect(uri)\n\ntable = db.create_table(\n \"my_table_fts\",\n data=[\n {\"vector\": [3.1, 4.1], \"text\": \"Frodo was a happy puppy\"},\n {\"vector\": [5.9, 26.5], \"text\": \"There are several kittens playing\"},\n ],\n mode=\"overwrite\",\n)\n\ntable.create_fts_index(\"text\")\ntable.search(\"puppy\").limit(10).select([\"text\"]).to_list()\n# [{'text': 'Frodo was a happy puppy', '_score': 0.6931471824645996}]\n# ...\n"; -export const PyBasicFtsAsync = "uri = \"data/sample-lancedb\"\nasync_db = await lancedb.connect_async(uri)\n\nasync_tbl = await async_db.create_table(\n \"my_table_fts_async\",\n data=[\n {\"vector\": [3.1, 4.1], \"text\": \"Frodo was a happy puppy\"},\n {\"vector\": [5.9, 26.5], \"text\": \"There are several kittens playing\"},\n ],\n mode=\"overwrite\",\n)\n\n# async API uses our native FTS algorithm\nawait async_tbl.create_index(\"text\", config=FTS())\nawait (await async_tbl.search(\"puppy\")).select([\"text\"]).limit(10).to_list()\n# [{'text': 'Frodo was a happy puppy', '_score': 0.6931471824645996}]\n# ...\n"; +export const PyBasicFtsAsync = "import lancedb\n\nuri = \"data/sample-lancedb\"\nasync_db = await lancedb.connect_async(uri)\n\nasync_tbl = await async_db.create_table(\n \"my_table_fts_async\",\n data=[\n {\"vector\": [3.1, 4.1], \"text\": \"Frodo was a happy puppy\"},\n {\"vector\": [5.9, 26.5], \"text\": \"There are several kittens playing\"},\n ],\n mode=\"overwrite\",\n)\n\n# async API uses our native FTS algorithm\nawait async_tbl.create_index(\"text\", config=FTS())\nawait (await async_tbl.search(\"puppy\")).select([\"text\"]).limit(10).to_list()\n# [{'text': 'Frodo was a happy puppy', '_score': 0.6931471824645996}]\n# ...\n"; -export const PyBasicHybridSearch = "data = [\n {\"text\": \"rebel spaceships striking from a hidden base\"},\n {\"text\": \"have won their first victory against the evil Galactic Empire\"},\n {\"text\": \"during the battle rebel spies managed to steal secret plans\"},\n {\"text\": \"to the Empire's ultimate weapon the Death Star\"},\n]\nuri = \"data/sample-lancedb\"\ndb = lancedb.connect(uri)\ntable = db.create_table(\"documents\", schema=Documents)\n# ingest docs with auto-vectorization\ntable.add(data)\n# Create a fts index before the hybrid search\ntable.create_fts_index(\"text\")\n# hybrid search with default re-ranker\ntable.search(\"flower moon\", query_type=\"hybrid\").to_pandas()\n"; +export const PyBasicHybridSearch = "import lancedb\n\ndata = [\n {\"text\": \"rebel spaceships striking from a hidden base\"},\n {\"text\": \"have won their first victory against the evil Galactic Empire\"},\n {\"text\": \"during the battle rebel spies managed to steal secret plans\"},\n {\"text\": \"to the Empire's ultimate weapon the Death Star\"},\n]\nuri = \"data/sample-lancedb\"\ndb = lancedb.connect(uri)\ntable = db.create_table(\"documents\", schema=Documents)\n# ingest docs with auto-vectorization\ntable.add(data)\n# Create a fts index before the hybrid search\ntable.create_fts_index(\"text\")\n# hybrid search with default re-ranker\ntable.search(\"flower moon\", query_type=\"hybrid\").to_pandas()\n"; -export const PyBasicHybridSearchAsync = "uri = \"data/sample-lancedb\"\nasync_db = await lancedb.connect_async(uri)\ndata = [\n {\"text\": \"rebel spaceships striking from a hidden base\"},\n {\"text\": \"have won their first victory against the evil Galactic Empire\"},\n {\"text\": \"during the battle rebel spies managed to steal secret plans\"},\n {\"text\": \"to the Empire's ultimate weapon the Death Star\"},\n]\nasync_tbl = await async_db.create_table(\"documents_async\", schema=Documents)\n# ingest docs with auto-vectorization\nawait async_tbl.add(data)\n# Create a fts index before the hybrid search\nawait async_tbl.create_index(\"text\", config=FTS())\ntext_query = \"flower moon\"\n# hybrid search with default re-ranker\nawait (await async_tbl.search(\"flower moon\", query_type=\"hybrid\")).to_pandas()\n"; +export const PyBasicHybridSearchAsync = "import lancedb\n\nuri = \"data/sample-lancedb\"\nasync_db = await lancedb.connect_async(uri)\ndata = [\n {\"text\": \"rebel spaceships striking from a hidden base\"},\n {\"text\": \"have won their first victory against the evil Galactic Empire\"},\n {\"text\": \"during the battle rebel spies managed to steal secret plans\"},\n {\"text\": \"to the Empire's ultimate weapon the Death Star\"},\n]\nasync_tbl = await async_db.create_table(\"documents_async\", schema=Documents)\n# ingest docs with auto-vectorization\nawait async_tbl.add(data)\n# Create a fts index before the hybrid search\nawait async_tbl.create_index(\"text\", config=FTS())\ntext_query = \"flower moon\"\n# hybrid search with default re-ranker\nawait (await async_tbl.search(\"flower moon\", query_type=\"hybrid\")).to_pandas()\n"; export const PyBatchSearch = "# Load a batch of query embeddings\nquery_dataset = load_dataset(\n \"sunhaozhepy/ag_news_sbert_keywords_embeddings\", split=\"test[5000:5005]\"\n)\nquery_embeds = query_dataset[\"keywords_embeddings\"]\nbatch_results = table.search(query_embeds).limit(5).to_pandas()\nprint(batch_results)\n"; @@ -14,10 +14,10 @@ export const PyBruteForceSearch = "tbl.search(np.random.random((1536))).limit(3) export const PyBypassVectorIndex = "table.search(embedding).bypass_vector_index().limit(5).to_pandas()\n"; -export const PyClassDefinition = "class Metadata(BaseModel):\n source: str\n timestamp: datetime\n\n\nclass Document(BaseModel):\n content: str\n meta: Metadata\n\n\nclass LanceSchema(LanceModel):\n id: str\n vector: Vector(1536)\n payload: Document\n"; - export const PyClassDocuments = "class Documents(LanceModel):\n vector: Vector(embeddings.ndims()) = embeddings.VectorField()\n text: str = embeddings.SourceField()\n"; +export const PyClassDefinition = "class Metadata(BaseModel):\n source: str\n timestamp: datetime\n\n\nclass Document(BaseModel):\n content: str\n meta: Metadata\n\n\nclass LanceSchema(LanceModel):\n id: str\n vector: Vector(1536)\n payload: Document\n"; + export const PyConfigureDistanceMetric = "tbl.search(np.random.random((1536))).distance_type(\"cosine\").limit(10).to_list()\n"; export const PyCreateTableAsyncWithNestedSchema = "# Let's add 100 sample rows to our dataset\ndata = [\n LanceSchema(\n id=f\"id{i}\",\n vector=np.random.randn(1536),\n payload=Document(\n content=f\"document{i}\",\n meta=Metadata(source=f\"source{i % 10}\", timestamp=datetime.now()),\n ),\n )\n for i in range(100)\n]\n\nasync_tbl = await async_db.create_table(\n \"documents_async\", data=data, mode=\"overwrite\"\n)\n"; @@ -26,9 +26,9 @@ export const PyCreateTableWithNestedSchema = "# Let's add 100 sample rows to our export const PyExactVsApproximateDistances = "# Indexed ANN search without refinement (fast, approximate `_distance`)\nfast_results = (\n table.search(embedding)\n .limit(10)\n .to_pandas()\n)\n\n# Recompute distances on full vectors for reranked candidates\nexact_distance_results = (\n table.search(embedding)\n .limit(10)\n .refine_factor(1)\n .to_pandas()\n)\n\n# Rerank a larger candidate set for better recall (higher latency)\nhigher_recall_results = (\n table.search(embedding)\n .limit(10)\n .refine_factor(20)\n .to_pandas()\n)\n"; -export const PyExhaustiveSearch = "uri = \"data/sample-lancedb\"\ndb = lancedb.connect(uri)\ndata = [\n {\"vector\": row, \"item\": f\"item {i}\"}\n for i, row in enumerate(np.random.random((10_000, 1536)).astype(\"float32\"))\n]\ntbl = db.create_table(\"vector_search\", data=data, mode=\"overwrite\")\ntbl.search(np.random.random((1536))).limit(10).to_list()\n"; +export const PyExhaustiveSearch = "import lancedb\n\nuri = \"data/sample-lancedb\"\ndb = lancedb.connect(uri)\ndata = [\n {\"vector\": row, \"item\": f\"item {i}\"}\n for i, row in enumerate(np.random.random((10_000, 1536)).astype(\"float32\"))\n]\ntbl = db.create_table(\"vector_search\", data=data, mode=\"overwrite\")\ntbl.search(np.random.random((1536))).limit(10).to_list()\n"; -export const PyExhaustiveSearchAsync = "uri = \"data/sample-lancedb\"\nasync_db = await lancedb.connect_async(uri)\ndata = [\n {\"vector\": row, \"item\": f\"item {i}\"}\n for i, row in enumerate(np.random.random((10_000, 1536)).astype(\"float32\"))\n]\nasync_tbl = await async_db.create_table(\n \"vector_search_async\", data=data, mode=\"overwrite\"\n)\n(await (await async_tbl.search(np.random.random((1536)))).limit(10).to_list())\n"; +export const PyExhaustiveSearchAsync = "import lancedb\n\nuri = \"data/sample-lancedb\"\nasync_db = await lancedb.connect_async(uri)\ndata = [\n {\"vector\": row, \"item\": f\"item {i}\"}\n for i, row in enumerate(np.random.random((10_000, 1536)).astype(\"float32\"))\n]\nasync_tbl = await async_db.create_table(\n \"vector_search_async\", data=data, mode=\"overwrite\"\n)\n(await (await async_tbl.search(np.random.random((1536)))).limit(10).to_list())\n"; export const PyExhaustiveSearchAsyncCosine = "(\n await (await async_tbl.search(np.random.random((1536))))\n .distance_type(\"cosine\")\n .limit(10)\n .to_list()\n)\n"; diff --git a/docs/web/snippets/search_examples.mdx b/docs/web/snippets/search_examples.mdx index a9aeb5e7f..806f129d0 100644 --- a/docs/web/snippets/search_examples.mdx +++ b/docs/web/snippets/search_examples.mdx @@ -1,14 +1,14 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyFilterSearch = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-search-\") as uri:\n db = lancedb.connect(uri)\n table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n )\n rows = (\n table.search([0.0, 1.0])\n .where(\"category = 'animals'\", prefilter=True)\n .select([\"id\", \"text\", \"category\", \"_distance\"])\n .limit(2)\n .to_list()\n )\n print(rows)\n"; +export const PyFilterSearch = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n)\nrows = (\n table.search([0.0, 1.0])\n .where(\"category = 'animals'\", prefilter=True)\n .select([\"id\", \"text\", \"category\", \"_distance\"])\n .limit(2)\n .to_list()\n)\nprint(rows)\n"; -export const PyHybridSearch = "from tempfile import TemporaryDirectory\n\nimport lancedb\nfrom lancedb.index import FTS\n\nwith TemporaryDirectory(prefix=\"lancedb-search-\") as uri:\n db = lancedb.connect(uri)\n table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n )\n from lancedb.rerankers import RRFReranker\n\n table.create_index(\"text\", config=FTS())\n rows = (\n table.search(\n query_type=\"hybrid\", vector_column_name=\"vector\", fts_columns=\"text\"\n )\n .vector([1.0, 0.0])\n .text(\"puppy\")\n .rerank(RRFReranker())\n .limit(2)\n .to_list()\n )\n print(rows)\n"; +export const PyHybridSearch = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n)\nfrom lancedb.rerankers import RRFReranker\n\ntable.create_index(\"text\", config=FTS())\nrows = (\n table.search(\n query_type=\"hybrid\", vector_column_name=\"vector\", fts_columns=\"text\"\n )\n .vector([1.0, 0.0])\n .text(\"puppy\")\n .rerank(RRFReranker())\n .limit(2)\n .to_list()\n)\nprint(rows)\n"; -export const PyQueryPlan = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-search-\") as uri:\n db = lancedb.connect(uri)\n table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n )\n query = table.search([1.0, 0.0]).select([\"id\", \"text\", \"_distance\"]).limit(2)\n print(\"Plan:\", query.explain_plan())\n print(\"Measured execution:\", query.analyze_plan())\n rows = query.to_list()\n print(rows)\n"; +export const PyQueryPlan = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n)\nquery = table.search([1.0, 0.0]).select([\"id\", \"text\", \"_distance\"]).limit(2)\nprint(\"Plan:\", query.explain_plan())\nprint(\"Measured execution:\", query.analyze_plan())\nrows = query.to_list()\nprint(rows)\n"; -export const PyTextSearch = "from tempfile import TemporaryDirectory\n\nimport lancedb\nfrom lancedb.index import FTS\n\nwith TemporaryDirectory(prefix=\"lancedb-search-\") as uri:\n db = lancedb.connect(uri)\n table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n },\n ],\n )\n table.create_index(\"text\", config=FTS())\n rows = (\n table.search(\"puppy\", query_type=\"fts\", fts_columns=\"text\")\n .select([\"id\", \"text\", \"_score\"])\n .limit(2)\n .to_list()\n )\n print(rows)\n"; +export const PyTextSearch = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n },\n ],\n)\ntable.create_index(\"text\", config=FTS())\nrows = (\n table.search(\"puppy\", query_type=\"fts\", fts_columns=\"text\")\n .select([\"id\", \"text\", \"_score\"])\n .limit(2)\n .to_list()\n)\nprint(rows)\n"; -export const PyVectorSearch = "from tempfile import TemporaryDirectory\n\nimport lancedb\n\nwith TemporaryDirectory(prefix=\"lancedb-search-\") as uri:\n db = lancedb.connect(uri)\n table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n )\n rows = (\n table.search([1.0, 0.0])\n .distance_type(\"l2\")\n .select([\"id\", \"text\", \"_distance\"])\n .limit(2)\n .to_list()\n )\n print(rows)\n"; +export const PyVectorSearch = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n)\nrows = (\n table.search([1.0, 0.0])\n .distance_type(\"l2\")\n .select([\"id\", \"text\", \"_distance\"])\n .limit(2)\n .to_list()\n)\nprint(rows)\n"; export const TsFilterSearchBody = "const lancedb = await import(\"@lancedb/lancedb\");\nconst { mkdtemp, rm } = await import(\"node:fs/promises\");\nconst { tmpdir } = await import(\"node:os\");\nconst { join } = await import(\"node:path\");\nconst uri = await mkdtemp(join(tmpdir(), \"lancedb-search-\"));\ntry {\n const db = await lancedb.connect(uri);\n const table = await db.createTable(\"documents\", [\n {\n id: 1,\n text: \"A puppy playing in the park\",\n category: \"animals\",\n vector: [1.0, 0.0],\n },\n {\n id: 2,\n text: \"A dog resting at home\",\n category: \"animals\",\n vector: [0.9, 0.1],\n },\n {\n id: 3,\n text: \"A guide to growing tomatoes\",\n category: \"gardening\",\n vector: [0.0, 1.0],\n },\n ]);\n const rows = await table\n .vectorSearch([0.0, 1.0])\n .where(\"category = 'animals'\")\n .select([\"id\", \"text\", \"category\", \"_distance\"])\n .limit(2)\n .toArray();\n console.log(rows);\n"; diff --git a/docs/web/snippets/storage.mdx b/docs/web/snippets/storage.mdx index 942fd8aec..6eec4c580 100644 --- a/docs/web/snippets/storage.mdx +++ b/docs/web/snippets/storage.mdx @@ -1,36 +1,32 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyStorageAzureAccount = "db = lancedb.connect(\n \"az://my-container/my-database\",\n storage_options={\n \"account_name\": \"some-account\",\n \"account_key\": \"some-key\",\n },\n)\n"; +export const PyStorageAzureAccount = "import lancedb\n\ndb = lancedb.connect(\n \"az://my-container/my-database\",\n storage_options={\n \"account_name\": \"some-account\",\n \"account_key\": \"some-key\",\n },\n)\n"; -export const PyStorageAzureSas = "db = lancedb.connect(\n \"az://my-container/my-database\",\n storage_options={\n \"azure_storage_account_name\": \"some-account\",\n \"azure_storage_sas_token\": \"\",\n },\n)\n"; +export const PyStorageAzureSas = "import lancedb\n\ndb = lancedb.connect(\n \"az://my-container/my-database\",\n storage_options={\n \"azure_storage_account_name\": \"some-account\",\n \"azure_storage_sas_token\": \"\",\n },\n)\n"; -export const PyStorageConnectAzure = "db = lancedb.connect(\"az://bucket/path\")\n"; +export const PyStorageConnectAzure = "import lancedb\n\ndb = lancedb.connect(\"az://bucket/path\")\n"; -export const PyStorageConnectGcs = "db = lancedb.connect(\"gs://bucket/path\")\n"; +export const PyStorageConnectGcs = "import lancedb\n\ndb = lancedb.connect(\"gs://bucket/path\")\n"; -export const PyStorageConnectS3 = "db = lancedb.connect(\"s3://bucket/path\")\n"; +export const PyStorageConnectS3 = "import lancedb\n\ndb = lancedb.connect(\"s3://bucket/path\")\n"; -export const PyStorageConnectTimeout = "db = lancedb.connect(\n \"s3://bucket/path\",\n storage_options={\"timeout\": \"60s\"},\n)\n"; +export const PyStorageConnectTimeout = "import lancedb\n\ndb = lancedb.connect(\n \"s3://bucket/path\",\n storage_options={\"timeout\": \"60s\"},\n)\n"; -export const PyStorageGcsServiceAccount = "db = lancedb.connect(\n \"gs://my-bucket/my-database\",\n storage_options={\n \"service_account\": \"path/to/service-account.json\",\n },\n)\n"; +export const PyStorageGcsServiceAccount = "import lancedb\n\ndb = lancedb.connect(\n \"gs://my-bucket/my-database\",\n storage_options={\n \"service_account\": \"path/to/service-account.json\",\n },\n)\n"; -export const PyStorageS3Ddb = "db = lancedb.connect(\n \"s3+ddb://bucket/path?ddbTableName=my-dynamodb-table\",\n)\n"; +export const PyStorageS3Ddb = "import lancedb\n\ndb = lancedb.connect(\n \"s3+ddb://bucket/path?ddbTableName=my-dynamodb-table\",\n)\n"; -export const PyStorageS3DdbLocal = "db = lancedb.connect(\n \"s3+ddb://bucket/path?ddbTableName=my-dynamodb-table\",\n storage_options={\n \"endpoint\": \"http://localhost:4566\",\n \"dynamodb_endpoint\": \"http://localhost:4566\",\n \"allow_http\": \"true\",\n },\n)\n"; +export const PyStorageS3DdbLocal = "import lancedb\n\ndb = lancedb.connect(\n \"s3+ddb://bucket/path?ddbTableName=my-dynamodb-table\",\n storage_options={\n \"endpoint\": \"http://localhost:4566\",\n \"dynamodb_endpoint\": \"http://localhost:4566\",\n \"allow_http\": \"true\",\n },\n)\n"; -export const PyStorageS3Express = "db = lancedb.connect(\n \"s3://my-bucket--use1-az4--x-s3/path\",\n storage_options={\n \"region\": \"us-east-1\",\n \"s3_express\": \"true\",\n },\n)\n"; +export const PyStorageS3Express = "import lancedb\n\ndb = lancedb.connect(\n \"s3://my-bucket--use1-az4--x-s3/path\",\n storage_options={\n \"region\": \"us-east-1\",\n \"s3_express\": \"true\",\n },\n)\n"; -export const PyStorageS3Minio = "db = lancedb.connect(\n \"s3://bucket/path\",\n storage_options={\n \"region\": \"us-east-1\",\n \"endpoint\": \"http://minio:9000\",\n },\n)\n"; +export const PyStorageS3Minio = "import lancedb\n\ndb = lancedb.connect(\n \"s3://bucket/path\",\n storage_options={\n \"region\": \"us-east-1\",\n \"endpoint\": \"http://minio:9000\",\n },\n)\n"; -export const PyStorageS3SseKms = "db = lancedb.connect(\n \"s3://bucket/path\",\n storage_options={\n \"aws_server_side_encryption\": \"aws:kms\",\n \"aws_sse_kms_key_id\": \"\",\n },\n)\n"; +export const PyStorageS3SseKms = "import lancedb\n\ndb = lancedb.connect(\n \"s3://bucket/path\",\n storage_options={\n \"aws_server_side_encryption\": \"aws:kms\",\n \"aws_sse_kms_key_id\": \"\",\n },\n)\n"; export const PyStorageTableTimeout = "table = db.create_table(\n \"table\",\n [{\"a\": 1, \"b\": 2}],\n storage_options={\"timeout\": \"60s\"},\n)\n"; -export const PyStorageTigrisConnect = "db = lancedb.connect(\n \"s3://your-bucket/path\",\n storage_options={\n \"endpoint\": \"https://t3.storage.dev\",\n \"region\": \"auto\",\n },\n)\n"; - -export const PyStorageCosConnect = "db = lancedb.connect(\n \"cos://my-bucket/my-database\",\n storage_options={\n \"secret_id\": \"\",\n \"secret_key\": \"\",\n \"region\": \"ap-guangzhou\",\n },\n)\n"; - -export const PyStorageGoosefsConnect = "db = lancedb.connect(\"goosefs://my-namespace/my-database\")\n"; +export const PyStorageTigrisConnect = "import lancedb\n\ndb = lancedb.connect(\n \"s3://your-bucket/path\",\n storage_options={\n \"endpoint\": \"https://t3.storage.dev\",\n \"region\": \"auto\",\n },\n)\n"; export const TsStorageAzureAccount = "async function storageAzureAccount() {\n const db = await lancedb.connect(\n \"az://my-container/my-database\",\n {\n storageOptions: {\n accountName: \"some-account\",\n accountKey: \"some-key\",\n },\n },\n );\n return db;\n}\n"; @@ -60,5 +56,3 @@ export const TsStorageTableTimeout = "async function storageTableTimeout() {\n export const TsStorageTigrisConnect = "async function storageTigrisConnect() {\n const db = await lancedb.connect(\n \"s3://your-bucket/path\",\n {\n storageOptions: {\n endpoint: \"https://t3.storage.dev\",\n region: \"auto\",\n },\n },\n );\n return db;\n}\n"; -export const TsStorageGoosefsConnect = "async function storageGoosefsConnect() {\n const db = await lancedb.connect(\"goosefs://my-namespace/my-database\");\n return db;\n}\n"; - diff --git a/docs/web/snippets/tables.mdx b/docs/web/snippets/tables.mdx index 28b9ce172..f4b0a1af8 100644 --- a/docs/web/snippets/tables.mdx +++ b/docs/web/snippets/tables.mdx @@ -14,7 +14,7 @@ export const PyAddDataToTable = "import pyarrow as pa\n\n# create an empty table export const PyAddFeatureColumnsSql = "table.add_columns(\n {\n \"price_per_id\": \"cast(price / id as float)\",\n \"price_log\": \"ln(price)\",\n \"price_score\": \"cast(price / (price + 100.0) as float)\",\n }\n)\n"; -export const PyAddFromDataset = "import pyarrow.dataset as ds\n\ndataset = ds.dataset(data_path, format=\"parquet\")\ndb = tmp_db\ntable = db.create_table(\"my_table\", schema=dataset.schema, mode=\"overwrite\")\ntable.add(dataset)\n"; +export const PyAddFromDataset = "table = db.create_table(\"my_table\", schema=dataset.schema, mode=\"overwrite\")\ntable.add(dataset)\n"; export const PyAlterColumnsDataType = "# Change price from int32 to int64 for larger numbers\ntable.alter_columns({\"path\": \"price\", \"data_type\": pa.int64()})\n"; @@ -24,9 +24,9 @@ export const PyAlterColumnsNullable = "# Make the name column nullable\ntable.al export const PyAlterColumnsRename = "# Rename discount_price to sale_price\ntable.alter_columns({\"path\": \"discount_price\", \"rename\": \"sale_price\"})\n"; -export const PyAlterColumnsWithExpression = "# For custom transforms, create a new column from a SQL expression.\nexpression_table = tmp_db.create_table(\n \"schema_evolution_expression_example\",\n [{\"id\": 1, \"price_text\": \"$100\"}],\n mode=\"overwrite\",\n)\n\nexpression_table.add_columns(\n {\"price_numeric\": \"cast(replace(price_text, '$', '') as int)\"}\n)\nexpression_table.drop_columns([\"price_text\"])\nexpression_table.alter_columns({\"path\": \"price_numeric\", \"rename\": \"price\"})\n"; +export const PyAlterColumnsWithExpression = "# For custom transforms, create a new column from a SQL expression.\nexpression_table = db.create_table(\n \"schema_evolution_expression_example\",\n [{\"id\": 1, \"price_text\": \"$100\"}],\n mode=\"overwrite\",\n)\n\nexpression_table.add_columns(\n {\"price_numeric\": \"cast(replace(price_text, '$', '') as int)\"}\n)\nexpression_table.drop_columns([\"price_text\"])\nexpression_table.alter_columns({\"path\": \"price_numeric\", \"rename\": \"price\"})\n"; -export const PyAlterVectorColumn = "vector_dim = 768 # Your embedding dimension\ntable_name = \"vector_alter_example\"\ndb = tmp_db\ndata = [\n {\n \"id\": 1,\n \"embedding\": np.random.random(vector_dim).tolist(),\n },\n]\ntable = db.create_table(table_name, data, mode=\"overwrite\")\n\ntable.alter_columns(\n dict(path=\"embedding\", data_type=pa.list_(pa.float32(), vector_dim))\n)\n"; +export const PyAlterVectorColumn = "data = [\n {\n \"id\": 1,\n \"embedding\": np.random.random(vector_dim).tolist(),\n },\n]\ntable = db.create_table(table_name, data, mode=\"overwrite\")\n\ntable.alter_columns(\n dict(path=\"embedding\", data_type=pa.list_(pa.float32(), vector_dim))\n)\n"; export const PyBatchDataInsertion = "import pyarrow as pa\n\ndef make_batches():\n for i in range(5): # Create 5 batches\n yield pa.RecordBatch.from_arrays(\n [\n pa.array([[3.1, 4.1], [5.9, 26.5]], pa.list_(pa.float32(), 2)),\n pa.array([f\"item{i * 2 + 1}\", f\"item{i * 2 + 2}\"]),\n pa.array([float((i * 2 + 1) * 10), float((i * 2 + 2) * 10)]),\n ],\n [\"vector\", \"item\", \"price\"],\n )\n\nschema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 2)),\n pa.field(\"item\", pa.utf8()),\n pa.field(\"price\", pa.float32()),\n ]\n)\n# Create table with batches\ntable_name = \"batch_ingestion_example\"\ntable = db.create_table(table_name, make_batches(), schema=schema, mode=\"overwrite\")\n"; @@ -42,33 +42,33 @@ export const PyBranchUpsertToMain = "# This is a row-level upsert, not a merge o export const PyBranchWrite = "# Writes land on the branch handle only; main is left untouched.\nbranch.add([{\"id\": 4, \"author\": \"Lancelot\", \"quote\": \"For the realm!\"}])\nprint(branch.count_rows()) # 4 rows on the branch\nprint(table.count_rows()) # 3 rows; main is unaffected\n\n# List every branch, each mapped to its metadata (including its fork point).\nprint(table.branches.list())\n"; -export const PyConsistencyCheckoutLatest = "uri = str(tmp_db.uri)\nwriter_db = lancedb.connect(uri)\nreader_db = lancedb.connect(uri)\nwriter_table = writer_db.create_table(\n \"consistency_checkout_latest_table\", [{\"id\": 1}], mode=\"overwrite\"\n)\nreader_table = reader_db.open_table(\"consistency_checkout_latest_table\")\n\nwriter_table.add([{\"id\": 2}])\nrows_before_refresh = reader_table.count_rows()\nprint(f\"Rows before checkout_latest: {rows_before_refresh}\")\n\nreader_table.checkout_latest()\nrows_after_refresh = reader_table.count_rows()\nprint(f\"Rows after checkout_latest: {rows_after_refresh}\")\n"; +export const PyConsistencyCheckoutLatest = "import lancedb\n\nwriter_db = lancedb.connect(uri)\nreader_db = lancedb.connect(uri)\nwriter_table = writer_db.create_table(\n \"consistency_checkout_latest_table\", [{\"id\": 1}], mode=\"overwrite\"\n)\nreader_table = reader_db.open_table(\"consistency_checkout_latest_table\")\n\nwriter_table.add([{\"id\": 2}])\nrows_before_refresh = reader_table.count_rows()\nprint(f\"Rows before checkout_latest: {rows_before_refresh}\")\n\nreader_table.checkout_latest()\nrows_after_refresh = reader_table.count_rows()\nprint(f\"Rows after checkout_latest: {rows_after_refresh}\")\n"; -export const PyConsistencyEventual = "from datetime import timedelta\n\nuri = str(tmp_db.uri)\nwriter_db = lancedb.connect(uri)\nreader_db = lancedb.connect(uri, read_consistency_interval=timedelta(seconds=3600))\nwriter_table = writer_db.create_table(\n \"consistency_eventual_table\", [{\"id\": 1}], mode=\"overwrite\"\n)\nreader_table = reader_db.open_table(\"consistency_eventual_table\")\nwriter_table.add([{\"id\": 2}])\nrows_after_write = reader_table.count_rows()\nprint(f\"Rows visible before eventual refresh interval: {rows_after_write}\")\n"; +export const PyConsistencyEventual = "import lancedb\nfrom datetime import timedelta\n\nwriter_db = lancedb.connect(uri)\nreader_db = lancedb.connect(uri, read_consistency_interval=timedelta(seconds=3600))\nwriter_table = writer_db.create_table(\n \"consistency_eventual_table\", [{\"id\": 1}], mode=\"overwrite\"\n)\nreader_table = reader_db.open_table(\"consistency_eventual_table\")\nwriter_table.add([{\"id\": 2}])\nrows_after_write = reader_table.count_rows()\nprint(f\"Rows visible before eventual refresh interval: {rows_after_write}\")\n"; -export const PyConsistencyStrong = "from datetime import timedelta\n\nuri = str(tmp_db.uri)\nwriter_db = lancedb.connect(uri)\nreader_db = lancedb.connect(uri, read_consistency_interval=timedelta(0))\nwriter_table = writer_db.create_table(\n \"consistency_strong_table\", [{\"id\": 1}], mode=\"overwrite\"\n)\nreader_table = reader_db.open_table(\"consistency_strong_table\")\nwriter_table.add([{\"id\": 2}])\nrows_after_write = reader_table.count_rows()\nprint(f\"Rows visible with strong consistency: {rows_after_write}\")\n"; +export const PyConsistencyStrong = "import lancedb\nfrom datetime import timedelta\n\nwriter_db = lancedb.connect(uri)\nreader_db = lancedb.connect(uri, read_consistency_interval=timedelta(0))\nwriter_table = writer_db.create_table(\n \"consistency_strong_table\", [{\"id\": 1}], mode=\"overwrite\"\n)\nreader_table = reader_db.open_table(\"consistency_strong_table\")\nwriter_table.add([{\"id\": 2}])\nrows_after_write = reader_table.count_rows()\nprint(f\"Rows visible with strong consistency: {rows_after_write}\")\n"; -export const PyCreateEmptyTable = "import pyarrow as pa\n\nschema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 2)),\n pa.field(\"item\", pa.string()),\n pa.field(\"price\", pa.float32()),\n ]\n)\ndb = tmp_db\ntbl = db.create_table(\"test_empty_table\", schema=schema, mode=\"overwrite\")\n"; +export const PyCreateEmptyTable = "tbl = db.create_table(\"test_empty_table\", schema=schema, mode=\"overwrite\")\n"; -export const PyCreateEmptyTablePydantic = "from lancedb.pydantic import LanceModel, Vector\n\nclass Item(LanceModel):\n vector: Vector(2)\n item: str\n price: float\n\ndb = tmp_db\ntbl = db.create_table(\n \"test_empty_table_new\", schema=Item.to_arrow_schema(), mode=\"overwrite\"\n)\n"; +export const PyCreateEmptyTablePydantic = "tbl = db.create_table(\n \"test_empty_table_new\", schema=Item.to_arrow_schema(), mode=\"overwrite\"\n)\n"; export const PyCreateTableConflictHandling = "# Idempotent open: reuse the existing table if it exists.\n# The provided data is ignored; the schema is validated against the\n# existing table and a mismatch raises an error.\ntbl = db.create_table(\"conflict_table\", data, exist_ok=True)\n\n# Overwrite: drop the existing table and create a new one with the\n# provided data. This permanently discards the old table's data.\ntbl = db.create_table(\"conflict_table\", data, mode=\"overwrite\")\n"; -export const PyCreateTableCustomSchema = "import pyarrow as pa\n\ncustom_schema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 4)),\n pa.field(\"lat\", pa.float32()),\n pa.field(\"long\", pa.float32()),\n ]\n)\n\ndata = [\n {\"vector\": [1.1, 1.2, 1.3, 1.4], \"lat\": 45.5, \"long\": -122.7},\n {\"vector\": [0.2, 1.8, 0.4, 3.6], \"lat\": 40.1, \"long\": -74.1},\n]\ndb = tmp_db\ntbl = db.create_table(\n \"my_table_custom_schema\", data, schema=custom_schema, mode=\"overwrite\"\n)\n"; +export const PyCreateTableCustomSchema = "tbl = db.create_table(\n \"my_table_custom_schema\", data, schema=custom_schema, mode=\"overwrite\"\n)\n"; -export const PyCreateTableFromArrow = "import numpy as np\nimport pyarrow as pa\n\ndim = 16\ntotal = 2\nschema = pa.schema(\n [pa.field(\"vector\", pa.list_(pa.float16(), dim)), pa.field(\"text\", pa.string())]\n)\ndata = pa.Table.from_arrays(\n [\n pa.array(\n [np.random.randn(dim).astype(np.float16) for _ in range(total)],\n pa.list_(pa.float16(), dim),\n ),\n pa.array([\"foo\", \"bar\"]),\n ],\n [\"vector\", \"text\"],\n)\ndb = tmp_db\ntbl = db.create_table(\"f16_tbl\", data, schema=schema, mode=\"overwrite\")\n"; +export const PyCreateTableFromArrow = "tbl = db.create_table(\"f16_tbl\", data, schema=schema, mode=\"overwrite\")\n"; -export const PyCreateTableFromDicts = "data = [\n {\"vector\": [1.1, 1.2], \"lat\": 45.5, \"long\": -122.7},\n {\"vector\": [0.2, 1.8], \"lat\": 40.1, \"long\": -74.1},\n]\ndb = tmp_db\ndb.create_table(\"test_table\", data, mode=\"overwrite\")\ntbl = db[\"test_table\"]\ntbl.head()\n"; +export const PyCreateTableFromDicts = "db.create_table(\"test_table\", data, mode=\"overwrite\")\ntbl = db[\"test_table\"]\ntbl.head()\n"; -export const PyCreateTableFromIterator = "import pyarrow as pa\n\nschema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 4)),\n pa.field(\"item\", pa.utf8()),\n pa.field(\"price\", pa.float32()),\n ]\n)\n\ndef make_batches():\n for i in range(5):\n yield pa.RecordBatch.from_arrays(\n [\n pa.array(\n [[3.1, 4.1, 5.1, 6.1], [5.9, 26.5, 4.7, 32.8]],\n pa.list_(pa.float32(), 4),\n ),\n pa.array([\"foo\", \"bar\"]),\n pa.array([10.0, 20.0]),\n ],\n [\"vector\", \"item\", \"price\"],\n )\n\ndb = tmp_db\ndb.create_table(\"batched_table\", make_batches(), schema=schema, mode=\"overwrite\")\n"; +export const PyCreateTableFromIterator = "db.create_table(\"batched_table\", make_batches(), schema=schema, mode=\"overwrite\")\n"; -export const PyCreateTableFromPandas = "import pandas as pd\n\ndata = pd.DataFrame(\n {\n \"vector\": [[1.1, 1.2, 1.3, 1.4], [0.2, 1.8, 0.4, 3.6]],\n \"lat\": [45.5, 40.1],\n \"long\": [-122.7, -74.1],\n }\n)\ndb = tmp_db\ndb.create_table(\"my_table_pandas\", data, mode=\"overwrite\")\ndb[\"my_table_pandas\"].head()\n"; +export const PyCreateTableFromPandas = "db.create_table(\"my_table_pandas\", data, mode=\"overwrite\")\ndb[\"my_table_pandas\"].head()\n"; -export const PyCreateTableFromPolars = "import polars as pl\n\ndata = pl.DataFrame(\n {\n \"vector\": [[3.1, 4.1], [5.9, 26.5]],\n \"item\": [\"foo\", \"bar\"],\n \"price\": [10.0, 20.0],\n }\n)\ndb = tmp_db\ntbl = db.create_table(\"my_table_pl\", data, mode=\"overwrite\")\n"; +export const PyCreateTableFromPolars = "tbl = db.create_table(\"my_table_pl\", data, mode=\"overwrite\")\n"; -export const PyCreateTableFromPydantic = "from lancedb.pydantic import LanceModel, Vector\n\nclass Content(LanceModel):\n movie_id: int\n vector: Vector(128)\n genres: str\n title: str\n imdb_id: int\n\n @property\n def imdb_url(self) -> str:\n return f\"https://www.imdb.com/title/tt{self.imdb_id}\"\n\ndb = tmp_db\ntbl = db.create_table(\"movielens_small\", schema=Content, mode=\"overwrite\")\n"; +export const PyCreateTableFromPydantic = "tbl = db.create_table(\"movielens_small\", schema=Content, mode=\"overwrite\")\n"; -export const PyCreateTableNestedSchema = "from lancedb.pydantic import LanceModel, Vector\n\n# --8<-- [start:tables_document_model]\nfrom pydantic import BaseModel\n\nclass Document(BaseModel):\n content: str\n source: str\n\n# --8<-- [end:tables_document_model]\n\nclass NestedSchema(LanceModel):\n id: str\n vector: Vector(1536)\n document: Document\n\ndb = tmp_db\ntbl = db.create_table(\"nested_table\", schema=NestedSchema, mode=\"overwrite\")\n"; +export const PyCreateTableNestedSchema = "tbl = db.create_table(\"nested_table\", schema=NestedSchema, mode=\"overwrite\")\n"; export const PyDeleteOperation = "# delete data\npredicate = \"id = 3\"\ntable.delete(predicate)\n"; @@ -76,7 +76,7 @@ export const PyDropColumnsMultiple = "# Remove the second temporary column\ntabl export const PyDropColumnsSingle = "# Remove the first temporary column\ntable.drop_columns([\"temp_col1\"])\n"; -export const PyDropTable = "db = tmp_db\n# Create a table first\ndata = [{\"vector\": [1.1, 1.2], \"lat\": 45.5}]\ndb.create_table(\"my_table\", data, mode=\"overwrite\")\n\n# Drop the table\ndb.drop_table(\"my_table\")\n"; +export const PyDropTable = "# Create a table first\ndata = [{\"vector\": [1.1, 1.2], \"lat\": 45.5}]\ndb.create_table(\"my_table\", data, mode=\"overwrite\")\n\n# Drop the table\ndb.drop_table(\"my_table\")\n"; export const PyInsertIfNotExists = "import pyarrow as pa\n\ntable = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n)\n\nincoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n \"login_count\": [21, 5],\n }\n)\n\n(table.merge_insert(\"id\").when_not_matched_insert_all().execute(incoming_users))\n"; @@ -88,13 +88,13 @@ export const PyMergePartialColumns = "import pyarrow as pa\n\ntable = db.create_ export const PyMergeUpdateInsert = "import pyarrow as pa\n\ntable = db.create_table(\n \"users_example\",\n data=pa.table(\n {\n \"id\": [1, 2],\n \"name\": [\"Alice\", \"Bob\"],\n \"login_count\": [10, 20],\n }\n ),\n mode=\"overwrite\",\n)\n\nincoming_users = pa.table(\n {\n \"id\": [2, 3],\n \"name\": [\"Bobby\", \"Charlie\"],\n \"login_count\": [21, 5],\n }\n)\n\n(\n table.merge_insert(\"id\")\n .when_matched_update_all()\n .when_not_matched_insert_all()\n .execute(incoming_users)\n)\n"; -export const PyOpenExistingTable = "db = tmp_db\n# Create a table first\ndata = [{\"vector\": [1.1, 1.2], \"lat\": 45.5, \"long\": -122.7}]\ndb.create_table(\"test_table\", data, mode=\"overwrite\")\n\n# List table names\nprint(db.list_tables().tables)\n\n# Open existing table\ntbl = db.open_table(\"test_table\")\n"; +export const PyOpenExistingTable = "# Create a table first\ndata = [{\"vector\": [1.1, 1.2], \"lat\": 45.5, \"long\": -122.7}]\ndb.create_table(\"test_table\", data, mode=\"overwrite\")\n\n# List table names\nprint(db.list_tables().tables)\n\n# Open existing table\ntbl = db.open_table(\"test_table\")\n"; export const PySchemaAddSetup = "import numpy as np\n\ndata = [\n {\n \"id\": 1,\n \"name\": \"Laptop\",\n \"price\": 1200.00,\n \"vector\": np.random.random(128).tolist(),\n },\n {\n \"id\": 2,\n \"name\": \"Smartphone\",\n \"price\": 800.00,\n \"vector\": np.random.random(128).tolist(),\n },\n {\n \"id\": 3,\n \"name\": \"Headphones\",\n \"price\": 150.00,\n \"vector\": np.random.random(128).tolist(),\n },\n]\ntable = db.create_table(\"schema_evolution_add_example\", data, mode=\"overwrite\")\n"; -export const PySchemaAlterSetup = "table_name = \"schema_evolution_alter_example\"\nif data is None:\n data = [\n {\n \"id\": 1,\n \"name\": \"Laptop\",\n \"price\": 1200,\n \"discount_price\": 1080.0,\n \"vector\": np.random.random(128).tolist(),\n },\n {\n \"id\": 2,\n \"name\": \"Smartphone\",\n \"price\": 800,\n \"discount_price\": 720.0,\n \"vector\": np.random.random(128).tolist(),\n },\n ]\nschema = pa.schema(\n {\n \"id\": pa.int64(),\n \"name\": pa.string(),\n \"price\": pa.int32(),\n \"discount_price\": pa.float64(),\n \"vector\": pa.list_(pa.float32(), 128),\n }\n)\ntable = tmp_db.create_table(table_name, data, schema=schema, mode=\"overwrite\")\n"; +export const PySchemaAlterSetup = "table_name = \"schema_evolution_alter_example\"\nif data is None:\n data = [\n {\n \"id\": 1,\n \"name\": \"Laptop\",\n \"price\": 1200,\n \"discount_price\": 1080.0,\n \"vector\": np.random.random(128).tolist(),\n },\n {\n \"id\": 2,\n \"name\": \"Smartphone\",\n \"price\": 800,\n \"discount_price\": 720.0,\n \"vector\": np.random.random(128).tolist(),\n },\n ]\nschema = pa.schema(\n {\n \"id\": pa.int64(),\n \"name\": pa.string(),\n \"price\": pa.int32(),\n \"discount_price\": pa.float64(),\n \"vector\": pa.list_(pa.float32(), 128),\n }\n)\ntable = db.create_table(table_name, data, schema=schema, mode=\"overwrite\")\n"; -export const PySchemaDropSetup = "if data is None:\n data = [\n {\n \"id\": 1,\n \"name\": \"Laptop\",\n \"price\": 1200.00,\n \"temp_col1\": \"X\",\n \"temp_col2\": 100,\n \"vector\": np.random.random(128).tolist(),\n },\n {\n \"id\": 2,\n \"name\": \"Smartphone\",\n \"price\": 800.00,\n \"temp_col1\": \"Y\",\n \"temp_col2\": 200,\n \"vector\": np.random.random(128).tolist(),\n },\n {\n \"id\": 3,\n \"name\": \"Headphones\",\n \"price\": 150.00,\n \"temp_col1\": \"Z\",\n \"temp_col2\": 300,\n \"vector\": np.random.random(128).tolist(),\n },\n ]\ntable = tmp_db.create_table(\"schema_evolution_drop_example\", data, mode=\"overwrite\")\n"; +export const PySchemaDropSetup = "if data is None:\n data = [\n {\n \"id\": 1,\n \"name\": \"Laptop\",\n \"price\": 1200.00,\n \"temp_col1\": \"X\",\n \"temp_col2\": 100,\n \"vector\": np.random.random(128).tolist(),\n },\n {\n \"id\": 2,\n \"name\": \"Smartphone\",\n \"price\": 800.00,\n \"temp_col1\": \"Y\",\n \"temp_col2\": 200,\n \"vector\": np.random.random(128).tolist(),\n },\n {\n \"id\": 3,\n \"name\": \"Headphones\",\n \"price\": 150.00,\n \"temp_col1\": \"Z\",\n \"temp_col2\": 300,\n \"vector\": np.random.random(128).tolist(),\n },\n ]\ntable = db.create_table(\"schema_evolution_drop_example\", data, mode=\"overwrite\")\n"; export const PySchemaFieldMetadataMerge = "# Set two metadata keys on the `category` field.\nres = table.update_field_metadata(\n {\"path\": \"category\", \"metadata\": {\"unit\": \"label\", \"pii\": \"false\"}}\n)\nprint(res.version)\n\n# Merge: add a new key, delete one with None, keep the rest.\ntable.update_field_metadata(\n {\"path\": \"category\", \"metadata\": {\"source\": \"import\", \"pii\": None}}\n)\n\n# Arrow stores field metadata as bytes.\nassert table.schema.field(\"category\").metadata == {\n b\"unit\": b\"label\",\n b\"source\": b\"import\",\n}\n"; @@ -122,7 +122,7 @@ export const PyUpdateUsingSql = "import pyarrow as pa\n\ntable = db.create_table export const PyVersioningAddData = "more_data = [\n {\n \"id\": 4,\n \"author\": \"Richard Daniel Sanchez\",\n \"quote\": \"That's the way the news goes!\",\n },\n {\"id\": 5, \"author\": \"Morty\", \"quote\": \"Aww geez, Rick!\"},\n]\ntable.add(more_data)\n"; -export const PyVersioningBasicSetup = "import pyarrow as pa\n\ndb = tmp_db\n\ntable_name = \"quotes_versioning_example\"\ndata = [\n {\"id\": 1, \"author\": \"Richard\", \"quote\": \"Wubba Lubba Dub Dub!\"},\n {\"id\": 2, \"author\": \"Morty\", \"quote\": \"Rick, what's going on?\"},\n {\n \"id\": 3,\n \"author\": \"Richard\",\n \"quote\": \"I turned myself into a pickle, Morty!\",\n },\n]\n\n# Define schema\nschema = pa.schema(\n [\n pa.field(\"id\", pa.int64()),\n pa.field(\"author\", pa.string()),\n pa.field(\"quote\", pa.string()),\n ]\n)\n\ntable = db.create_table(table_name, data, schema=schema, mode=\"overwrite\")\n"; +export const PyVersioningBasicSetup = "\ntable_name = \"quotes_versioning_example\"\ndata = [\n {\"id\": 1, \"author\": \"Richard\", \"quote\": \"Wubba Lubba Dub Dub!\"},\n {\"id\": 2, \"author\": \"Morty\", \"quote\": \"Rick, what's going on?\"},\n {\n \"id\": 3,\n \"author\": \"Richard\",\n \"quote\": \"I turned myself into a pickle, Morty!\",\n },\n]\n\n# Define schema\nschema = pa.schema(\n [\n pa.field(\"id\", pa.int64()),\n pa.field(\"author\", pa.string()),\n pa.field(\"quote\", pa.string()),\n ]\n)\n\ntable = db.create_table(table_name, data, schema=schema, mode=\"overwrite\")\n"; export const PyVersioningCheckInitialVersion = "versions = table.list_versions()\ncurrent_version = table.version\nprint(f\"Number of versions after creation: {len(versions)}\")\nprint(f\"Current version: {current_version}\")\n"; diff --git a/docs/web/sql/data-types.mdx b/docs/web/sql/data-types.mdx index c5f362a6b..ef5dfcab7 100644 --- a/docs/web/sql/data-types.mdx +++ b/docs/web/sql/data-types.mdx @@ -3,7 +3,7 @@ title: "SQL data types" sidebarTitle: "Data Types" description: "How Lance columns appear to SQL, including the types SQL has no name for." icon: shapes -keywords: ["sql types", "arrow", "cast", "pseudo-columns", "vector", "json"] +keywords: ["sql types", "arrow", "cast", "pseudo-columns", "vector"] availability: embedded: unavailable enterprise: available @@ -68,12 +68,14 @@ Some column kinds have no SQL type name. A dense vector column has a fixed dimension, commonly represented as `FixedSizeList`. Other supported vector element types are -possible; inspect the column with [`arrow_typeof`](/sql/scalar-functions#type) rather than assuming Float32. +possible; inspect the column with [`arrow_typeof`](/sql/dql/scalar-functions#type) rather than assuming Float32. It is selectable and testable for nullness: -```sql + +```sql SQL icon="database" SELECT id FROM documents WHERE vector IS NOT NULL ``` + A list representation does not imply that ordinary arithmetic operators @@ -82,18 +84,24 @@ calculations. SQL vector search depends on the Enterprise server version and que plan; see [SQL](/basics/sql#no-vector-sql). +{/* +Draft until JSON columns reach early access. + ### JSON {#json} Stored as JSONB in `large_binary` with the `lance.json` extension name. It reads through accessor functions rather than a `->` operator: -```sql + +```sql SQL icon="database" SELECT json_get_string(data, 'name') FROM events WHERE json_get_int(data, 'status') = 200 ``` + `json_get`, its typed variants, and `json_extract` are **index-accelerated** by a -JSON scalar index. See [Functions](/sql/scalar-functions#json). +JSON scalar index. See [JSON functions](/sql/dql/json-functions). +*/} ### bfloat16 {#bfloat16} @@ -101,6 +109,9 @@ Sixteen-bit floats in the bfloat16 layout, stored as `fixed_size_binary(2)`. Useful as a vector element type when halving the memory matters more than the precision does. +{/* +Draft: geospatial queries and indexes are unsupported in LanceDB Enterprise. + ## Geospatial {#geospatial} @@ -114,6 +125,7 @@ spatial index is gated the same way. Geometry can still be stored (it is binary, and binary columns work), but nothing interprets it. Filter on a bounding box held in ordinary numeric columns if you need spatial predicates today. +*/} ## Pseudo-columns {#pseudo-columns} @@ -127,7 +139,7 @@ its schema, so `_score` is included in `SELECT * FROM fts(...)`. | `_rowid` | `UInt64` | Lance scan row identifier; stability requires stable row ids | | `_rowaddr` | `UInt64` | physical row address | | `_rowoffset` | `UInt64` | offset within the fragment | -| `_score` | `Float32` | relevance, from [`fts()`](/sql/functions#fts) | +| `_score` | `Float32` | relevance, from [`fts()`](/sql/dql/fts) | `_rowid`, `_rowaddr`, and `_rowoffset` describe Lance scan metadata, not columns automatically registered on an ordinary SQL table. Select `_score` @@ -135,10 +147,12 @@ from an `fts()` relation explicitly when you want a projection containing it. ## Casting {#casting} -```sql + +```sql SQL icon="database" SELECT CAST(identifier AS VARCHAR) FROM documents SELECT TRY_CAST(maybe_number AS BIGINT) FROM raw ``` + `TRY_CAST` yields null rather than failing the query on a value that will not -convert. See [Operators](/sql/operators#casting). +convert. See [Operators](/sql/dql/operators#casting). diff --git a/docs/web/sql/ddl/database.mdx b/docs/web/sql/ddl/database.mdx index 6f4ab557f..e8cdb55bc 100644 --- a/docs/web/sql/ddl/database.mdx +++ b/docs/web/sql/ddl/database.mdx @@ -1,9 +1,9 @@ --- title: "Database" sidebarTitle: "Database" -description: "ATTACH DATABASE: bind a database to a storage location." +description: "Create, describe, list, attach, and drop databases with SQL." icon: database -keywords: ["attach database", "database", "sql", "ddl"] +keywords: ["database", "create database", "describe database", "show databases", "drop database", "attach database", "sql"] availability: embedded: unavailable enterprise: available @@ -11,23 +11,96 @@ availability: A database is the catalog's top-level container: it holds [namespaces](/sql/ddl/namespace), which hold tables, views and other objects. -`ATTACH DATABASE` binds a name to a storage location so its objects become -reachable. +Database statements name one database, independently of the session's +current database. Database creation uses the deployment's native catalog +and storage settings. + +## CREATE DATABASE {#create} + + +```sql SQL icon="database" +CREATE DATABASE analytics +CREATE DATABASE IF NOT EXISTS "team/search" +``` + + +Creates a persistent database. Requires `CREATE DATABASE` on the system, and +ownership of the database name if it already has an owner. The caller +becomes the owner of a new name, following the same rules as the REST API. + +The result has `operation`, `name`, and `status` columns. Status is +`created`, or `already_exists` with `IF NOT EXISTS`. Without that clause, an +existing database is an error. Creation never overwrites an existing +database. + + +`WITH` options are unsupported on `CREATE DATABASE`. Use `ATTACH DATABASE` +[below](#attach) to register a database at an existing location. The +`system` database and reserved storage names cannot be created. + + +## DESCRIBE DATABASE {#describe} + + +```sql SQL icon="database" +DESCRIBE DATABASE analytics +DESC DATABASE "team/search" +``` + + +Requires `USAGE` on the database. Returns one row with `name` and +`properties`. Properties are the catalog's metadata encoded as a JSON +object; a database without metadata returns `{}`, and a database mid +`CASCADE` drop reports a transient property marking it as dropping. A +missing database is an error. `DESCRIBE DATABASE system` returns empty +properties and requires system `USAGE`. + +## SHOW DATABASES {#show} + + +```sql SQL icon="database" +SHOW DATABASES +``` + + +Returns a sorted `name` column containing the databases the caller has +`USAGE` on, including `system` when permitted. `LIKE` and `WHERE` filters +are unsupported. ## ATTACH DATABASE {#attach} -```sql + +```sql SQL icon="database" ATTACH DATABASE analytics WITH (location = 'analytics') ATTACH DATABASE IF NOT EXISTS analytics WITH (location = 'analytics') +ATTACH DATABASE analytics WITH (location = 's3://customer-bucket/raw/analytics/') +ATTACH DATABASE analytics WITH (location = 'az://customer-data@customeraccount.blob.core.windows.net/raw/analytics') ``` + -`location` is the only supported option, and the only way to say where a -database lives: a relative subdirectory, never an absolute path or a URI. +Registers an existing database at a path relative to the catalog's storage +root, or at an external S3, GCS or Azure location, instead of creating a +new one. `location` is the only supported option -- naming a storage +integration explicitly is refused. For an external location, the +deployment automatically binds the most specific +[storage integration](/sql/ddl/storage-integration) whose prefix covers +it; one must already exist. An Azure location must be account-qualified +(`az://container@account.blob.core.windows.net/path`); a bare +`az://container/path` is refused. `ATTACH DATABASE` requires the same +creation privileges as `CREATE DATABASE`. For an external location, it also +requires `USAGE` on the storage integration that binds it, and on that +integration's own database and namespace; the integration itself must live +in a native, root-backed database under the catalog root. + +Attaching writes Enterprise's own tracking metadata into the location to +bring it under management -- it does not rewrite, move, or re-encode any +existing table's data. -An absolute path (`/tmp/db`), an `s3://` or `file://` URI, a Windows path -(`C:/db`), a `..` segment, an empty string and a doubled slash (`sub//db`) -are all refused. +A relative-path location never accepts an absolute path (`/tmp/db`), a +`file://` URI, a Windows path (`C:/db`), a `..` segment, an empty string, +or a doubled slash (`sub//db`). An S3 or GCS location must be a concrete +prefix, not a bare scheme (`s3://`) on its own. `IF NOT EXISTS` makes the statement a no-op rather than an error when the @@ -36,6 +109,36 @@ database is already attached. A quoted name reaches characters a bare identifier cannot, such as `` ATTACH DATABASE "team/search" WITH (location = 'team-search') ``. +Removing an externally attached database with `DROP DATABASE` unregisters +the attachment and releases its storage-integration reference, without +deleting the underlying data. + + +## DROP DATABASE {#drop} + + +```sql SQL icon="database" +DROP DATABASE analytics +DROP DATABASE IF EXISTS analytics RESTRICT +DROP DATABASE analytics CASCADE +``` + + +Requires `USAGE` and `OWNERSHIP` on the database. The default, `RESTRICT`, +refuses a database that still contains objects. `CASCADE` refuses new +objects in the database, revokes every grant in it, and starts a job that +drops its contents; deployments without cascade support reject it. An +externally attached database cannot be dropped with `CASCADE`. + +`RESTRICT` returns `operation`, `name`, and `status` columns: `dropped`, or +`not_found` with `IF EXISTS` for a missing database. `CASCADE` returns +`operation`, `job_id`, and `status` columns: the job's id with `dropping`, +or an empty `job_id` with `not_found`. The name stays taken until the job +finishes and the dropped storage is cleaned up. The `system` database and +federated databases cannot be dropped. + + +`ALTER DATABASE` is unsupported. ## What to read next {#next} @@ -47,4 +150,7 @@ A quoted name reaches characters a bare identifier cannot, such as Creating tables once a database and namespace exist. + + The SDK equivalent, and connection settings. + diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 1593c2d7b..8cd45f8bc 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -1,30 +1,40 @@ --- title: "Function" +tag: "Early access" sidebarTitle: "Function" -description: "CREATE FUNCTION, SHOW FUNCTIONS, and DROP FUNCTION." +description: "Create, describe, alter, list, and drop registered functions with SQL." icon: function keywords: ["create function", "drop function", "show functions", "sql", "udf"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) +Early access + +[SQL runs in LanceDB Enterprise.](/sql) ## CREATE FUNCTION {#create} -```sql + +```sql SQL icon="database" CREATE FUNCTION f(x int64) RETURNS int64 LANGUAGE python AS 'def f(x): return x * 2' WITH (pip = 'numpy==1.26.4', python_version = '3.11') ``` + A function takes more than one parameter; each one binds a separate column or literal where the function is called: -```sql + +```sql SQL icon="database" CREATE FUNCTION ratio(numerator float64, denominator float64) RETURNS float64 LANGUAGE python AS 'def ratio(numerator, denominator): return numerator / denominator' ``` + Parameter and result types are Arrow type names, not SQL ones: `int64`, `float64`, `utf8`, `bool`, `date32`, and lists such as `list` or @@ -41,8 +51,14 @@ version is unaffected. | `pip` | pip requirements for the worker environment | | `conda` | conda packages instead of pip | | `conda_channels` | channels in priority order; requires `conda` | +| `apt` | OS packages to install in the worker environment | +| `image` | a specific container image to run the worker in, such as `'host/repo@sha256:...'` | | `python_version` | worker Python version; `3.12` when omitted, whatever Python you send the statement from | | `gpu` | `'true'` when every execution needs a GPU | +| `gpu_class` | which configured GPU class to run on, when `gpu = 'true'` | +| `result_stability` | `'input_and_context'` or `'per_call'` | +| `batch_size` | maximum rows per Function call | +| `row_timeout_seconds` | per-row (or per-batch, for a vectorized Function) execution timeout | **Errors and limits** @@ -60,14 +76,45 @@ version is unaffected. the function is baked into an image before the version becomes usable. +## Artifact registration {#artifact} + +`CREATE FUNCTION name FROM ''` accepts the artifact, +signature, runtime, optional secret bindings, and result stability produced by +the SDK's registration request. Omit its `name` property because the SQL +identifier supplies it. Escape apostrophes in the JSON as doubled apostrophes. + +By default, the command waits for its internal image-build job to publish the +version, then returns one UTF-8 `definition` column containing FunctionVersion +JSON. `WITH (wait = false)` instead returns the existing image-build registry +job ID in `job_id`, with `operation` and `status` columns. The SDK's ordinary +registration handle has type `query` and uses the SQL query UUID as its single +`id`; the internal image-build job has type `create_function`. + +## DESCRIBE and ALTER FUNCTION {#describe-alter} + +```sql +DESCRIBE FUNCTION embed WITH (version = '1', include_source = true) +``` + +DESCRIBE returns one `definition` JSON column for the exact version. +`include_source` defaults to false; source-inclusive reads report an omission +when the stored artifact exceeds the inline source limit. + +`ALTER FUNCTION name FROM ''` accepts a `reference` with +name, namespace, object ID, location, version, and manifest digest, plus optional +`metadata` and `disabled` updates. The command checks that reference before +appending a revision and returns the resulting `definition` JSON. + ## Call it {#call} Once registered, a function is callable by name in any query, the same as a built-in scalar function: -```sql + +```sql SQL icon="database" SELECT id, f(x) AS doubled FROM my_table ``` + This is also the fastest way to check a new registration before binding it to a column: call it over a few rows, or over literal arguments, before @@ -76,31 +123,39 @@ from it. ## SHOW FUNCTIONS {#show} -```sql + +```sql SQL icon="database" SHOW FUNCTIONS +SHOW FUNCTIONS HISTORY IN "analytics" WITH (name = 'embed', limit = 100) +SHOW FUNCTIONS HISTORY WITH (after_name = 'embed', after_version = '1', limit = 100) ``` + -Lists registered functions and their versions. Since a version is immutable -and a column pins the version that fills it, this is how you find which -versions are still in use before dropping one. +`SHOW FUNCTIONS` returns the highest published numeric revision for each name. +Add `HISTORY` to list every published revision, as Python's `list_functions()` +does. Rows are ordered by name and numeric revision, so `2` comes before `10`. +`after_name` and `after_version` must be supplied together for keyset pagination. +`limit` bounds +the response; `include_definition = false` omits the optional definition JSON. ## DROP FUNCTION {#drop} -```sql + +```sql SQL icon="database" DROP FUNCTION embed WITH (version = '1') DROP FUNCTION IF EXISTS embed WITH (version = '1') -DROP FUNCTION embed WITH (version = '1', cascade = 'true') ``` + -`version` is required: a function is a set of immutable versions, and -dropping is always of one specific version, never "the function" as a whole. +DROP removes only the requested revision from lookup and listing. Other +published revisions and their grants remain available. Dropping the last visible +revision releases the name and object binding; physical cleanup continues +separately. The result reports `dropped` or `not_found`. `IF EXISTS` allows a +missing name or a repeated drop of a previously published revision. A revision +that was never published under an existing name is an error. - -Without `cascade = 'true'`, dropping a version that a column still pins fails -rather than breaking that column silently. Passing it drops the version and -lets columns pinned to it stop refreshing. They keep their last-filled -values, per [Guarantees](/basics/guarantees#jobs). - +All function object commands retain shared results even when general query-result +copying is disabled, so asynchronous polling can resume on another query node. ## What to read next {#next} diff --git a/docs/web/sql/ddl/grant.mdx b/docs/web/sql/ddl/grant.mdx index 85da7832a..370529209 100644 --- a/docs/web/sql/ddl/grant.mdx +++ b/docs/web/sql/ddl/grant.mdx @@ -1,34 +1,51 @@ --- title: "Grant" sidebarTitle: "Grant" -description: "GRANT and REVOKE: privileges on Secrets and Functions." +description: "GRANT and REVOKE: privileges on every catalog object, from a database down to a Function." icon: user-lock keywords: ["grant", "revoke", "privileges", "authorization", "sql", "ownership"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) + +```sql SQL icon="database" +GRANT [, ...] ON TO [, ...] +REVOKE [, ...] ON FROM [, ...] -```sql -GRANT [, ...] ON { SECRET | FUNCTION } TO [, ...] -GRANT [, ...] ON SCHEMA TO [, ...] -REVOKE [, ...] ON ... FROM [, ...] + ::= SYSTEM | DATABASE | SCHEMA | NAMESPACE [IN ] | TABLE | VIEW + | MATERIALIZED VIEW | SECRET | STORAGE INTEGRATION | FUNCTION + ::= [ROLE] | [USER] { | ID '' } | [GROUP] { | ID '' } ``` + -```sql -GRANT USAGE, UPDATE ON SECRET api_key TO ROLE readers, writers -GRANT CREATE FUNCTION ON SCHEMA analytics TO ROLE data_science -REVOKE USAGE ON FUNCTION embed FROM ROLE readers + +```sql SQL icon="database" +GRANT OPERATE, USAGE ON SYSTEM TO ROLE ops +GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE readers +GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl +GRANT CREATE SECRET, CREATE FUNCTION ON SCHEMA platform TO ROLE platform_admins +GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service +GRANT USAGE ON SECRET platform.`model-api-key` TO USER alice, GROUP ID 'g1' +GRANT USAGE ON FUNCTION platform.embed TO ROLE research +GRANT OWNERSHIP ON SECRET platform.`model-api-key` TO ROLE platform_admins +REVOKE USAGE ON FUNCTION platform.embed FROM ROLE research ``` + ## Privileges {#privileges} -| Privilege | Allows | +| Target | Privileges it accepts | | --- | --- | -| `OWNERSHIP` | everything on the object | -| `USAGE` | using it: binding a Secret's value, calling a Function | -| `UPDATE` | changing it | -| `CREATE SECRET` | creating a Secret inside a `SCHEMA` | -| `CREATE FUNCTION` | creating a Function inside a `SCHEMA` | +| `SYSTEM` | `OPERATE`, `CREATE DATABASE`, `USAGE` -- no `OWNERSHIP`; the system itself has no owner | +| `DATABASE` | `OWNERSHIP`, `USAGE`, `CREATE SCHEMA` (or `CREATE NAMESPACE`) | +| `SCHEMA` (a namespace) | `OWNERSHIP`, `USAGE`, `CREATE NAMESPACE`, `CREATE TABLE`, `CREATE MATERIALIZED VIEW`, `CREATE VIEW`, `CREATE SECRET`, `CREATE STORAGE INTEGRATION`, `CREATE FUNCTION` | +| `TABLE`, `MATERIALIZED VIEW` | `OWNERSHIP`, `SELECT`, `INSERT`, `UPDATE`, `DELETE` | +| `VIEW` | `OWNERSHIP`, `SELECT` | +| `SECRET` | `OWNERSHIP`, `USAGE` (bind it to a Function), `UPDATE` (rotate it) | +| `STORAGE INTEGRATION` | `OWNERSHIP`, `USAGE` | +| `FUNCTION` | `OWNERSHIP`, `USAGE` (call it in a query, bind it to a column, or refresh a column it computes) | `OWNERSHIP` cannot be revoked, only granted to someone else, which transfers @@ -36,39 +53,86 @@ it: an object always has exactly one owner. `GRANT OWNERSHIP` is refused with more than one grantee for the same reason. -These are a subset of the full privilege model; see -[Authorization](/governance/authorization#privileges) for privileges on -tables, views and namespaces, which this statement does not grant. +See [Privileges](/governance/privileges) for what each privilege allows in +full, and how a creation privilege resolves against an object's parent when +the object doesn't exist yet. ## Grantees {#grantees} -```sql - ::= [ ROLE ] | [ { USER | GROUP } ] { | ID '' } -``` - -```sql -GRANT USAGE ON SECRET api_key TO ROLE readers, USER alice, GROUP ID 'g1' -``` - A grantee is a role, or a user or group named by its identity-directory name or its directory ID. A grantee with no leading `ROLE`/`USER`/`GROUP` keyword takes the kind of the one before it, so `TO ROLE a, b` names two roles -- but the first grantee in the list always needs its keyword. An unquoted name -is folded to lowercase before it is looked up; a quoted name is looked up -exactly as written. +is folded to lowercase before it is looked up; quote one that has capitals, +such as `TO ROLE "DataEng"`. ## Naming the target {#targets} A `SECRET` or `FUNCTION` target can be qualified with its namespace and database, the same as anywhere else: `SECRET analytics.api_key`, -`SECRET db1.analytics.api_key`. A `SCHEMA` target is the namespace itself. -There is no `TABLE` target: table privileges are granted through -[Authorization](/governance/authorization), not this statement. +`SECRET db1.analytics.api_key`. `SCHEMA` and `NAMESPACE` both target a +namespace but aren't interchangeable: `SCHEMA ` takes the +namespace's complete path, while `NAMESPACE [IN ]` takes +one unqualified component, resolved under an explicit parent schema or the +session's current namespace when `IN` is omitted -- `NAMESPACE a.b` (a +qualified name with no `IN`) is refused. A `MATERIALIZED VIEW` is a table +for authorization purposes: the same privileges apply, and granting one +does not reach the non-materialized `VIEW` beside it. + +## How a statement is applied {#semantics} + +- A statement applies all of its changes or none of them. +- The caller must already hold `OWNERSHIP` on the object to change any grant + on it. +- Granting a privilege a grantee already holds, or revoking one it does not + hold, is a no-op. +- `GRANT` requires the object to exist; `REVOKE` does not, so an entry left + on a dropped object can still be removed. A role need not exist + beforehand, but a `USER` or `GROUP` name must resolve to exactly one + identity in your identity provider -- checked only after the caller's + `OWNERSHIP` -- or the statement fails. The `ID ''` form is not looked + up. +- `GRANT ... ON ... FROM ...` and `REVOKE ... ON ... TO ...` are both + refused; `GRANT` always takes `TO`, `REVOKE` always takes `FROM`. +- Returns one row per privilege and grantee, with status `granted`, + `already_granted`, `revoked` or `not_granted`. + + +SQL has no syntax for binding a Secret to a Function; that's a +registration-time argument to `create_function` in the Python SDK. See +[Vend a Secret to a Function](/curation/vend-secret). + + +## SHOW GRANTS {#show-grants} + + +```sql SQL icon="database" +SHOW GRANTS [ON ] [TO [, ...]] [LIMIT n] +``` + + + +```sql SQL icon="database" +SHOW GRANTS +SHOW GRANTS ON TABLE events TO ROLE readers LIMIT 2 +SHOW GRANTS ON NAMESPACE features IN analytics.team +SHOW GRANTS TO USER ID 'p1' +``` + + +Lists grants as rows of `subject_id`, `subject_name`, `object` and +`privilege`. `ON` filters to one target's own grants; `TO` filters to one +or more grantees; combine both, or omit both for every grant the caller +can see. `ON ` requires `USAGE` on that target; a target-less call +requires system `USAGE` instead, since it can surface grants across the +whole catalog. `SHOW ROLE BINDINGS` is the counterpart for role +membership rather than object privileges -- see +[Role membership in SQL](/governance/principals#membership). ## What to read next {#next} - + The full privilege model, and how creation privileges resolve upward. diff --git a/docs/web/sql/ddl/index.mdx b/docs/web/sql/ddl/index.mdx index dd900ee52..425af7376 100644 --- a/docs/web/sql/ddl/index.mdx +++ b/docs/web/sql/ddl/index.mdx @@ -11,10 +11,12 @@ availability: ## CREATE INDEX {#create} -```sql + +```sql SQL icon="database" CREATE INDEX ON documents USING btree (title) CREATE INDEX text_search ON documents USING fts (text) ``` + `USING` is required: it names the algorithm. The scalar algorithms are `btree`, `bitmap` and `label_list`; `fts` builds a full-text index; and the vector @@ -33,14 +35,16 @@ multi-column index, use the SDK's [`create_index`](/indexing). `reindex_btree` or `reindex_ivf_pq`; the name says which algorithm is building, not a different feature. An SDK build that must not replace an existing index runs as `create_` followed by the algorithm instead. See -[Build & Repair](/indexing/reindexing). +[Incremental Indexing](/indexing/incremental-indexing). ## DROP INDEX {#drop} -```sql + +```sql SQL icon="database" DROP INDEX documents.title_idx ``` + Takes the qualified `table.index` name. Find it with the SDK's [`list_indices`](/indexing) if you created the index without @@ -54,7 +58,7 @@ naming it yourself. A deployment builds the index in the background after Choosing an index type from the SDK. - + Keeping an index current as data arrives. diff --git a/docs/web/sql/ddl/job.mdx b/docs/web/sql/ddl/job.mdx index 1b66e1e29..a4cf13490 100644 --- a/docs/web/sql/ddl/job.mdx +++ b/docs/web/sql/ddl/job.mdx @@ -1,46 +1,99 @@ --- title: "Job" sidebarTitle: "Job" -description: "SHOW JOBS, SHOW ERRORS, and controlling a running job with PAUSE, RESUME and CANCEL." +description: "SHOW JOBS, SHOW JOB EVENTS, DESCRIBE JOB, SHOW ERRORS, and controlling a running job with PAUSE, RESUME and CANCEL." icon: hourglass-half -keywords: ["show jobs", "show errors", "pause job", "resume job", "cancel job", "sql"] +keywords: ["show jobs", "show job events", "describe job", "show errors", "pause job", "resume job", "cancel job", "sql"] availability: embedded: unavailable enterprise: available --- A [job](/basics/jobs) is not a catalog object (it has no schema and is not -namespaced), but it has its own SQL statements, grouped here the same way the -catalog objects are. +namespaced), but it has its own SQL statements, grouped here the same way +the catalog objects are. ## SHOW JOBS {#show} -```sql + +```sql SQL icon="database" SHOW JOBS +SHOW JOBS FOR TABLE documents +SHOW JOBS FOR JOB '' [LIMIT n] ``` + -Every job the server knows about: id, type, state, creation time. The SQL -counterpart of `list_jobs`. +The unfiltered command lists jobs in the connected database, newest first: +id, type, state, creation time -- the SQL counterpart of `list_jobs`. `FOR +TABLE` filters that listing by the current namespace's table name. `FOR JOB` +lists the parent's direct child jobs using the REST API's child model. +Child rows expose their ID, kind, phase, row progress and attempt; unknown +values remain NULL. Children are read-only diagnostic identities. + +`FOR JOB` defaults to 1,000 children and accepts `LIMIT` from 1 to 10,000, +following backend continuation pages up to that limit. Child history can be +`available`, `not_yet_recorded`, or `unavailable` after archival. + + +A job you completed weeks ago eventually stops appearing here -- it was +archived, not deleted. Two deployment-scheduled jobs sweep the registry on a +per-database schedule: `job_registry_archive` moves terminal jobs out of the +active registry into archival storage, and `job_events_export` separately +copies terminal jobs' event histories into a curated system table for +metering, where the deployment enables it. A job's events can survive in +that exported table after the job itself is archived. + + +## SHOW JOB EVENTS {#events} + + +```sql SQL icon="database" +SHOW JOB EVENTS '' [LIMIT n] +``` + + +Events are returned newest first. Parent history does not include child +history. The default limit is 1,000; valid limits range from 1 to 10,000. +The result includes event sequence, state, timestamps, origin, claim and +resource/work fields. Child `kind` and `details` expose the REST API's +allowlisted diagnostics; raw parent payloads are excluded. + +## DESCRIBE JOB {#describe} + + +```sql SQL icon="database" +DESCRIBE JOB '' [FORMAT TEXT | TABLE | JSON] +DESC JOB '' [FORMAT TEXT | TABLE | JSON] +``` + + +Both spellings show a finished root job's timing profile. `TEXT` is the +default; `TABLE` returns typed phase/step rows and `JSON` returns the +profile as one document. A running job has no profile rows. ## SHOW ERRORS {#errors} -```sql + +```sql SQL icon="database" SHOW ERRORS ON [FOR JOB ''] [LIMIT ] ``` + -```sql + +```sql SQL icon="database" SHOW ERRORS ON documents SHOW ERRORS ON documents FOR JOB 'job-abc' LIMIT 100 ``` + Why rows failed. Reach for this when a [refresh](/sql/dml/refresh-column) reports fewer filled rows than you expected. -**Errors and limits** +### Errors and limits {#errors-and-limits} | | | | --- | --- | -| `LIMIT` | must be between 1 and 100,000 | +| `LIMIT` | defaults to 10,000; must be between 1 and 100,000 | | Failed jobs scanned without `FOR JOB` | 32 most recent | | Tables the server does not open directly | not supported | @@ -48,27 +101,47 @@ Without `FOR JOB` this surveys recent failures and stops at 32 jobs. When the listing stops at your `LIMIT`, the message says so. Narrow with `FOR JOB` rather than raising the limit blindly. + +`SHOW JOBS`, `SHOW JOB EVENTS`, `DESCRIBE JOB` and `SHOW ERRORS` require +system `USAGE`, as do the equivalent REST diagnostics. Explicit table +listings additionally use the table-list authorization policy. + + ## PAUSE JOB {#pause} -```sql + +```sql SQL icon="database" PAUSE JOB 'j-ci-abc-def' ``` + ## RESUME JOB {#resume} -```sql + +```sql SQL icon="database" RESUME JOB 'j-ci-abc-def' ``` + ## CANCEL JOB {#cancel} -```sql + +```sql SQL icon="database" CANCEL JOB 'j-ci-abc-def' ``` + The job id is always a quoted string literal. All three take exactly one and nothing after it: a second token on the line is a syntax error rather than -being ignored. +being ignored. Pause requires the deployment's pause-write opt-in and a +resumable job type; it may return `pausing` while workers drain, and resume +may return `still_pausing` until drain finishes. + + +`PAUSE JOB`, `RESUME JOB` and `CANCEL JOB` require system `OPERATE` -- a +broader privilege than the `USAGE` that reading job state needs, since +these change what a running job does. + Cancellation is a request, matching the SDK's @@ -79,13 +152,23 @@ configured, which is a deployment condition rather than something you can work around from SQL. +## Compatibility {#compatibility} + +`SHOW JOBS FOR
` (without the `TABLE` keyword), `SHOW JOB SUMMARY`, +and `SHOW JOB SPLITS` retain their existing behavior as compatibility forms. +Prefer `SHOW JOBS FOR TABLE`/`FOR JOB` and `DESCRIBE JOB` going forward. See +[`SHOW JOBS FOR JOB`](#show) for the per-split diagnostics +form -- each split is a child job, listed with its own phase and progress. +See [Watching a refresh](/sql/dml/refresh#watching) for `SHOW JOB SPLITS`'s +full column reference and a `DESCRIBE JOB` example. + ## What to read next {#next} The handle these statements are the SQL view of. - - Job types you did not start yourself. + + A job type the deployment schedules on its own, without a call. diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index 25fcab76e..2f9173ecd 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -21,9 +21,11 @@ its LanceDB Enterprise version and configuration. ## CREATE MATERIALIZED VIEW {#create} -```sql + +```sql SQL icon="database" CREATE MATERIALIZED VIEW AS SELECT ... ``` + Once created, a materialized view can be queried like a table. Use the statements below to list, refresh and drop it. For SDK methods, see @@ -34,15 +36,19 @@ Draft for automatic materialized-view refresh. Enable this section, and "ALTER MATERIALIZED VIEW" below, when the server feature is released. Set scheduling options at creation, continuing the join and chained -Functions from [Functions](/management/function#chain): +Functions from [Create a Function](/curation/create-function#chain): ```sql -CREATE MATERIALIZED VIEW frames_captioned AS -SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, - caption(extract_frame(v.video, f.ts)) AS caption -FROM videos v JOIN frames f ON v.id = f.video_id -WHERE f.selected = true +CREATE MATERIALIZED VIEW frames_captioned WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 5) +AS +SELECT + f.frame_id, + extract_frame(v.video, f.ts) AS jpeg, + caption(extract_frame(v.video, f.ts)) AS caption +FROM videos v +JOIN frames f ON v.id = f.video_id +WHERE f.selected = true ``` `auto_refresh_enabled` and `auto_refresh_interval_seconds` work the same way @@ -54,9 +60,11 @@ automatic execution needs the same server-side switch enabled. Omitting ## SHOW MATERIALIZED VIEWS {#show} -```sql + +```sql SQL icon="database" SHOW MATERIALIZED VIEWS ``` + This asks the server for its views, as the SDK's `list_materialized_views` does @@ -65,9 +73,11 @@ on a `db://` connection. ## Refreshing one {#refresh} -```sql + +```sql SQL icon="database" REFRESH MATERIALIZED VIEW chunks ``` + See [REFRESH MATERIALIZED VIEW](/sql/dml/refresh-materialized-view) for the full syntax, and compatibility notes for older server versions. @@ -102,13 +112,18 @@ that are gated by the setting. ## Dropping one {#drop} -A materialized view **is** a table, so it is dropped with -[`DROP TABLE`](/sql/ddl/table#drop). For the same reason, dropping one removes -stored rows, unlike dropping a [view](/sql/ddl/view#drop). +```sql +DROP MATERIALIZED VIEW +``` + +A dedicated statement; the SDKs emit it rather than +[`DROP TABLE`](/sql/ddl/table#drop), even though a materialized view **is** +a table underneath. For the same reason, dropping one removes stored rows, +unlike dropping a [view](/sql/ddl/view#drop). **Enterprise job type for a refresh:** `sql`. Dropping, by contrast, runs the -same job as dropping any table, `drop_table` or `drop_object`. +same underlying job as dropping any table, `drop_table` or `drop_object`. ## What to read next {#next} diff --git a/docs/web/sql/ddl/namespace.mdx b/docs/web/sql/ddl/namespace.mdx index dd50031ac..8f446f1e7 100644 --- a/docs/web/sql/ddl/namespace.mdx +++ b/docs/web/sql/ddl/namespace.mdx @@ -1,48 +1,193 @@ --- title: "Namespace" sidebarTitle: "Namespace" -description: "CREATE SCHEMA and DROP SCHEMA: the SQL spelling of namespace DDL." +description: "Create, alter, describe, list, and drop namespace paths with SQL." icon: folder-tree -keywords: ["namespace", "schema", "create schema", "drop schema", "sql"] +keywords: ["namespace", "schema", "create schema", "create namespace", "describe schema", "show namespaces", "drop schema", "sql"] availability: embedded: unavailable enterprise: available --- A [namespace](/management/namespace) is addressed in SQL as a `SCHEMA`, the -standard's name for the same concept. +standard's name for the same concept. A **schema** is a complete namespace +path, optionally qualified by a database; a nested path occupies one +backtick-quoted identifier with `$` between components, such as +`` analytics.`team$features` ``. A **namespace**, as a separate keyword, names +one path component, relative to an explicit parent schema or the session's +current schema -- it cannot contain `$` or be qualified with a database. -## CREATE SCHEMA {#create} +`SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete +schema identifier. Names are lowercased unless quoted. -```sql +## CREATE SCHEMA and CREATE NAMESPACE {#create} + +Create a namespace using its complete schema path: + + +```sql SQL icon="database" CREATE SCHEMA analytics CREATE SCHEMA db1.`ns1$ns2` CREATE SCHEMA IF NOT EXISTS `ns1$ns2` ``` + + +Alternatively, create the same namespace by naming its component and parent: + + +```sql SQL icon="database" +CREATE NAMESPACE features IN team +``` + + +To supply creation metadata and tolerate an existing namespace: + + +```sql SQL icon="database" +CREATE NAMESPACE IF NOT EXISTS features IN analytics.team + WITH (owner = 'search-team', purpose = 'retrieval') +``` + A nested namespace is one backtick-quoted name with `$` between its -components: `` db1.`ns1$ns2` `` creates `ns2` inside `ns1` in database `db1`, -provided `ns1` already exists. The part before the dot is the database, so a -three-part path such as `db1.ns1.ns2` is rejected. `public` is the database's -root namespace, which is never created or dropped. +components: `` db1.`ns1$ns2` `` creates `ns2` inside `ns1` in database `db1`. +Both forms create namespaces in the same catalog, and missing ancestors are +created automatically -- the part before the first dot is always the +database. `public` is the database's root namespace, which is never created +or dropped. `IF NOT EXISTS` makes the statement a no-op rather than an error when the -namespace is already there. +namespace is already there, though it does not replace an existing +namespace's properties. Without it, an existing target is an error. +Properties are string values stored on the target only; implicitly created +ancestors receive no properties, and duplicate property keys are errors. -## DROP SCHEMA {#drop} +The result has `operation`, `name`, and `status` columns. The operation is +`CREATE SCHEMA` for either spelling; the name is the resolved path and the +status is `created`. -```sql -DROP SCHEMA db1.analytics -DROP SCHEMA IF EXISTS `a$b` -DROP SCHEMA `a$b` RESTRICT + +Creation requires `CREATE NAMESPACE` on the database and the parent +namespace -- the same privileges the +[namespace REST API](/management/namespace) checks. The caller becomes the +owner of each newly created namespace, including implicitly created +ancestors. See [Grant](/sql/ddl/grant#privileges) for the full privilege +list a namespace accepts. + + +## ALTER SCHEMA and ALTER NAMESPACE {#alter} + +| Operation | SCHEMA syntax | NAMESPACE syntax | +| --- | --- | --- | +| Set metadata | `` ALTER SCHEMA `team$features` SET (purpose = 'retrieval') `` | `ALTER NAMESPACE features IN team SET (purpose = 'retrieval')` | +| Remove metadata | `` ALTER SCHEMA `team$features` UNSET (purpose) `` | `ALTER NAMESPACE features IN team UNSET (purpose)` | + +`SET` adds or replaces the listed string properties, preserving other keys. +`UNSET` removes the listed keys; a missing key is ignored. Lists must be +nonempty, and duplicate keys are errors. Quote a key containing punctuation, +for example `SET ("owner.team" = 'search')`. + +Each statement updates metadata atomically and preserves unrelated +concurrent changes. Metadata changes do not change ownership or grants. Use +`DESCRIBE` to read the updated properties. A missing namespace is an error. + + +Requires `USAGE` on the database and the namespace, and `OWNERSHIP` on the +namespace itself. + + + +`ALTER` metadata is supported by native manifest-backed databases. Legacy +directory and external catalogs report an unsupported-operation error. The +implicit `public` root and the read-only `system` database cannot be +altered. + + +The result has `operation`, `name`, and `status` columns, with operation +`ALTER SCHEMA` for either spelling and status `altered`. + +## DESCRIBE SCHEMA and DESCRIBE NAMESPACE {#describe} + + +```sql SQL icon="database" +DESCRIBE SCHEMA analytics.`team$features` +DESCRIBE NAMESPACE features IN analytics.team +DESC NAMESPACE features IN team ``` + - -`CASCADE` is rejected: **"DROP SCHEMA CASCADE is not supported; drop the -objects inside first."** A namespace's tables, views and other objects must be -dropped explicitly before the namespace itself can go. `RESTRICT` (the -default) states that requirement rather than changing it. - +Returns one row with `name` (the complete `$`-joined schema path) and +`properties` (a JSON object). An unannotated namespace returns `{}`. A +missing namespace is an error. `DESC` is an alias for `DESCRIBE`. + + +Requires `USAGE` on the database and the namespace. + + +## SHOW SCHEMAS and SHOW NAMESPACES {#show} + + +```sql SQL icon="database" +SHOW SCHEMAS +SHOW NAMESPACES +SHOW NAMESPACES IN analytics.team +``` + + +`SHOW SCHEMAS` returns complete paths in the current database, recursively, +including `public` when the caller can use it. It does not accept `IN`. + +`SHOW NAMESPACES` lists only immediate child names under the session's +current schema. `IN` selects a different parent schema, optionally in +another database -- use `IN public` for the current database's root, or +`IN analytics.public` for another database's root. A missing parent is an +error. + +Both forms return a sorted `name` column and omit namespaces the caller +cannot use. Large listings that exceed 10,000 namespaces, or recursive +listings deeper than 32 levels, return an error suggesting a narrower +listing. + +## DROP SCHEMA and DROP NAMESPACE {#drop} + + +```sql SQL icon="database" +DROP SCHEMA analytics.`team$features` +DROP NAMESPACE IF EXISTS features IN analytics.team RESTRICT +DROP NAMESPACE team CASCADE +``` + + +The default, `RESTRICT`, refuses a namespace with children or objects -- +tables, views and other objects inside must be dropped explicitly first. In +native manifest-backed databases, `CASCADE` instead removes the namespace +and all descendant bindings atomically in one catalog commit, then submits +a background job that cleans up their storage; deployments without cascade +support reject it. A storage integration used by an attached database +blocks the drop of its namespace. + + +Requires `USAGE` and `OWNERSHIP` on the namespace. A dropped Secret is +eligible for immediate deletion even when jobs still reference it: a +process that already holds the value keeps it for the rest of its run, but +a later launch that needs the Secret can fail once it's gone. + + +`RESTRICT` returns `operation`, `name`, and `status`, with status `dropped` +or `not_found`. `CASCADE` returns `operation`, `job_id`, and `status`, with +status `dropping`, or an empty job ID and `not_found` for a missing target +with `IF EXISTS`. Inspect a cascade drop's child jobs with +[`SHOW JOBS FOR JOB`](/sql/ddl/job#show). Both spellings report operation +`DROP SCHEMA`. + +## Correcting invalid syntax {#errors} + +| Invalid form | Use instead | +| --- | --- | +| `CREATE SCHEMA child IN parent` | `CREATE NAMESPACE child IN parent` or `` CREATE SCHEMA `parent$child` `` | +| `` DESCRIBE NAMESPACE `parent$child` `` | `` DESCRIBE SCHEMA `parent$child` `` or `DESCRIBE NAMESPACE child IN parent` | +| `DROP NAMESPACE analytics.child` | `DROP NAMESPACE child IN analytics.public` | +| `SHOW SCHEMAS IN parent` | `SHOW NAMESPACES IN parent` | ## What to read next {#next} diff --git a/docs/web/sql/ddl/secret.mdx b/docs/web/sql/ddl/secret.mdx new file mode 100644 index 000000000..922dec247 --- /dev/null +++ b/docs/web/sql/ddl/secret.mdx @@ -0,0 +1,175 @@ +--- +title: "Secret" +tag: "Early access" +sidebarTitle: "Secret" +description: "CREATE, ALTER, DROP, SHOW and DESCRIBE SECRET, and granting privileges on Secrets." +icon: key +keywords: ["secret", "create secret", "alter secret", "drop secret", "show secrets", "describe secret", "grant", "sql"] +--- + +Early access Enterprise [SQL runs in LanceDB Enterprise.](/sql) + +A [Secret](/management/secret) is a named credential that Functions bind by +reference. These statements store, rotate, list, describe and drop Secrets. + +A Secret is addressed like a table: `[db.][namespace.]name`. An unqualified +name uses the session's database and namespace. A nested namespace is one +backtick-quoted name with `$` between its components, and `public` is the +database's root namespace. A Secret name may contain letters, digits, `_`, `.` +and `-`, so quote one that contains `.` or `-`: + + +```sql SQL icon="database" +api_key +platform.`model-api-key` +analytics.`ml$vision`.`model-api-key` +``` + + +`CREATE`, `ALTER` and `DROP` return one row of `operation`, `name` and +`status`. Without `IF [NOT] EXISTS`, a taken name (for `CREATE`) or a missing +Secret (for `ALTER` and `DROP`) is an error rather than a status. + +## CREATE SECRET {#create} + + +```sql SQL icon="database" +CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = '' +CREATE SECRET IF NOT EXISTS api_key TYPE = GENERIC_STRING SECRET_STRING = $$$$ +``` + + +Stores a new Secret. `TYPE = GENERIC_STRING` is required; it is currently the +only supported type. The value may be single-quoted or dollar-quoted, or a +bound `$1` parameter -- the same choice `ALTER SECRET` offers below -- so the +value never has to appear in the SQL text itself: + + +```python Python icon="python" +db.execute_query( + "CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = $1", + parameters=[""], +) +``` + + +Requires `CREATE SECRET` on the namespace; the caller becomes the Secret's +owner. + +The status is `created`, or `already_exists` with `IF NOT EXISTS`. It never +overwrites an existing Secret; use `ALTER SECRET`. + +## ALTER SECRET {#alter} + + +```sql SQL icon="database" +ALTER SECRET platform.`model-api-key` SET SECRET_STRING = '' +ALTER SECRET IF EXISTS api_key SET SECRET_STRING = $$$$ +``` + + +Replaces the Secret's value -- `SECRET_STRING` takes the same single-quoted, +dollar-quoted, or bound `$1` parameter forms `CREATE SECRET` does. Every +Function bound to it gets the latest value the next time a job starts -- a +job already running, and its retries, keep the value they captured at their +own start -- without a new Function version. Requires `UPDATE` on the +Secret. + +The status is `altered`, or `not_found` with `IF EXISTS`. + +## DROP SECRET {#drop} + + +```sql SQL icon="database" +DROP SECRET platform.`model-api-key` +DROP SECRET IF EXISTS api_key +``` + + +Deletes the Secret and every grant on it. Functions bound to it fail at their +next job, naming the Secret. Requires `OWNERSHIP` on the Secret. + +The status is `dropped`, or `not_found` with `IF EXISTS`. + + +`DROP SECRET` cannot be undone. A new Secret created under the same name is +picked up by every Function still bound to that name. + + +## SHOW SECRETS {#show} + + +```sql SQL icon="database" +SHOW SECRETS +SHOW SECRETS IN platform +SHOW SECRETS IN analytics.`ml$vision` +SHOW SECRETS IN public +SHOW SECRETS IN platform WHERE name > 'model-api-key' LIMIT 50 +``` + + +Lists the Secret names in one namespace as a sorted `name` column. Without +`IN`, it lists the session's namespace; `IN public` lists the root. `WHERE +name > ''` pages past the last name already seen, and `LIMIT` +bounds the page size; `WHERE` must compare `name` with `>`. Requires +`USAGE` on the database and the namespace. + +## DESCRIBE SECRET {#describe} + + +```sql SQL icon="database" +DESCRIBE SECRET platform.`model-api-key` +DESC SECRET api_key +``` + + +Returns one row: + +| Column | Type | Meaning | +| --- | --- | --- | +| `name` | string | The Secret's name | +| `created_at_millis` | int64 | When it was created, in milliseconds since the Unix epoch | +| `updated_at_millis` | int64 | When its value was last set. Watch this change to confirm a rotation landed. | +| `history` | list of struct `{generation: uint64, at_millis: int64}` | Creation and each rotation since, oldest first, up to the most recent 100 | + +A missing Secret is an error. Requires `USAGE` on the Secret. + +## GRANT and REVOKE {#grant} + + +```sql SQL icon="database" +GRANT CREATE SECRET ON SCHEMA platform TO ROLE platform_admins +GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service +REVOKE UPDATE ON SECRET platform.`model-api-key` FROM ROLE etl +``` + + +`CREATE SECRET` on the containing `SCHEMA` creates one; `OWNERSHIP`, `USAGE` +(bind it to a Function) and `UPDATE` (rotate it) apply to the Secret itself. +See [GRANT and REVOKE](/sql/ddl/grant) for the full statement grammar, every +target type, and the shared mechanics -- grantee forms, no-op rules, and the +status a statement returns -- which apply the same way to a Secret as to +any other object. + +## The value stays out of output {#redaction} + +A Secret's value never appears in a statement's result, an error message, +`EXPLAIN` output, or the query log. The query log masks everything after the +name in `CREATE SECRET`, and everything after `SET` in `ALTER SECRET`. + + +SQL has no syntax for binding a Secret to a Function. Register Functions that +bind Secrets through the Python SDK; see +[Vend a Secret to a Function](/curation/vend-secret). + + +## What to read next {#next} + + + + Create, rotate, list and drop the credential from the Python SDK and SQL. + + + Every object's privileges, and how grants resolve. + + diff --git a/docs/web/sql/ddl/storage-integration.mdx b/docs/web/sql/ddl/storage-integration.mdx new file mode 100644 index 000000000..37351f971 --- /dev/null +++ b/docs/web/sql/ddl/storage-integration.mdx @@ -0,0 +1,243 @@ +--- +title: "Storage Integration" +sidebarTitle: "Storage Integration" +description: "CREATE, DESCRIBE, SHOW and DROP STORAGE INTEGRATION: a namespace-scoped, reusable credential for reading or importing from external storage." +icon: cloud +keywords: ["storage integration", "create storage integration", "show storage integrations", "drop storage integration", "s3", "gcs", "azure", "huggingface", "sql"] +availability: + embedded: unavailable + enterprise: available +--- + +A storage integration is a namespace-scoped catalog object that lets a +query read from, or import from, a storage location outside the +deployment's own tables -- an S3, GCS or Azure prefix, or a HuggingFace +dataset repository -- without embedding a credential in the query itself. +It is addressed and scoped the same way a [Secret](/sql/ddl/secret) is: a +1-3 part identifier, `name`, `namespace.name` or `database.namespace.name`, +with a nested namespace path `$`-joined into that middle part. + +## CREATE STORAGE INTEGRATION {#create} + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION + STORAGE_PROVIDER = 'S3' | 'AZURE' | 'GCP' | 'HUGGINGFACE' + STORAGE_PREFIX = '' + [ = [...] ] +``` + + +`STORAGE_PROVIDER` and `STORAGE_PREFIX` are required for every provider. +`STORAGE_PREFIX` is the URI prefix the integration covers -- a query only +matches an integration whose prefix is a prefix of the URI it reads. +Options ending in `_SECRET` take a [Secret](/sql/ddl/secret) identifier, not +a quoted string: `name`, `namespace.name` or `database.namespace.name`, with a +nested namespace path `$`-joined in the middle part (`` db.`team$prod`.key ``). +Omitted parts default to the session's current database and namespace. +Creating the integration requires `USAGE` on each referenced Secret and on its +database and namespace. Passing an option a provider does not accept, such as +an Azure option on an `S3` integration, is refused. + +### S3 {#s3} + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION raw + STORAGE_PROVIDER = 'S3' + STORAGE_PREFIX = 's3://customer-data/raw/' + STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/lancedb-access' + +CREATE STORAGE INTEGRATION raw + STORAGE_PROVIDER = 'S3' + STORAGE_PREFIX = 's3://customer-data/raw/' + STORAGE_AWS_ACCESS_KEY_ID_SECRET = bootstrap.credentials.aws_key_id + STORAGE_AWS_SECRET_ACCESS_KEY_SECRET = bootstrap.credentials.aws_key_secret +``` + + +| Option | Type | Meaning | +| --- | --- | --- | +| `STORAGE_AWS_ROLE_ARN` | string | an IAM role to assume, by cross-account trust (see [below](#trust)) | +| `STORAGE_AWS_ACCESS_KEY_ID_SECRET` | Secret ref | a static access key ID, paired with the secret key below | +| `STORAGE_AWS_SECRET_ACCESS_KEY_SECRET` | Secret ref | the matching static secret access key | +| `STORAGE_AWS_REGION` | string, optional | the bucket's region | +| `STORAGE_AWS_ENDPOINT` | string, optional | an S3-compatible endpoint URL (MinIO, Tigris, ...) instead of AWS itself | + +Give either `STORAGE_AWS_ROLE_ARN` alone, or both key-pair options together +-- mixing the two, or supplying only one half of the key pair, is refused. + +### Azure {#azure} + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION blobs + STORAGE_PROVIDER = 'AZURE' + STORAGE_PREFIX = 'az://customer-data/raw/' + STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount' + STORAGE_AZURE_TENANT_ID_SECRET = bootstrap.credentials.tenant + STORAGE_AZURE_CLIENT_ID_SECRET = bootstrap.credentials.client + STORAGE_AZURE_CLIENT_SECRET_SECRET = bootstrap.credentials.credential +``` + + +| Option | Type | Meaning | +| --- | --- | --- | +| `STORAGE_AZURE_STORAGE_ACCOUNT` | string | the storage account name | +| `STORAGE_AZURE_TENANT_ID_SECRET` | Secret ref | Entra ID tenant | +| `STORAGE_AZURE_CLIENT_ID_SECRET` | Secret ref | service principal client ID | +| `STORAGE_AZURE_CLIENT_SECRET_SECRET` | Secret ref | service principal client secret | + +All four are required together; there is no role-based alternative for +Azure. + +### GCP {#gcp} + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION gcs + STORAGE_PROVIDER = 'GCP' + STORAGE_PREFIX = 'gs://customer-data/raw/' + GCP_CREDENTIALS_JSON_SECRET = bootstrap.credentials.gcp +``` + + +`GCP_CREDENTIALS_JSON_SECRET` -- note the option name has no `STORAGE_` +prefix, unlike every other provider's options -- names a Secret holding +the full service-account JSON key. It is required; GCP has no role-based +alternative here. + +### HuggingFace {#huggingface} + + +```sql SQL icon="database" +CREATE STORAGE INTEGRATION hub + STORAGE_PROVIDER = 'HUGGINGFACE' + STORAGE_PREFIX = 'hf://datasets/owner/private/data/' + HUGGINGFACE_TOKEN_SECRET = bootstrap.credentials.hf_token +``` + + +`HUGGINGFACE_TOKEN_SECRET` is the only HuggingFace option, and it is +required: creating an integration without it is refused. For anonymous +access, at HuggingFace's default anonymous rate limits, register no +integration for that prefix at all. See +[Inspect Datasets](/curation/inspect-datasets) for the full +read and import workflow this integration unlocks. + +### The S3 trust policy {#trust} + +Creating an `STORAGE_AWS_ROLE_ARN` integration does not finish the AWS +side of the setup. The result row's `trust_policy`, `permissions_policy` +and `configuration_instructions` columns -- also visible from +[`DESCRIBE`](#describe) -- are the IAM policy documents your role needs: +attach `trust_policy` as the role's trust relationship, scoped to +`aws_account_id`, `aws_iam_principal_arn` and `aws_external_id` from the +same row, and attach `permissions_policy` to grant that role read access +to the bucket. `access_verified` reports whether the deployment already +confirmed it can assume the role and read the prefix; `false` typically +means the trust policy has not been attached yet. + +## Reading and importing through the integration {#read-import} + +A query or `CREATE TABLE ... AS SELECT` can reference a matching URI +directly, once an integration covers it -- the integration is never named +in the statement. What the URI reads depends on the provider: + +- **HuggingFace** (`hf://datasets/...`) reads Parquet files from a dataset + repository. See [Inspect Datasets](/curation/inspect-datasets) + for the full workflow, including how a CTAS import distributes across + plan executors. +- **S3, GCS and Azure** (`s3://`, `gs://`, `az://`) read an existing Lance + dataset at that prefix, the same way as a managed table: + + +```sql SQL icon="database" +SELECT * FROM 's3://customer-data/raw/events.lance' LIMIT 10 + +CREATE TABLE events_copy AS +SELECT * FROM 's3://customer-data/raw/events.lance' +``` + + +A CTAS import distributes the same way regardless of provider: disjoint +file and row-group ranges go to plan-executor workers, each writes +uncommitted Lance files, and a coordinator commits the table once every +worker finishes. See [`CREATE TABLE`](/sql/ddl/table#create) for +`CREATE TABLE AS SELECT` syntax in general. + +## DESCRIBE STORAGE INTEGRATION {#describe} + + +```sql SQL icon="database" +DESCRIBE STORAGE INTEGRATION raw +DESC STORAGE INTEGRATION platform.hub +``` + + +Returns one row with every column `CREATE` returns: the provider, prefix, +the Secret references and plain-string options that apply to its +provider (the rest are null), `created_at_millis`, `access_verified`, and +-- for an `STORAGE_AWS_ROLE_ARN` integration -- the generated AWS policy +documents from [above](#trust). No call ever returns a Secret's value, +only the reference naming it. + +## SHOW STORAGE INTEGRATIONS {#show} + + +```sql SQL icon="database" +SHOW STORAGE INTEGRATIONS +SHOW STORAGE INTEGRATIONS IN platform +LIST STORAGE INTEGRATIONS +``` + + +`LIST` is an alias for `SHOW` here. Returns one `name` column; `IN` +narrows the listing to one namespace. + +## DROP STORAGE INTEGRATION {#drop} + + +```sql SQL icon="database" +DROP STORAGE INTEGRATION raw +DROP STORAGE INTEGRATION IF EXISTS raw +``` + + +Returns `dropped`, `true` or `false`. There is no `ALTER STORAGE +INTEGRATION`: to rotate a credential, rotate the Secret it references +(see [Secret](/sql/ddl/secret)) rather than dropping and recreating the +integration. A storage integration an attached database still depends on +blocks the drop; detach the database first. + +## GRANT and REVOKE {#grant} + + +```sql SQL icon="database" +GRANT CREATE STORAGE INTEGRATION ON SCHEMA platform TO ROLE platform_admins +GRANT USAGE ON STORAGE INTEGRATION platform.hub TO ROLE research +GRANT OWNERSHIP ON STORAGE INTEGRATION platform.hub TO ROLE platform_admins +REVOKE USAGE ON STORAGE INTEGRATION platform.hub FROM ROLE research +``` + + +`CREATE_STORAGE_INTEGRATION` on the namespace creates one; `USAGE` on the +integration itself lets a query match and read through it; `OWNERSHIP` +grants full control, including dropping it. See +[Privileges](/governance/privileges#sql) for the full statement syntax, +every grantee form, and how a query picks a matching integration without +naming one. + +## What to read next {#next} + + + + Query and import HuggingFace or object-storage datasets, the most common use of a storage integration today. + + + The credential storage integration options reference. + + + Every privilege, and the grant and revoke syntax that covers each one. + + diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index b1a5e8f1e..6e751667e 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -11,21 +11,27 @@ availability: ## CREATE TABLE {#create} -```sql + +```sql SQL icon="database" CREATE TABLE documents (id BIGINT, title VARCHAR, created_at TIMESTAMP) -CREATE TABLE recent AS SELECT * FROM documents WHERE created_at > now() - INTERVAL '7 days' +CREATE TABLE recent AS +SELECT * FROM documents +WHERE created_at > now() - INTERVAL '7 days' ``` + Column types are Arrow types under SQL names. See [Data types](/sql/data-types). -A table inside a [namespace](/sql/ddl/namespace) is written as a dotted path: -`prod.events.clicks`. +A table inside a [namespace](/sql/ddl/namespace) is written with its +[schema](/basics/catalog#schema) before the name: `` `prod$events`.clicks ``. ## DESCRIBE {#describe} -```sql + +```sql SQL icon="database" DESCRIBE documents ``` + The table's columns and types, without a plan. The SQL counterpart of `table.schema`. @@ -44,9 +50,11 @@ with the SDK instead. See ### A computed column {#computed-column} -```sql + +```sql SQL icon="database" ALTER TABLE t ADD COLUMN doubled AS value * 2 ``` + `AS ` declares a [computed column](/feature-engineering/add-computed-column). The column is committed empty and the expression is stored, not evaluated: @@ -76,12 +84,15 @@ inputs do not force work. A new column is immediately eligible for its first refresh. The server's separate automatic-refresh switch must also be enabled. These options also work beside a Function binding's `version` and `branch`, -continuing the [`caption` Function](/management/function#chain) from Functions: +continuing the [`caption` Function](/curation/create-function#chain) from Create a Function: ```sql ALTER TABLE frames ADD COLUMN caption AS caption(extract_frame(video, ts)) -WITH (version = 'fv_1', auto_refresh_enabled = true, - auto_refresh_interval_seconds = 300); +WITH ( + version = 'fv_1', + auto_refresh_enabled = true, + auto_refresh_interval_seconds = 300 +); ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_enabled = false; ``` @@ -106,9 +117,6 @@ the only toggle. The current setting is in the column's own field metadata, SDK's `table.schema` without submitting a job to ask. */} -{/* -Draft for the Functions release. - ### A function column {#function-column} ```sql @@ -145,25 +153,28 @@ Declaration `WITH` accepts `auto_refresh_enabled` and `branch`. Worker resource options such as `num_workers` belong on `REFRESH COLUMN ... WITH (...)`. -*/} ### Table properties {#properties} -```sql + +```sql SQL icon="database" ALTER TABLE t SET UNENFORCED PRIMARY KEY (id) ``` + Records which column identifies a row. **Unenforced** is not a hedge in the naming: uniqueness is not checked on write, and declaring it does not make duplicates impossible. It tells the planner what to assume. The column must be declared `NOT NULL`. -```sql + +```sql SQL icon="database" ALTER TABLE t SET RTE ALTER TABLE t SET RTE WITH (sharding = 'bucket', column = 'id', buckets = 4) ALTER TABLE t SET RTE WITH (maintained_indexes = '') ALTER TABLE t UNSET RTE ``` + The [real time engine](/tables/realtime-engine) puts a write-ahead log in front of the table, making small frequent writes cheap by batching them out of the @@ -174,15 +185,15 @@ scalar index on that key. `maintained_indexes` chooses which indexes are kept current against WAL rows; omitted, every supported index is kept current, including ones created later. A table with a computed column cannot take a write-ahead log. See -[Background jobs](/maintenance/background-jobs#wal) for how the log gets -folded back into the table. +[RTE Compaction](/enterprise/realtime-engine-compaction) for how +the log gets folded back into the table. [`TABLESAMPLE`](/sql/dql/sampling) is refused on a WAL-backed table, because rows a sample would draw from are not all in the fragments yet. -**Errors and limits** +### Errors and limits {#errors-and-limits} | | | | --- | --- | @@ -194,12 +205,14 @@ Dropping, renaming, or retyping a column is an SDK operation ## CLONE {#clone} -```sql + +```sql SQL icon="database" CREATE TABLE docs_snapshot CLONE documents CREATE TABLE docs_at_v42 CLONE documents AT 42 CREATE TABLE docs_at_release CLONE documents AT TAG 'release-1' CREATE TABLE docs_yesterday CLONE documents AT TIMESTAMP '2026-09-01T00:00:00Z' ``` + A **shallow clone**: the new table shares the source's data files rather than copying them, so it costs one metadata commit regardless of the source's size. @@ -219,9 +232,11 @@ when the copy has to outlive the source's history. ## DROP TABLE {#drop} -```sql + +```sql SQL icon="database" DROP TABLE documents ``` + Removes the table and every version of it. There is no undrop. @@ -230,7 +245,7 @@ Removes the table and every version of it. There is no undrop. **Enterprise job type:** `drop_table` or `drop_object`, depending on how the deployment stores its catalog. See -[Background jobs](/maintenance/background-jobs#teardown). +[Object teardown](/basics/jobs#teardown). ## What to read next {#next} diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index c6c1f7ecb..e039fc43a 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -1,7 +1,7 @@ --- title: "View" sidebarTitle: "View" -description: "CREATE VIEW and DROP VIEW: a saved query, evaluated when read." +description: "Create, describe, list, and drop saved queries with SQL." icon: eye keywords: ["create view", "drop view", "sql", "catalog"] availability: @@ -16,30 +16,42 @@ stores rows and is brought up to date by a refresh; both are [catalog objects](/basics/catalog) defined by a query, differing only in when that query runs. -There is no SDK method for a view, because the thing it stores *is* a SQL -statement. +The SDK methods `create_view`, `describe_view`, `list_views`, and `drop_view` +submit SQL through the connection's Flight endpoint. `drop_view_async` returns +a job of type `query` whose single `id` is the SQL query UUID. Waiting confirms +catalog removal; physical cleanup can continue afterward. ## CREATE VIEW {#create} -```sql + +```sql SQL icon="database" CREATE VIEW "recent_matches" AS SELECT t1.floats FROM "documents" AS t1 INNER JOIN "categories" AS t2 ON t1.ints = t2.ints ``` + -The statement returns the view's schema (column name, data type, nullability), -resolved from the query at creation time. Anything the -[dialect](/sql/functions) supports can define one: joins, predicates, +The statement returns one row with UTF-8 `name`, `query`, and `schema` columns. +`query` contains the stored query, including any declared column aliases, and +`schema` contains its Arrow schema as JSON. The schema metadata keys +`lancedb::view::default_db` and `lancedb::view::default_namespace` identify the +defining database and namespace. The root namespace is `public`; nested +namespace components are separated by `$`. + +`DESCRIBE VIEW "recent_matches"` returns the same metadata shape. Anything the +[dialect](/sql/dql/functions) supports can define one: joins, predicates, aggregates, window functions. ## Reading one {#reading} A view is queried like a table: -```sql + +```sql SQL icon="database" SELECT * FROM "recent_matches" WHERE floats > 0.5 ``` + Predicates applied to the view compose with the query inside it rather than filtering its output afterwards, so a selective filter does not pay for rows @@ -47,15 +59,28 @@ the view would have produced and then discarded. ## DROP VIEW {#drop} -```sql + +```sql SQL icon="database" DROP VIEW "recent_matches" ``` + Removes the saved query. Unlike dropping a table, no data is removed: there was none to begin with. ## Listing {#listing} +```sql +SHOW VIEWS +SHOW VIEWS IN "analytics" WHERE name > 'previous_view' LIMIT 100 +``` + +`SHOW VIEWS` returns ascending `name` values. The `name` cursor is scoped to +the selected namespace. + +Object commands retain their small results in shared storage even when general +query-result copying is disabled, so asynchronous polling can use any query node. + Views and tables share a namespace, and both are things you can query. The catalog distinguishes them: diff --git a/docs/web/sql/dml/copy.mdx b/docs/web/sql/dml/copy.mdx index 90b655d5b..da44df802 100644 --- a/docs/web/sql/dml/copy.mdx +++ b/docs/web/sql/dml/copy.mdx @@ -12,9 +12,11 @@ supported". On those, export a result by reading it through a Flight SQL client or an SDK and writing the files from your application. -```sql + +```sql SQL icon="database" COPY (SELECT id, title FROM documents) TO 's3://bucket/export/' STORED AS PARQUET ``` + Writes a query result to object storage. This is the export path when the consumer is another engine rather than an application: results land as files diff --git a/docs/web/sql/dml/delete.mdx b/docs/web/sql/dml/delete.mdx index 29b8f65d9..f3069ae5f 100644 --- a/docs/web/sql/dml/delete.mdx +++ b/docs/web/sql/dml/delete.mdx @@ -9,9 +9,11 @@ availability: enterprise: available --- -```sql + +```sql SQL icon="database" DELETE FROM documents WHERE created_at < TIMESTAMP '2025-01-01 00:00:00' ``` + Compare a timestamp column with a typed literal, as above, or with `CAST('2025-01-01' AS TIMESTAMP)`. A bare string such as `'2025-01-01'` is diff --git a/docs/web/sql/dml/insert.mdx b/docs/web/sql/dml/insert.mdx index 71a7d1182..c8ee8c62f 100644 --- a/docs/web/sql/dml/insert.mdx +++ b/docs/web/sql/dml/insert.mdx @@ -9,11 +9,15 @@ availability: enterprise: available --- -```sql + +```sql SQL icon="database" INSERT INTO documents (id, title) VALUES (1, 'Merlin'), (2, 'Arthur') -INSERT INTO archive SELECT * FROM documents WHERE created_at < '2026-01-01' +INSERT INTO archive +SELECT * FROM documents +WHERE created_at < '2026-01-01' ``` + `INSERT ... SELECT` is the form worth knowing: it moves rows between tables server-side, without a round trip through your process. diff --git a/docs/web/sql/dml/refresh-column.mdx b/docs/web/sql/dml/refresh-column.mdx index db5d26475..fcb78bd35 100644 --- a/docs/web/sql/dml/refresh-column.mdx +++ b/docs/web/sql/dml/refresh-column.mdx @@ -1,7 +1,7 @@ --- title: "REFRESH COLUMN" sidebarTitle: "REFRESH COLUMN" -description: "Filling a computed column: idempotent, scoped, and resumable." +description: "Fill computed outputs and select rows to recompute." icon: arrows-rotate keywords: ["refresh column", "backfill", "computed column"] availability: @@ -13,59 +13,88 @@ A LanceDB extension with no DataFusion equivalent. It is what makes [feature engineering](/feature-engineering) reachable from SQL: a column declared by [DDL](/sql/ddl/table#computed-column) starts empty, and a refresh fills it. -```sql + +```sql SQL icon="database" REFRESH COLUMN ON [TABLE]
[WHERE ] [WITH (
, , - distance_threshold => - [, resolution => 'connected_components' | 'direct_representative'] - [, selection => 'all' | 'first' | 'random', count => , seed => ] + +```sql SQL icon="database" +SELECT * FROM dedupe( +
, + , + distance_threshold => + [, resolution => 'connected_components' | 'direct_representative'] ) ``` + -```sql -SELECT * FROM dedupe('frames', 'vec', distance_threshold => 0.02) + +```sql SQL icon="database" +SELECT * FROM dedupe( + 'frames', + 'vec', + distance_threshold => 0.02 +) ``` + Earlier releases spelled this `vector_dedup`; that name is rejected on @@ -41,13 +50,10 @@ current deployments. | vector column | string literal | yes | the indexed vector column to compare | | `distance_threshold` | float | yes | maximum distance for a pair to count as close | | `resolution` | `'connected_components'` (default) \| `'direct_representative'` | no | how overlapping pairs group together -- see [Resolution](#resolution) | -| `selection` | `'all'` (default) \| `'first'` \| `'random'` | no | which index partitions to scan | -| `count` | int | no | number of partitions to sample when `selection => 'random'` | -| `seed` | int | no | random seed when `selection => 'random'` | -`id_column` is refused on `dedupe`: it has no separate pair-identifier output -to project onto, only [`duplicate_pairs`](/sql/dql/duplicate-pairs#input) -accepts it. +`dedupe` always scans every partition and returns original rows -- sampling +a subset of partitions and `id_column` are pair-query-only options, accepted +by [`duplicate_pairs`](/sql/dql/duplicate-pairs#input) but refused here. ## Output {#output} @@ -61,31 +67,32 @@ table's schema. Because the result is already shaped like the table, it composes directly into a new table or a materialized view: -```sql + +```sql SQL icon="database" CREATE MATERIALIZED VIEW frames_deduped AS -SELECT * FROM dedupe('frames', 'vec', distance_threshold => 0.02) +SELECT * FROM dedupe( + 'frames', + 'vec', + distance_threshold => 0.02 +) ``` + ## Resolution {#resolution} `resolution` chooses how overlapping pairs group together: -| `resolution` | | +| `resolution` value | How pairs group | | --- | --- | | `connected_components` (default) | groups transitively: if a~b and b~c are both close, all three resolve together | | `direct_representative` | only pairs within the threshold of each other resolve together | -## Sampling partitions {#sampling} +## Estimating on a sample first {#sampling} -`selection` scopes the scan to a sample of partitions instead of all of them, -the same `all` (default) / `first` / `random` choice as -[`ivf_partition`](/sql/scalar-functions#ivf-partition). Use it to estimate a -duplicate rate on a large table before scanning it in full: - -```sql -SELECT * FROM dedupe('frames', 'vec', - distance_threshold => 0.02, selection => 'random', count => 100, seed => 42) -``` +`dedupe` itself always scans every partition. To estimate a duplicate rate +on a large table before committing to a full scan, sample partitions with +[`duplicate_pairs`](/sql/dql/duplicate-pairs#sampling) instead, which +accepts `selection`, `count` and `seed` for exactly this. ## What to read next {#next} diff --git a/docs/web/sql/dql/duplicate-pairs.mdx b/docs/web/sql/dql/duplicate-pairs.mdx index e8651a28c..daa078955 100644 --- a/docs/web/sql/dql/duplicate-pairs.mdx +++ b/docs/web/sql/dql/duplicate-pairs.mdx @@ -16,17 +16,27 @@ row per source row -- use it to inspect what would be collapsed before committing to [`dedupe`](/sql/dql/dedupe), which resolves these same pairs into groups. -```sql -SELECT * FROM duplicate_pairs(
, , - distance_threshold => - [, id_column => ] - [, selection => 'all' | 'first' | 'random', count => , seed => ] + +```sql SQL icon="database" +SELECT * FROM duplicate_pairs( +
, + , + distance_threshold => + [, id_column => ] + [, selection => 'all' | 'first' | 'random', count => , seed => ] ) ``` + -```sql -SELECT * FROM duplicate_pairs('frames', 'vec', distance_threshold => 0.02) + +```sql SQL icon="database" +SELECT * FROM duplicate_pairs( + 'frames', + 'vec', + distance_threshold => 0.02 +) ``` + Earlier releases spelled this `vector_duplicate_pairs`; that name is rejected @@ -57,33 +67,49 @@ table: | --- | --- | --- | | `row_id_a` | uint64 | internal row ID of the first row in the pair, the same identifier as the [`_rowid`](/sql/data-types#pseudo-columns) pseudo-column | | `row_id_b` | uint64 | internal row ID of the second row in the pair | -| `distance` | float32 | distance between the pair's vectors, at or below `distance_threshold` | -| `segment_id` | int64 | which index segment the pair was found in | -| `partition_id` | int64 | which index partition the pair was found in | -| `dataset_version` | int64 | the dataset version the scan ran against | +| `distance` | float32 | distance between the pair's vectors, at or below `distance_threshold`. For `l2`, this is the squared distance, not its square root | +| `segment_id` | Utf8 | which index segment the pair was found in, a UUID | +| `partition_id` | uint64 | which index partition the pair was found in | +| `dataset_version` | uint64 | the dataset version the scan ran against | ### Application-level identifiers {#id-column} A row ID is internal and not stable across compaction. Pass `id_column`, a -top-level scalar column such as a primary key, to project its value instead: -`row_id_a`/`row_id_b` are replaced by `id_a`/`id_b`, typed like `id_column`. +top-level scalar column such as a primary key, to also project its value: +`id_a`/`id_b`, typed like `id_column`, are appended alongside +`row_id_a`/`row_id_b`, which remain in the output. -```sql -SELECT * FROM duplicate_pairs('frames', 'vec', distance_threshold => 0.02, id_column => 'frame_id') + +```sql SQL icon="database" +SELECT * FROM duplicate_pairs( + 'frames', + 'vec', + distance_threshold => 0.02, + id_column => 'frame_id' +) ``` + ## Sampling partitions {#sampling} `selection` scopes the scan to a sample of partitions instead of all of them, the same `all` (default) / `first` / `random` choice as -[`ivf_partition`](/sql/scalar-functions#ivf-partition). Use it to estimate a +[`ivf_partition`](/sql/dql/ivf-partition). Use it to estimate a distance threshold or duplicate rate on a large table before scanning it in full: -```sql -SELECT * FROM duplicate_pairs('frames', 'vec', - distance_threshold => 0.02, selection => 'random', count => 100, seed => 42) + +```sql SQL icon="database" +SELECT * FROM duplicate_pairs( + 'frames', + 'vec', + distance_threshold => 0.02, + selection => 'random', + count => 100, + seed => 42 +) ``` + ## What to read next {#next} diff --git a/docs/web/sql/dql/explain.mdx b/docs/web/sql/dql/explain.mdx index 151a861bc..431a71928 100644 --- a/docs/web/sql/dql/explain.mdx +++ b/docs/web/sql/dql/explain.mdx @@ -9,10 +9,12 @@ availability: enterprise: available --- -```sql + +```sql SQL icon="database" EXPLAIN SELECT * FROM documents WHERE identifier < 1000 EXPLAIN ANALYZE SELECT * FROM documents WHERE identifier < 1000 ``` + | Statement | What it returns | | --- | --- | @@ -25,15 +27,15 @@ through the same client you use for regular queries. See [Connecting](/sql#connecting). SQL plans and the SDK's -[`explain_plan` and `analyze_plan`](/search/explain) output share scan and index +[`explain_plan` and `analyze_plan`](/basics/sql#query-plans) output share scan and index operators. Use the same approach to inspect index coverage and filter pushdown; SQL can also add joins, aggregates and other operators: - + Reading a plan: operators, pushdown, index usage. - + Reading the metrics, and a worked before/after. diff --git a/docs/web/sql/dql/fts.mdx b/docs/web/sql/dql/fts.mdx index 3dc6d3a3e..7b52f5e17 100644 --- a/docs/web/sql/dql/fts.mdx +++ b/docs/web/sql/dql/fts.mdx @@ -20,7 +20,8 @@ classes used from the SDK and serialized with `.to_json()`. Run these statements in order, sending one statement per SQL request. Semicolons separate the statements for clients that execute a script. -```sql + +```sql SQL icon="database" CREATE TABLE my_docs (id INT, text STRING, category STRING, author STRING); INSERT INTO my_docs VALUES @@ -31,6 +32,7 @@ INSERT INTO my_docs VALUES CREATE INDEX ON my_docs USING fts (text); ``` + Phrase queries need position information, which costs extra index size. @@ -45,28 +47,40 @@ The query builder produces the JSON string used as the second SQL argument. The SQL examples below spell out the equivalent match object so they can be run directly after the setup above. -```python + +```python Python icon="python" from lancedb.query import MatchQuery query = MatchQuery("puppy", "text") json_query = query.to_json() ``` + -```sql + +```sql SQL icon="database" SELECT id, text, category -FROM fts('my_docs', '{"match":{"column":"text","terms":"puppy"}}') +FROM fts( + 'my_docs', + '{"match":{"column":"text","terms":"puppy"}}' +) LIMIT 5 ``` + By default the top 5 matches come back in **arbitrary order**. Select `_score` and order by it for relevance ranking: -```sql + +```sql SQL icon="database" SELECT id, text, _score -FROM fts('my_docs', '{"match":{"column":"text","terms":"puppy"}}') +FROM fts( + 'my_docs', + '{"match":{"column":"text","terms":"puppy"}}' +) ORDER BY _score DESC LIMIT 5 ``` + `_score` is a pseudo-column carrying the query's BM25 relevance for the row; it behaves like any other column, but exists only in a relation that came @@ -76,35 +90,42 @@ from `fts()`. See [Data types](/sql/data-types#pseudo-columns). Tolerates typos, up to a character-edit budget: -```python + +```python Python icon="python" MatchQuery("pupy", "text", fuzziness=2) ``` + ## Phrase {#phrase} Exact phrase, or with `slop` to allow words between terms: -```python + +```python Python icon="python" from lancedb.query import PhraseQuery PhraseQuery("happy puppy", "text") PhraseQuery("puppy park", "text", slop=2) # up to 2 words between them ``` + ## Boolean {#boolean} Combine queries with `&` (AND) or `|` (OR): -```python + +```python Python icon="python" MatchQuery("puppy", "text") & MatchQuery("happy", "text") MatchQuery("puppy", "text") | MatchQuery("kitten", "text") ``` + ## Boost {#boost} Weight a query up or down relative to another: -```python + +```python Python icon="python" from lancedb.query import BoostQuery BoostQuery( @@ -113,29 +134,37 @@ BoostQuery( negative_boost=0.2, ) ``` + ## Multi-match {#multi-match} Search several columns at once, optionally weighting them differently: -```python + +```python Python icon="python" from lancedb.query import MultiMatchQuery MultiMatchQuery("puppy", ["text", "category"]) MultiMatchQuery("puppy", ["text", "category"], boosts=[2.0, 1.0]) # text weighted 2x ``` + ## Combining with SQL {#combining} `fts()` is a relation, so it composes with the rest of the SQL surface. Filter, join, or aggregate over it same as any table: -```sql + +```sql SQL icon="database" SELECT id, text, category -FROM fts('my_docs', '{"match":{"column":"text","terms":"puppy"}}') +FROM fts( + 'my_docs', + '{"match":{"column":"text","terms":"puppy"}}' +) WHERE category = 'animals' LIMIT 5 ``` + ## What to read next {#next} diff --git a/docs/web/sql/dql/functions.mdx b/docs/web/sql/dql/functions.mdx new file mode 100644 index 000000000..0ea53a508 --- /dev/null +++ b/docs/web/sql/dql/functions.mdx @@ -0,0 +1,61 @@ +--- +title: "Functions" +sidebarTitle: "Functions" +description: "Where to find each kind of function, and the dialect version they come from." +icon: function +keywords: ["functions", "datafusion", "scalar", "aggregate", "window", "fts", "table function"] +availability: + embedded: unavailable + enterprise: available +--- + +LanceDB executes SQL with [Apache DataFusion](https://datafusion.apache.org), +currently **version 54**. The function set is DataFusion's default registration +plus what Lance adds. + +| | | +| --- | --- | +| [Scalar functions](/sql/dql/scalar-functions) | per row: math, string, regex, date/time, array, struct{/* Draft until JSON columns reach early access: restore ", JSON" */} | +| [Aggregate functions](/sql/dql/aggregation#functions) | per group: `count`, `sum`, statistical, approximate | +| [Window functions](/sql/dql/window#functions) | per window: ranking, offset, running aggregates | +| [Table functions](#table-functions) | produce a relation rather than a value | + + +Function availability is version-specific. DataFusion adds functions in most +releases, so one documented on `main` may not exist in 54. When a name is not +recognised, check it against the reference for that version before assuming a +bug. + + +## Table functions {#table-functions} + +A table function appears in `FROM` and produces a relation, which is what lets +it return columns a scalar function has nowhere to put. Each has its own +reference page: + +| | | +| --- | --- | +| [`fts(table, query)`](/sql/dql/fts) | full-text search, with a relevance score alongside the matching rows | +| [`dedupe(table, column, ...)`](/sql/dql/dedupe) | one representative row per near-duplicate group | +| [`duplicate_pairs(table, column, ...)`](/sql/dql/duplicate-pairs) | every close pair, before resolving into groups | +| [`generate_series(start, stop)`](/sql/dql/generate-series) | rows from a range | + +`_score`, the relevance pseudo-column `fts()` produces, is not a function; +see [Data types](/sql/data-types#pseudo-columns). + +## What Lance accelerates {#accelerated} + +`contains_tokens` uses an index rather than scanning, which is the difference +between a fast predicate and a slow one: + +| | Index used | +| --- | --- | +| [`contains_tokens`](/sql/dql/contains-tokens) | full-text index | + +{/* +Draft until JSON columns reach early access; restore "Two function families" above. +| [`json_get`, typed variants, `json_extract`](/sql/dql/json-functions) | JSON scalar index | +*/} + +Confirm with [`EXPLAIN`](/sql/dql/explain): an accelerated predicate shows an +index node rather than a `LanceScan` followed by a filter. diff --git a/docs/web/sql/dql/generate-series.mdx b/docs/web/sql/dql/generate-series.mdx new file mode 100644 index 000000000..46dcfe55b --- /dev/null +++ b/docs/web/sql/dql/generate-series.mdx @@ -0,0 +1,30 @@ +--- +title: "GENERATE_SERIES" +sidebarTitle: "GENERATE_SERIES" +description: "The generate_series() table function: rows from a range." +icon: list-ol +keywords: ["generate_series", "sql", "table function", "range", "series"] +availability: + embedded: unavailable + enterprise: available +--- + + +```sql SQL icon="database" +SELECT * FROM generate_series( + 1, + 10 +) +``` + + +Rows from a range, useful for building a dense axis to left-join sparse data +onto. + +## What to read next {#next} + + + + The other table functions: `fts`, `dedupe`, and `duplicate_pairs`. + + diff --git a/docs/web/sql/dql/ivf-partition.mdx b/docs/web/sql/dql/ivf-partition.mdx new file mode 100644 index 000000000..2797da03c --- /dev/null +++ b/docs/web/sql/dql/ivf-partition.mdx @@ -0,0 +1,59 @@ +--- +title: "IVF_PARTITION" +sidebarTitle: "IVF_PARTITION" +description: "The ivf_partition() scalar function: assign each row to its trained IVF index partition." +icon: circle-nodes +keywords: ["ivf_partition", "sql", "vector index", "ivf", "partition", "scalar function", "clustering", "blocking"] +availability: + embedded: unavailable + enterprise: available +--- + + +```sql SQL icon="database" +SELECT + ivf_partition(embedding, selection => 'random', count => 100, seed => 42) AS partition, + array_agg(id) AS ids +FROM documents +GROUP BY partition +``` + + +`ivf_partition` reads an existing IVF-family vector index's trained +partitions and assigns each row to the one its vector falls into. The column +needs an up-to-date, single-segment index before the function runs -- the +same requirement [`dedupe`](/curation/dedupe#example-data) has. + +Grouping by its result buckets rows by vector proximity without a full +pairwise scan -- useful for blocking a large table into comparable chunks, +such as before a pairwise similarity pass. + +## Input {#input} + +`ivf_partition` takes exactly 1, 3, or 4 arguments -- the vector column +alone (scans every partition), or the vector column plus `selection` and +`count`, plus `seed` only when `selection` is `'random'`: + +| Argument | Type | Required | Meaning | +| --- | --- | --- | --- | +| vector column | column reference | yes | the indexed vector column to assign | +| `selection` | `'first'` \| `'random'` | required with `count` | which partitions to sample -- there is no explicit `'all'`; omit `selection` and `count` entirely to scan every partition | +| `count` | int, > 0 | required with `selection` | number of partitions to sample | +| `seed` | int, >= 0 | required for `'random'`, refused for `'first'` | random seed | + +Arguments can be passed positionally, `ivf_partition(embedding, 'random', 100, 42)`, +or named as shown above. `count` and `seed` are the same scan-scoping +arguments [`duplicate_pairs`](/sql/dql/duplicate-pairs#sampling) accepts, +so a sampled partition estimate carries over -- but not `dedupe`, which +always scans every partition and refuses sampling arguments entirely. + +## What to read next {#next} + + + + Use this function to group and sample records by an existing index's partitions. + + + The packaged table function for the deduplication use case, over the same index. + + diff --git a/docs/web/sql/dql/join.mdx b/docs/web/sql/dql/join.mdx index ecc81ec31..23384a181 100644 --- a/docs/web/sql/dql/join.mdx +++ b/docs/web/sql/dql/join.mdx @@ -13,11 +13,13 @@ Use SQL joins to combine rows from two or more tables. ## The join types {#types} -```sql + +```sql SQL icon="database" SELECT d.title, c.name FROM documents AS d JOIN categories AS c ON c.id = d.category_id ``` + | | What it keeps | | --- | --- | @@ -32,29 +34,37 @@ avoids repeating it in the select list. ## Across namespaces {#namespaces} -Tables in different [namespaces](/management/namespace) join by their dotted paths. The -catalog is one catalog, so there is nothing to federate: +Tables in different [namespaces](/management/namespace) join like any other table, each +addressed by its full `database.schema.table` identifier. The catalog is one +catalog, so there is nothing to federate: -```sql + +```sql SQL icon="database" SELECT c.id, u.email FROM prod.events.clicks AS c JOIN prod.reference.users AS u ON u.id = c.user_id ``` + ## Joining a search result {#search} -[`fts()`](/sql/functions#fts) is a table function, so its result is a relation +[`fts()`](/sql/dql/fts) is a table function, so its result is a relation and joins like any other. This example assumes `my_docs` has `text` and `category_id` columns, a full-text index on `text`, and a `categories` table with `id` and `name` columns: -```sql + +```sql SQL icon="database" SELECT c.name, count(*) AS hits -FROM fts('my_docs', '{"match":{"column":"text","terms":"puppy"}}') AS m +FROM fts( + 'my_docs', + '{"match":{"column":"text","terms":"puppy"}}' +) AS m JOIN categories AS c ON c.id = m.category_id GROUP BY c.name ORDER BY hits DESC ``` + That composition is the reason full-text search is a relation rather than a predicate: a `WHERE` clause has nowhere to put the relevance score. @@ -75,25 +85,8 @@ column can be materialized many more times than the result has rows. ## Late materialization for wide columns {#late-materialization} The planner can avoid the multiplication above: when a join narrows down to -a key column (such as `_rowid` or another narrow, selective column) before a -wide one is needed, it can defer reading a BlobV2 or vector column until -after the join has already settled which rows survive, instead of reading it -for every candidate row first. In a plan where this applies, the wide column -is read once per surviving row, where the worker runs, and never pulled into -the query node to be joined directly. - -```sql -SELECT d.title, b.caption -FROM documents AS d -JOIN (SELECT _rowid, caption FROM captions WHERE source = 'model-v2') AS b - ON b._rowid = d._rowid -``` - -This is query planning, not a syntax you opt into: a join written this way -is a **candidate** for the planner to defer the wide read, not a guarantee. -Confirm it for a specific query with [`EXPLAIN`](/sql/dql/explain) -- -`RemoteTake` in the plan means the deferral happened; its absence means the -wide column was read eagerly, even if the SQL above matches exactly. Neither -a passing query nor an `EXPLAIN` that omits `RemoteTake` tells you how much -I/O a plan did or did not save -- read the plan's own row and byte counts for -that. +a key column before a wide one is needed, it can defer reading a BlobV2 or +vector column until after the join has already settled which rows survive. +See [Blob Late Materialization](/curation/blob-late-materialization) for +the eligibility conditions, the `RemoteTake` operator, and how to confirm +a specific query got the deferred read with [`EXPLAIN`](/sql/dql/explain). diff --git a/docs/web/sql/dql/json-functions.mdx b/docs/web/sql/dql/json-functions.mdx new file mode 100644 index 000000000..9cdd289fa --- /dev/null +++ b/docs/web/sql/dql/json-functions.mdx @@ -0,0 +1,57 @@ +--- +title: "JSON functions" +sidebarTitle: "JSON Functions" +description: "json_get and its typed variants, json_extract, and the rest of Lance's JSON accessor functions." +icon: brackets-curly +keywords: ["json_get", "json_extract", "json", "sql", "scalar function"] +availability: + embedded: unavailable + enterprise: available +--- + +| Function | Returns | +| --- | --- | +| `json_get(col, key)` | the value at `key`, still JSON | +| `json_get_string(col, key)` | `Utf8` | +| `json_get_int(col, key)` | `Int64` | +| `json_get_float(col, key)` | `Float64` | +| `json_get_bool(col, key)` | `Boolean` | +| `json_extract(col, path)` | `Utf8`: the value as JSON text, by path | +| `json_extract_with_type(col, path)` | a struct of the value as JSON and a type tag, by path | +| `json_exists(col, path)` | `Boolean` | +| `json_array_contains(col, value)` | `Boolean` | +| `json_array_length(col)` | length | + +`json_get` returns JSON, so a typed accessor can read a field inside it: + + +```sql SQL icon="database" +SELECT * FROM events +WHERE json_get_string(json_get(data, 'user'), 'name') = 'Alice' +``` + + +That works one level down. A `json_get` nested inside another `json_get` is +refused, so reach a deeper value with `json_extract` and a JSONPath instead. It +returns JSON text, so a string compares with its quotes: + + +```sql SQL icon="database" +SELECT * FROM events +WHERE json_extract(data, '$.user.profile.name') = '"Alice"' +``` + + +**`json_get`, its typed variants, and `json_extract` are index-accelerated** by a +JSON scalar index on the column. The rest evaluate per row. + +## What to read next {#next} + + + + How a JSON column is stored, and reading it as a typed value. + + + Build the scalar index that accelerates `json_get` and `json_extract`. + + diff --git a/docs/web/sql/operators.mdx b/docs/web/sql/dql/operators.mdx similarity index 97% rename from docs/web/sql/operators.mdx rename to docs/web/sql/dql/operators.mdx index 156fab3b0..971d86a58 100644 --- a/docs/web/sql/operators.mdx +++ b/docs/web/sql/dql/operators.mdx @@ -26,7 +26,7 @@ operator precedence. | `~` `~*` `!~` | regular expression match | -For keyword matching on a text column, [`contains_tokens`](/sql/scalar-functions#contains-tokens) +For keyword matching on a text column, [`contains_tokens`](/sql/dql/contains-tokens) is index-accelerated where `LIKE` is not. Reach for `LIKE` only when you need its wildcard semantics. @@ -67,10 +67,12 @@ or a name with mixed case): `SELECT "order" FROM "MyTable"`. ## Casting {#casting} -```sql + +```sql SQL icon="database" SELECT CAST(identifier AS VARCHAR) AS with_cast, identifier::VARCHAR AS with_colons FROM documents ``` + Both forms work. Give each its own alias when one projection uses both: they produce the same expression name, and a projection refuses two columns with diff --git a/docs/web/sql/dql/sampling.mdx b/docs/web/sql/dql/sampling.mdx index 954247142..b6b24f8eb 100644 --- a/docs/web/sql/dql/sampling.mdx +++ b/docs/web/sql/dql/sampling.mdx @@ -13,10 +13,12 @@ Use `TABLESAMPLE` to explore a subset of a table or estimate aggregate statistics. The sampling method determines how much data is read and whether the table's physical layout influences the sample. -```sql + +```sql SQL icon="database" SELECT * FROM documents TABLESAMPLE (10) -- 10 percent SELECT * FROM documents TABLESAMPLE (500 ROWS) -- 500 rows ``` + A bare number is a **percentage**. Add `ROWS` for a count instead. @@ -25,10 +27,12 @@ A bare number is a **percentage**. Add `ROWS` for a count instead. The standard calls these two methods of one clause. They are different operations, and the difference matters on Lance: -```sql + +```sql SQL icon="database" SELECT * FROM documents TABLESAMPLE BERNOULLI (10) SELECT * FROM documents TABLESAMPLE SYSTEM (10) ``` + | Method | Aliases | What it picks | | --- | --- | --- | @@ -50,9 +54,11 @@ independent row sampling. Omitting the method gives Without a seed, every execution resamples: running the same query twice gives different rows. `REPEATABLE` fixes the draw: -```sql + +```sql SQL icon="database" SELECT * FROM documents TABLESAMPLE (10) REPEATABLE (42) ``` + Use the same seed and table snapshot to reproduce a sampling run. For a fixed evaluation set, save the selected row IDs or materialize the sample and retain @@ -64,13 +70,15 @@ or changes to the physical layout. It attaches to a table in `FROM`, including inside a subquery, a CTE, or either side of a join: -```sql + +```sql SQL icon="database" SELECT * FROM (SELECT * FROM documents TABLESAMPLE (10)) d SELECT * FROM a TABLESAMPLE (5 ROWS) JOIN b ON a.id = b.id SELECT * FROM t a TABLESAMPLE (10) JOIN t b TABLESAMPLE (10) ON a.id = b.id ``` + Each side of a join samples independently. Sampling both sides of a join shrinks the *result* far more than either fraction suggests, because a row only diff --git a/docs/web/sql/dql/scalar-functions.mdx b/docs/web/sql/dql/scalar-functions.mdx new file mode 100644 index 000000000..9bd2057b0 --- /dev/null +++ b/docs/web/sql/dql/scalar-functions.mdx @@ -0,0 +1,161 @@ +--- +title: "Scalar functions" +sidebarTitle: "Scalar Functions" +description: "The per-row function set: math, string, regex, date/time, array, struct, and what Lance adds." +icon: calculator +keywords: ["scalar functions", "string functions", "math functions", "regex", "array functions"] +availability: + embedded: unavailable + enterprise: available +--- + +Functions that take a value and return a value, one row at a time. The set is +based on DataFusion's registration plus Lance and deployment-specific +functions. The names below are selected examples, not an exhaustive catalog +for every deployment. Availability depends on the deployed version and build. + +For per-group functions see [Aggregation](/sql/dql/aggregation); for per-window, +[Window functions](/sql/dql/window). + +## Math {#math} + +```text +abs ceil floor round trunc signum power sqrt cbrt exp +ln log log2 log10 factorial gcd lcm pi random nanvl +isnan iszero cot degrees radians to_degrees to_radians +sin cos tan asin acos atan atan2 +sinh cosh tanh asinh acosh atanh +``` + +## String {#string} + +```text +ascii bit_length btrim chr concat concat_ws contains ends_with +starts_with levenshtein lower upper ltrim rtrim octet_length +repeat replace split_part to_hex uuid +``` + +Unicode-aware variants: + +```text +character_length find_in_set initcap left right lpad rpad +reverse strpos substr substr_index substring translate +``` + + +For keyword matching on a text column, [`contains_tokens`](/sql/dql/contains-tokens) +is index-accelerated where `contains` and `LIKE` are not. + + +## Regular expressions {#regex} + +```text +regexp_count regexp_instr regexp_like regexp_match regexp_replace +``` + +## Date and time {#datetime} + +```text +current_date current_time date_bin date_part date_trunc +from_unixtime to_unixtime make_date make_time to_char +to_date to_time to_local_time +``` + +`date_bin` is the one worth knowing for analytics: it buckets timestamps into +fixed-width intervals, which is how you build a time series without a +self-join. + + +```sql SQL icon="database" +SELECT date_bin(INTERVAL '1 hour', created_at) AS hour, count(*) +FROM events +GROUP BY hour +ORDER BY hour +``` + + +## Arrays and maps {#arrays} + +```text +make_array array_has array_filter array_transform array_any_match +array_compact array_normalize array_slice arrays_zip cardinality +flatten range generate_series +``` + +```text +map map_keys map_values map_entries map_extract +``` + +Distance functions over arrays: `cosine_distance`, `distance`, +`exact_distance`, `inner_product`. Only `distance` and `exact_distance` +take an options string, and only `distance` can plan as vector search; see +[Vector distance functions](/sql/dql/vector-distance). + +## Structs and fields {#structs} + +```text +named_struct get_field coalesce nullif nvl nvl2 greatest least +union_extract union_tag +``` + +## Crypto and encoding {#crypto} + +```text +digest md5 sha224 sha256 sha384 sha512 encode decode +``` + +## Type functions {#type} + +```text +arrow_cast arrow_try_cast arrow_typeof arrow_field arrow_metadata +with_metadata version +``` + +Use `arrow_typeof` to inspect the Arrow data type of a column or expression: + + +```sql SQL icon="database" +SELECT arrow_typeof(vector) FROM documents LIMIT 1 +-- FixedSizeList(Field { name: "item", data_type: Float32, .. }, 1536) +``` + + +`arrow_cast` casts to an Arrow type by name, reaching types SQL has no spelling +for. See [Data types](/sql/data-types). + +## What Lance adds {#lance} + +These are registered by Lance on top of DataFusion's set, each with its own +reference page: + +| | | +| --- | --- | +| [`contains_tokens`](/sql/dql/contains-tokens) | index-accelerated keyword predicate, usable in `WHERE` | +| [`ivf_partition`](/sql/dql/ivf-partition) | assign each row to its trained IVF index partition | +| [`blob_descriptor`](/sql/dql/blob-descriptor) | a BlobV2 column's payload location, without reading it | + +{/* +Draft until JSON columns reach early access. +| [JSON accessors](/sql/dql/json-functions) | `json_get` and its typed variants, `json_extract`, and more | +*/} + +{/* +Draft: geospatial queries and indexes are unsupported in LanceDB Enterprise. + +### Geospatial {#geo} + + +Lance defines `st_*` functions on GeoArrow, but they sit behind a build feature +**LanceDB does not ship**. Calling one returns an error naming the missing +feature rather than an unknown-function error, and the spatial index is gated +the same way. + +*/} + +## Additional scalar functions {#escape-hatch} + +SQL queries can call functions registered with the server, including functions +not listed on this page. Consult +[DataFusion's scalar function reference](https://datafusion.apache.org/user-guide/sql/scalar_functions.html) +for version 54. Functions documented for a newer DataFusion release may not be +available in your LanceDB Enterprise version. diff --git a/docs/web/sql/dql/select.mdx b/docs/web/sql/dql/select.mdx index 621061204..8306fa093 100644 --- a/docs/web/sql/dql/select.mdx +++ b/docs/web/sql/dql/select.mdx @@ -9,7 +9,8 @@ availability: enterprise: available --- -```sql + +```sql SQL icon="database" [WITH cte AS (...)] SELECT [ALL | DISTINCT] select_expr [, ...] FROM from_item [[JOIN ...] ON ...] @@ -19,11 +20,12 @@ FROM from_item [[JOIN ...] ON ...] [ORDER BY expr [ASC | DESC] [NULLS FIRST | LAST] [, ...]] [LIMIT n] [OFFSET n] ``` + ## Projection {#projection} -```sql SQL +```sql SQL icon="database" SELECT id, title, identifier FROM documents ``` @@ -50,7 +52,7 @@ Row metadata is available as [pseudo-columns](/sql/data-types#pseudo-columns) ## Filtering {#filtering} -```sql SQL +```sql SQL icon="database" SELECT * FROM documents WHERE identifier > 0 AND identifier < 1000000 ``` @@ -66,16 +68,18 @@ await tbl.query().where("identifier > 0 AND identifier < 1000000").toArrow(); The SDK `where` takes the same expression language, so a predicate moves between them unchanged. A supported predicate can use a scalar index; confirm the chosen plan with -[`explain_plan`](/search/explain). See +[`explain_plan`](/basics/sql#query-plans). See [Filtering](/search/filtering) for the operators and their pushdown behaviour. ## Ordering and limiting {#order-limit} -```sql + +```sql SQL icon="database" SELECT id, title FROM documents ORDER BY created_at DESC NULLS LAST LIMIT 100 OFFSET 200 ``` + `ORDER BY` on a large table is a sort over the whole result, so pair it with a `LIMIT` unless you genuinely need every row ordered. @@ -84,23 +88,27 @@ LIMIT 100 OFFSET 200 `UNION`, `UNION ALL`, `INTERSECT` and `EXCEPT` combine whole queries: -```sql + +```sql SQL icon="database" SELECT id FROM documents WHERE category = 'film' UNION ALL SELECT id FROM archived_documents WHERE category = 'film' ``` + `UNION` deduplicates and `UNION ALL` does not, which makes `UNION ALL` the cheaper one when you already know the inputs are disjoint. ## Common table expressions {#ctes} -```sql + +```sql SQL icon="database" WITH recent AS ( SELECT * FROM documents WHERE created_at > now() - INTERVAL '7 days' ) SELECT category, count(*) FROM recent GROUP BY category ``` + A CTE is scoped to the statement. One you want to keep is a [view](/management/view); one whose rows you want stored is a @@ -111,27 +119,35 @@ A CTE is scoped to the statement. One you want to keep is a Subqueries are allowed anywhere an expression or a relation is (in `FROM`, in `WHERE` with `IN` or `EXISTS`, and as a scalar in the select list): -```sql + +```sql SQL icon="database" SELECT title FROM documents WHERE category_id IN (SELECT id FROM categories WHERE active) ``` + ## Namespaced tables {#namespaces} -A table inside a [namespace](/management/namespace) is written as a dotted path: +A table inside a [namespace](/management/namespace) is written with its +schema -- the `$`-joined namespace path, not a dotted one -- before the +table name; see [Schema](/basics/catalog#schema) for why: -```sql -SELECT * FROM prod.events.clicks + +```sql SQL icon="database" +SELECT * FROM `prod$events`.clicks ``` + ## Reading the plan {#plans} `EXPLAIN` and `EXPLAIN ANALYZE` work as DataFusion defines them, and produce the same operators the SDK methods do: -```sql + +```sql SQL icon="database" EXPLAIN ANALYZE SELECT * FROM documents WHERE identifier < 1000 ``` + -See [Explain](/search/explain) and [Explain Analyze](/search/explain). +See [Explain](/basics/sql#inspect-a-query-plan) and [Explain Analyze](/basics/sql#analyze-a-query-plan). diff --git a/docs/web/sql/dql/subqueries.mdx b/docs/web/sql/dql/subqueries.mdx index 3c5b5d11d..fec9867fe 100644 --- a/docs/web/sql/dql/subqueries.mdx +++ b/docs/web/sql/dql/subqueries.mdx @@ -13,39 +13,47 @@ A subquery is allowed anywhere an expression or a relation is. ## As a relation {#derived} -```sql + +```sql SQL icon="database" SELECT * FROM ( SELECT category, count(*) AS n FROM documents GROUP BY category ) AS counts WHERE n > 100 ``` + A derived table needs an alias. Its result cannot be [sampled](/sql/dql/sampling); sample the table inside it instead: -```sql + +```sql SQL icon="database" SELECT * FROM (SELECT * FROM documents TABLESAMPLE (10)) d ``` + ## As a scalar {#scalar} -```sql + +```sql SQL icon="database" SELECT title, (SELECT count(*) FROM revisions r WHERE r.doc_id = d.id) AS revisions FROM documents AS d ``` + A scalar subquery returns one column and at most one row. No rows produces `NULL`; more than one row is an error. ## IN and EXISTS {#in-exists} -```sql + +```sql SQL icon="database" SELECT title FROM documents WHERE category_id IN (SELECT id FROM categories WHERE active) SELECT title FROM documents AS d WHERE EXISTS (SELECT 1 FROM revisions r WHERE r.doc_id = d.id) ``` + Use `EXISTS` to test whether a matching row exists and `IN` to test membership in a set of values. The optimizer may rewrite either into a join; inspect @@ -72,7 +80,9 @@ rewriting it as an explicit [join](/sql/dql/join) is the fix. A [CTE](/sql/dql/select#ctes) is a named subquery, and is usually more readable when the same subquery appears twice or when nesting gets deep. -```sql + +```sql SQL icon="database" WITH active AS (SELECT id FROM categories WHERE active) SELECT title FROM documents WHERE category_id IN (SELECT id FROM active) ``` + diff --git a/docs/web/sql/dql/vector-distance.mdx b/docs/web/sql/dql/vector-distance.mdx new file mode 100644 index 000000000..f6991308f --- /dev/null +++ b/docs/web/sql/dql/vector-distance.mdx @@ -0,0 +1,58 @@ +--- +title: "Vector distance functions" +sidebarTitle: "Vector Distance" +description: "cosine_distance, distance, exact_distance and inner_product: per-row vector distance, and the ORDER BY rewrite into vector search." +icon: ruler +keywords: ["distance", "cosine_distance", "exact_distance", "inner_product", "vector search", "sql", "scalar function"] +availability: + embedded: unavailable + enterprise: available +--- + +```text +cosine_distance distance exact_distance inner_product +``` + + +Distance functions can evaluate arrays per row. Some deployment versions also +recognize `ORDER BY distance(vector, query_vector) LIMIT k` over a table scan +and plan it as vector search, with indexed or flat search as appropriate. +Where available, `exact_distance` evaluates distance without that rewrite. +Confirm the functions supported by your deployment and inspect SQL +[`EXPLAIN`](/sql/dql/explain); the function name alone does not guarantee an +index-backed plan. See [SQL vector search](/basics/sql#no-vector-sql). + + +A third, optional argument is a comma-separated options string, and only +`distance` and `exact_distance` accept one; `cosine_distance` and +`inner_product` are plain two-argument functions. `metric` selects `l2` +(default, alias `euclidean`), `cosine`, or `dot`. `nprobes` and `use_index` +only affect `distance`, since it's the only one of the two that the +index-search rewrite applies to in the first place -- `exact_distance` is +never rewritten into an index search, so passing it `use_index`/`nprobes` +does nothing; use a plain `distance` call with `use_index=false` to force a +flat scan instead: + + +```sql SQL icon="database" +SELECT id FROM documents +ORDER BY distance(embedding, ARRAY[0.1, 0.2, 0.3], 'metric=cosine,nprobes=20') +LIMIT 10 + +-- Force a flat scan, bypassing the index: +SELECT id FROM documents +ORDER BY distance(embedding, ARRAY[0.1, 0.2, 0.3], 'use_index=false') +LIMIT 10 +``` + + +## What to read next {#next} + + + + Server-version requirements and the supported `ORDER BY` query forms. + + + Confirm whether a query planned as an index-backed vector search. + + diff --git a/docs/web/sql/dql/window.mdx b/docs/web/sql/dql/window.mdx index e90f601c6..522e3862f 100644 --- a/docs/web/sql/dql/window.mdx +++ b/docs/web/sql/dql/window.mdx @@ -13,48 +13,56 @@ A window function computes across a set of rows related to the current one and returns a value **per row**. That is the difference from [aggregation](/sql/dql/aggregation), which collapses the rows it covers. -```sql + +```sql SQL icon="database" SELECT title, score, row_number() OVER (PARTITION BY category ORDER BY score DESC) AS rank FROM documents ``` + Every row survives; each one gains its rank within its category. ## The window {#window} -```sql + +```sql SQL icon="database" OVER ( [PARTITION BY expr [, ...]] [ORDER BY expr [, ...]] [ROWS | RANGE BETWEEN frame_start AND frame_end] ) ``` + `PARTITION BY` splits the rows into independent groups. `ORDER BY` orders them inside each partition. Supply an ordering for useful ranks, and a stable tie-breaker when selecting one row from several equal values. The frame clause narrows the window further, which is how running totals and moving averages are expressed: -```sql + +```sql SQL icon="database" SELECT created_at, sum(amount) OVER (ORDER BY created_at ROWS UNBOUNDED PRECEDING) AS running_total, avg(amount) OVER (ORDER BY created_at ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS trailing_7 FROM transactions ``` + A `WINDOW` clause names a definition when several functions share one: -```sql + +```sql SQL icon="database" SELECT row_number() OVER w, lag(score) OVER w FROM documents WINDOW w AS (PARTITION BY category ORDER BY score DESC) ``` + ## The functions {#functions} @@ -82,13 +90,15 @@ window function. This is how running totals and moving averages are written. The common practical use: keep one row per key, chosen by some ordering. A window ranks, and an outer query filters: -```sql + +```sql SQL icon="database" WITH ranked AS ( SELECT *, row_number() OVER (PARTITION BY doc_id ORDER BY version DESC) AS rn FROM revisions ) SELECT * FROM ranked WHERE rn = 1 ``` + The outer query is needed because a window function cannot appear in `WHERE`: windows are computed after filtering, so the predicate would have nothing to @@ -97,5 +107,5 @@ read. Window functions sort within each partition, so on a large table they are among the more expensive things you can ask for. Filter first, and check the cost with -[Explain Analyze](/search/explain). +[Explain Analyze](/basics/sql#analyze-a-query-plan). diff --git a/docs/web/sql/functions.mdx b/docs/web/sql/functions.mdx deleted file mode 100644 index 9f6a25229..000000000 --- a/docs/web/sql/functions.mdx +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: "Functions" -sidebarTitle: "Functions" -description: "Where to find each kind of function, and the dialect version they come from." -icon: function -keywords: ["functions", "datafusion", "scalar", "aggregate", "window", "fts", "table function"] -availability: - embedded: unavailable - enterprise: available ---- - -LanceDB executes SQL with [Apache DataFusion](https://datafusion.apache.org), -currently **version 54**. The function set is DataFusion's default registration -plus what Lance adds. - -| | | -| --- | --- | -| [Scalar functions](/sql/scalar-functions) | per row: math, string, regex, date/time, array, struct, JSON | -| [Aggregate functions](/sql/dql/aggregation#functions) | per group: `count`, `sum`, statistical, approximate | -| [Window functions](/sql/dql/window#functions) | per window: ranking, offset, running aggregates | -| [Table functions](#table-functions) | produce a relation rather than a value | - - -Function availability is version-specific. DataFusion adds functions in most -releases, so one documented on `main` may not exist in 54. When a name is not -recognised, check it against the reference for that version before assuming a -bug. - - -## Table functions {#table-functions} - -A table function appears in `FROM` and produces a relation, which is what lets -it return columns a scalar function has nowhere to put. - -### `fts(table, query)` {#fts} - -Full-text search is a table function rather than a predicate, because it -produces relevance alongside the matching rows. The following query assumes -`my_docs` has `id` and `text` columns and a full-text index on `text`; see the -[setup example](/sql/dql/fts#setup): - -```sql -SELECT id, text, _score -FROM fts('my_docs', '{"match":{"column":"text","terms":"puppy"}}') -ORDER BY _score DESC -LIMIT 5 -``` - -The second argument is a string literal containing a JSON query object. A bare -query string such as `'puppy'` is rejected. Match, fuzzy, phrase, boolean, boost -and multi-match queries use this JSON encoding. - -Its schema contains the dataset's columns plus `_score`, so every stored -column is available in the result. Projections push into the scan. -Being a relation is also what makes it compose: join it, filter it, aggregate -over it. This join additionally requires `my_docs.category_id` and a -`categories` table with `id` and `name` columns: - -```sql -SELECT c.name, count(*) AS hits -FROM fts('my_docs', '{"match":{"column":"text","terms":"puppy"}}') AS m -JOIN categories AS c ON c.id = m.category_id -GROUP BY c.name -ORDER BY hits DESC -``` - -For a keyword test that needs no score, the -[`contains_tokens`](/sql/scalar-functions#contains-tokens) predicate is -index-accelerated and usable directly in `WHERE`. - -See [Full-Text Search](/sql/dql/fts) for the fuzzy, phrase, boolean, boost and -multi-match query forms. - -### `_score` {#score} - -A pseudo-column produced by `fts()`, carrying relevance for the row. It behaves -like any other column (order by it, filter on it, project it) and exists only -in a relation that came from `fts()`. See -[Data types](/sql/data-types#pseudo-columns). - -### `dedupe` and `duplicate_pairs` {#dedupe} - -Scan a vector column's [index](/indexing/vector-index) partitions for rows -closer than a distance threshold, without a full pairwise scan or a shuffle: - -```sql -SELECT * FROM duplicate_pairs('frames', 'vec', distance_threshold => 0.02) -SELECT * FROM dedupe('frames', 'vec', distance_threshold => 0.02) -``` - - -Earlier releases spelled these `vector_duplicate_pairs` and `vector_dedup`; -those names are rejected on current deployments. - - -`duplicate_pairs` returns every close pair it finds, in a fixed schema. -`dedupe` instead resolves overlapping pairs into duplicate groups and returns -one representative row **in the table's own schema** per group, so its result -composes directly into `CREATE TABLE ... AS` or -`CREATE MATERIALIZED VIEW ... AS`. See [`DEDUPE`](/sql/dql/dedupe) and -[`DUPLICATE_PAIRS`](/sql/dql/duplicate-pairs) for the full input and output -schema, resolution grouping, and partition sampling. - -### `generate_series` {#generate-series} - -```sql -SELECT * FROM generate_series(1, 10) -``` - -Rows from a range, useful for building a dense axis to left-join sparse data -onto. - -## What Lance accelerates {#accelerated} - -Two function families use an index rather than scanning, which is the difference -between a fast predicate and a slow one: - -| | Index used | -| --- | --- | -| [`contains_tokens`](/sql/scalar-functions#contains-tokens) | full-text index | -| [`json_get`, typed variants, `json_extract`](/sql/scalar-functions#json) | JSON scalar index | - -Confirm with [`EXPLAIN`](/sql/dql/explain): an accelerated predicate shows an -index node rather than a `LanceScan` followed by a filter. diff --git a/docs/web/sql/index.mdx b/docs/web/sql/index.mdx index 74561fca3..1d779ea1f 100644 --- a/docs/web/sql/index.mdx +++ b/docs/web/sql/index.mdx @@ -24,11 +24,13 @@ Use Python's `execute_query` or a Flight SQL client after configuring the [Enterprise connection](/basics/sql#sql-is-remote). TypeScript applications use a Flight SQL client for SQL queries. -```python + +```python Python icon="python" reader = db.execute_query("SELECT id, text FROM my_docs LIMIT 10") for batch in reader: print(batch) ``` + SQL results arrive as Arrow record batches. Iterating over the reader avoids collecting the entire result in application memory. See @@ -47,18 +49,16 @@ operations that have no SQL form, such as a merge insert. See | | | | --- | --- | -| [Database](/sql/ddl/database) | `ATTACH DATABASE` | -| [Namespace](/sql/ddl/namespace) | `CREATE SCHEMA`, `DROP SCHEMA` | +| [Database](/sql/ddl/database) | `CREATE`, `DESCRIBE`, `SHOW`, `ATTACH`, `DROP DATABASE` | +| [Namespace](/sql/ddl/namespace) | `CREATE`, `ALTER`, `DESCRIBE`, `SHOW`, `DROP SCHEMA`/`NAMESPACE` | | [Table](/sql/ddl/table) | `CREATE`, `DESCRIBE`, `ALTER`, `CLONE`, `DROP TABLE` | | [View](/sql/ddl/view) | `CREATE VIEW`, `DROP VIEW` | | [Materialized view](/sql/ddl/materialized-view) | `CREATE MATERIALIZED VIEW`, `SHOW MATERIALIZED VIEWS` | +| [Secret](/sql/ddl/secret) | `CREATE`, `ALTER`, `DESCRIBE`, `SHOW`, `DROP SECRET` | +| [Storage Integration](/sql/ddl/storage-integration) | `CREATE`, `DESCRIBE`, `SHOW`, `DROP STORAGE INTEGRATION` | | [Index](/sql/ddl/index) | `CREATE INDEX`, `DROP INDEX` | -| [Job](/sql/ddl/job) | `SHOW JOBS`, `SHOW ERRORS`, `PAUSE`/`RESUME`/`CANCEL JOB` | - -{/* -Draft for the Functions release. Add this row to the table above, after Index: | [Function](/sql/ddl/function) | `CREATE FUNCTION`, `SHOW FUNCTIONS`, `DROP FUNCTION` | -*/} +| [Job](/sql/ddl/job) | `SHOW JOBS`, `SHOW JOB EVENTS`, `DESCRIBE JOB`, `SHOW ERRORS`, `PAUSE`/`RESUME`/`CANCEL JOB` | ### DML {#dml} @@ -84,17 +84,11 @@ Draft for the Functions release. Add this row to the table above, after Index: | [Sampling](/sql/dql/sampling) | `TABLESAMPLE`, by rows or by fragments | | [Changes](/sql/dql/changes) | `CHANGES`: rows appended since an earlier version | | [Full-Text Search](/sql/dql/fts) | the `fts()` table function, and its query forms | +| [Operators](/sql/dql/operators) | comparison, logical, arithmetic, literals, precedence | +| [Functions](/sql/dql/functions) | where to find each kind, and table functions | +| [Scalar functions](/sql/dql/scalar-functions) | the per-row catalogue, and what Lance accelerates | | [Explain](/sql/dql/explain) | `EXPLAIN`, `EXPLAIN ANALYZE`, `EXPLAIN VERBOSE` | -### Expressions {#expressions} - -| | | -| --- | --- | -| [Operators](/sql/operators) | comparison, logical, arithmetic, literals, precedence | -| [Functions](/sql/functions) | where to find each kind, and table functions | -| [Scalar functions](/sql/scalar-functions) | the per-row catalogue, and what Lance accelerates | -| [Prepared statements](/sql/prepared-statements) | preparing through a Flight SQL client | - ## SQL limitations and alternatives {#cannot} | | | @@ -103,7 +97,7 @@ Draft for the Functions release. Add this row to the table above, after Index: | Merge insert | no SQL form: it needs a source relation and a per-match policy | | `information_schema` | not enabled, so `SHOW TABLES` and `SHOW COLUMNS` fail | | `COPY` | refused by recent deployment versions (see [Copy](/sql/dml/copy)) | -| `PREPARE` / `EXECUTE` | preparation is a [protocol feature](/sql/prepared-statements), not a statement | +| `PREPARE` / `EXECUTE` | preparation is a [protocol feature](/basics/sql#prepared-statements), not a statement | | Run on a local database | no engine to plan the statement | See [Limits](/basics/limits#sql) for the bounds these pages enforce. diff --git a/docs/web/sql/prepared-statements.mdx b/docs/web/sql/prepared-statements.mdx deleted file mode 100644 index cc0b1257e..000000000 --- a/docs/web/sql/prepared-statements.mdx +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: "Prepared statements" -sidebarTitle: "Prepared Statements" -description: "What a deployment does when a Flight SQL client prepares a statement or binds parameter values." -icon: bolt -keywords: ["prepared statement", "flight sql", "parameters", "bind"] -availability: - embedded: unavailable - enterprise: available ---- - -A Flight SQL client can prepare a statement before it runs it. A deployment -accepts that, but it keeps no plan between runs and does not accept parameter -values. - -## Prepare through a Flight SQL client {#protocol} - - -There is no SQL `PREPARE` / `EXECUTE` here. Preparation is part of the -**Arrow Flight SQL protocol**, so you reach it through your client rather than -by sending a statement. - - -That distinction matters when porting SQL from another engine: a script -containing `PREPARE name AS SELECT ...` will not run. - -## Prepare and execute {#flow} - -A Flight SQL client takes these steps, whatever it calls them: - -1. **Prepare:** send the SQL and get back a handle and the result schema. The - statement is parsed and planned at this point, so a syntax or name error - surfaces here rather than at execution. -2. **Execute:** run the handle and read the result. The deployment plans the - statement again each time it runs, so reusing a handle does not save - planning time. -3. **Close:** release the handle. - -## Parameters {#parameters} - -A deployment does not accept parameter values for a prepared statement. A -client that binds values to placeholders such as `$1` and `$2` gets a "not -implemented" error when it executes the statement. A statement with fixed, -trusted values written into it runs as usual: - -```sql -SELECT id, title FROM documents WHERE category = 'news' AND score > 0.5 -``` - -Do not put untrusted input, such as a value from a user or a request, directly -into the statement text. Quoting it does not protect the statement the way -binding a parameter would. - - -This limitation is specific to the Flight SQL protocol's `PREPARE`/bind step. -The Python SDK's `execute_query(sql, parameters=...)` binds parameter values -through a separate, LanceDB-specific mechanism -- see -[Parameters in SQL queries](/basics/sql#parameters). - - -## When to use prepared statements {#when} - -Prepare a statement when your client requires it, or to get a statement's -result schema and catch syntax and name errors without running it. Preparing -does not make a repeated statement faster. - -To give a reusable query a name, create a [view](/management/view). To store -its result for later queries, create a -[materialized view](/management/materialized-view). diff --git a/docs/web/sql/scalar-functions.mdx b/docs/web/sql/scalar-functions.mdx deleted file mode 100644 index 1af20bb96..000000000 --- a/docs/web/sql/scalar-functions.mdx +++ /dev/null @@ -1,252 +0,0 @@ ---- -title: "Scalar functions" -sidebarTitle: "Scalar Functions" -description: "The per-row function set: math, string, regex, date/time, array, struct, and what Lance adds." -icon: calculator -keywords: ["scalar functions", "string functions", "math functions", "regex", "array functions", "json"] -availability: - embedded: unavailable - enterprise: available ---- - -Functions that take a value and return a value, one row at a time. The set is -based on DataFusion's registration plus Lance and deployment-specific -functions. The names below are selected examples, not an exhaustive catalog -for every deployment. Availability depends on the deployed version and build. - -For per-group functions see [Aggregation](/sql/dql/aggregation); for per-window, -[Window functions](/sql/dql/window). - -## Math {#math} - -```text -abs ceil floor round trunc signum power sqrt cbrt exp -ln log log2 log10 factorial gcd lcm pi random nanvl -isnan iszero cot degrees radians to_degrees to_radians -sin cos tan asin acos atan atan2 -sinh cosh tanh asinh acosh atanh -``` - -## String {#string} - -```text -ascii bit_length btrim chr concat concat_ws contains ends_with -starts_with levenshtein lower upper ltrim rtrim octet_length -repeat replace split_part to_hex uuid -``` - -Unicode-aware variants: - -```text -character_length find_in_set initcap left right lpad rpad -reverse strpos substr substr_index substring translate -``` - - -For keyword matching on a text column, [`contains_tokens`](#contains-tokens) is -index-accelerated where `contains` and `LIKE` are not. - - -## Regular expressions {#regex} - -```text -regexp_count regexp_instr regexp_like regexp_match regexp_replace -``` - -## Date and time {#datetime} - -```text -current_date current_time date_bin date_part date_trunc -from_unixtime to_unixtime make_date make_time to_char -to_date to_time to_local_time -``` - -`date_bin` is the one worth knowing for analytics: it buckets timestamps into -fixed-width intervals, which is how you build a time series without a -self-join. - -```sql -SELECT date_bin(INTERVAL '1 hour', created_at) AS hour, count(*) -FROM events GROUP BY hour ORDER BY hour -``` - -## Arrays and maps {#arrays} - -```text -make_array array_has array_filter array_transform array_any_match -array_compact array_normalize array_slice arrays_zip cardinality -flatten range generate_series -``` - -```text -map map_keys map_values map_entries map_extract -``` - -Distance functions over arrays: - -```text -cosine_distance distance exact_distance inner_product -``` - - -Distance functions can evaluate arrays per row. Some deployment versions also -recognize `ORDER BY distance(vector, query_vector) LIMIT k` over a table scan -and plan it as vector search, with indexed or flat search as appropriate. -Where available, `exact_distance` evaluates distance without that rewrite. -Confirm the -functions supported by your deployment and inspect SQL -[`EXPLAIN`](/sql/dql/explain); the function name alone does not guarantee an -index-backed plan. See [SQL vector search](/basics/sql#no-vector-sql). - - -A third, optional argument is a comma-separated options string. `metric` -selects `l2` (default, alias `euclidean`), `cosine`, or `dot`; the -index-search rewrite also reads `nprobes` and `use_index`: - -```sql -SELECT id FROM documents -ORDER BY distance(embedding, ARRAY[0.1, 0.2, 0.3], 'metric=cosine,nprobes=20') -LIMIT 10 - --- Force a flat scan, bypassing the index: -SELECT id FROM documents -ORDER BY exact_distance(embedding, ARRAY[0.1, 0.2, 0.3], 'use_index=false') -LIMIT 10 -``` - -## Structs and fields {#structs} - -```text -named_struct get_field coalesce nullif nvl nvl2 greatest least -union_extract union_tag -``` - -## Crypto and encoding {#crypto} - -```text -digest md5 sha224 sha256 sha384 sha512 encode decode -``` - -## Type functions {#type} - -```text -arrow_cast arrow_try_cast arrow_typeof arrow_field arrow_metadata -with_metadata version -``` - -Use `arrow_typeof` to inspect the Arrow data type of a column or expression: - -```sql -SELECT arrow_typeof(vector) FROM documents LIMIT 1 --- FixedSizeList(Field { name: "item", data_type: Float32, .. }, 1536) -``` - -`arrow_cast` casts to an Arrow type by name, reaching types SQL has no spelling -for. See [Data types](/sql/data-types). - -## What Lance adds {#lance} - -These are registered by Lance on top of DataFusion's set. - -### `contains_tokens(column, tokens)` {#contains-tokens} - -```sql -SELECT * FROM my_docs WHERE contains_tokens(text, 'fox jumps dog') -``` - -True when the column contains **all** the tokens, split on whitespace and -punctuation. Equivalent to an `fts()` match query with fuzziness off, `AND` -semantics and the simple tokenizer. - -**Index-accelerated.** When the column has a full-text index that suits the -query, the planner uses it instead of scanning, which is the reason to prefer -it over `LIKE` for keyword tests. - -### `ivf_partition(vector, ...)` {#ivf-partition} - -```sql -SELECT ivf_partition(embedding, selection => 'random', count => 100, seed => 42) AS partition, - array_agg(id) AS ids -FROM documents -GROUP BY partition -``` - -Assigns each row to one of `count` IVF-style partitions over `vector`, using -the named arguments `selection` (partition-center strategy; `'random'` is -sampled with `seed`) and `seed`. Grouping by its result buckets rows by -vector proximity without building or querying a vector index — useful for -blocking a large table into comparable chunks, such as before a pairwise -similarity pass. - -### `blob_descriptor(column)` {#blob-descriptor} - -```sql -SELECT id, blob_descriptor(video) AS descriptor FROM videos -``` - -A [BlobV2](/management/table#managed-blobs) column's bytes are not fetched by -a plain `SELECT`: that already returns `large_binary`, the same as any other -binary column. `blob_descriptor` instead returns a small struct describing -where the payload lives, without reading it. Pass one row's descriptor to -the SDK's blob file reader to open that payload directly: - -```python -rows = db.execute_query("SELECT id, blob_descriptor(video) AS descriptor FROM videos").read_all().to_pylist() -with table.open_blob_file(rows[0]["descriptor"]) as reader: - payload = reader.read() -``` - -A descriptor is pinned to the table version it was read at: it keeps -resolving correctly even after the table is appended to and checked out to a -newer version. - -### JSON accessors {#json} - -| Function | Returns | -| --- | --- | -| `json_get(col, key)` | the value at `key`, still JSON | -| `json_get_string(col, key)` | `Utf8` | -| `json_get_int(col, key)` | `Int64` | -| `json_get_float(col, key)` | `Float64` | -| `json_get_bool(col, key)` | `Boolean` | -| `json_extract(col, path)` | `Utf8`: the value as JSON text, by path | -| `json_extract_with_type(col, path)` | a struct of the value as JSON and a type tag, by path | -| `json_exists(col, path)` | `Boolean` | -| `json_array_contains(col, value)` | `Boolean` | -| `json_array_length(col)` | length | - -`json_get` returns JSON, so a typed accessor can read a field inside it: - -```sql -SELECT * FROM events -WHERE json_get_string(json_get(data, 'user'), 'name') = 'Alice' -``` - -That works one level down. A `json_get` nested inside another `json_get` is -refused, so reach a deeper value with `json_extract` and a JSONPath instead. It -returns JSON text, so a string compares with its quotes: - -```sql -SELECT * FROM events -WHERE json_extract(data, '$.user.profile.name') = '"Alice"' -``` - -**`json_get`, its typed variants, and `json_extract` are index-accelerated** by a -JSON scalar index on the column. The rest evaluate per row. - -### Geospatial {#geo} - - -Lance defines `st_*` functions on GeoArrow, but they sit behind a build feature -**LanceDB does not ship**. Calling one returns an error naming the missing -feature rather than an unknown-function error, and the spatial index is gated -the same way. - - -## Additional scalar functions {#escape-hatch} - -SQL queries can call functions registered with the server, including functions -not listed on this page. Consult -[DataFusion's scalar function reference](https://datafusion.apache.org/user-guide/sql/scalar_functions.html) -for version 54. Functions documented for a newer DataFusion release may not be -available in your LanceDB Enterprise version. diff --git a/docs/web/static/assets/images/overview/lancedb-distributed.png b/docs/web/static/assets/images/overview/lancedb-distributed.png index 893e884d6..781946e64 100644 Binary files a/docs/web/static/assets/images/overview/lancedb-distributed.png and b/docs/web/static/assets/images/overview/lancedb-distributed.png differ diff --git a/docs/web/static/assets/images/overview/lancedb-suite.svg b/docs/web/static/assets/images/overview/lancedb-suite.svg deleted file mode 100644 index 676ba76cc..000000000 --- a/docs/web/static/assets/images/overview/lancedb-suite.svg +++ /dev/null @@ -1,92 +0,0 @@ - - LanceDB suite - LanceDB Embedded supports search. LanceDB Enterprise is a multimodal lakehouse for search, data exploration and curation, feature engineering, and training. Both are built on the Lance open lakehouse format for multimodal AI. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - LanceDB Embedded - Search - - - - - - - - - - - - - - - LanceDB Enterprise - Multimodal Lakehouse - - Search - Data exploration - & curation - Feature - engineering - Training - - - - - - - - - - Lance Open Lakehouse Format for Multimodal AI - - diff --git a/docs/web/tables/consistency.mdx b/docs/web/tables/consistency.mdx index 78aedb23f..fb285390e 100644 --- a/docs/web/tables/consistency.mdx +++ b/docs/web/tables/consistency.mdx @@ -27,8 +27,8 @@ In **LanceDB Embedded**, a table handle sees its own committed writes. By defaul not automatically check for changes made through other handles or processes. Use a read consistency interval or `checkout_latest()` to pick up those changes. -In **LanceDB Distributed** (provided by LanceDB Enterprise), readers use the -service's configured freshness policy. +In **LanceDB Enterprise**, readers use the service's configured freshness +policy. A connection can request fresher data. When a read must include a completed write, use a zero interval or call `checkout_latest()` after the write, with a client and server that support these freshness controls. @@ -38,13 +38,13 @@ client and server that support these freshness controls. Set `read_consistency_interval` when connecting. This controls when reads pick up newer table versions; it does not change how writes commit. -| Setting | Embedded | Distributed | +| Setting | Embedded | Enterprise | | --- | --- | --- | | **Unset** | Keep the open table version until explicitly refreshed or changed by that handle. | Use the service's configured freshness policy. | | **Zero** | Check for the latest committed version on every read. | Request the latest committed version on every read. | | **Non-zero interval** | Check for updates on a read once the interval since the last check has elapsed. | Request data no older than the interval allows; the service may return fresher data. | -`checkout_latest()` explicitly refreshes an Embedded table handle. On Distributed it +`checkout_latest()` explicitly refreshes an Embedded table handle. On Enterprise it asks subsequent reads on that handle to reflect data at least as recent as the refresh request. To read a fixed historical version instead, use [table versioning](/management/table#versioning). diff --git a/docs/web/tables/realtime-engine.mdx b/docs/web/tables/realtime-engine.mdx index b3ca31346..5c6983cc5 100644 --- a/docs/web/tables/realtime-engine.mdx +++ b/docs/web/tables/realtime-engine.mdx @@ -1,11 +1,11 @@ --- title: "Real Time engine (RTE)" -sidebarTitle: "Real Time Engine" +sidebarTitle: "Real Time Engine (RTE)" description: "Absorb small, frequent writes cheaply and make them queryable within milliseconds." icon: "bolt" -keywords: ["rte", "real time engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] +keywords: ["rte", "real time engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] availability: - embedded: unavailable + embedded: available enterprise: available --- @@ -20,23 +20,74 @@ It turns many small writes into a few large commits, and makes each write **searchable within milliseconds** of being acknowledged. It is enabled per table, and nothing about how you query that table changes. -## How it works {#how-it-works} +## The Lance MemWAL format {#memwal-format} -- **[Writes](/ingestion/realtime-write).** A `merge_insert` or `delete` lands in - an in-memory **memtable** and is acknowledged once it is durable in the - write-ahead log on object storage. -- **Flush and compaction.** Memtables freeze into **SSTables**, which background - jobs compact into the base table, catching its indexes up as they go. See - [Background jobs](/maintenance/background-jobs#wal). -- **[Reads](/search/realtime-read).** Every query runs against the base table - and the fresh tier (memtables and SSTables) in parallel. Fresh rows supersede - base rows with the same primary key, and the two are merged into one result. -- **Indexes stay fresh.** Vector, full-text, BTree, bitmap, and most other - scalar indexes are maintained on the memtable, so new rows are searchable - through the index as soon as they are written. +RTE is built on **MemWAL**, a log-structured-merge (LSM) format that Lance +itself defines -- the structure Enterprise serves is part of the open Lance +format, not a layer bolted on beside it. A table with RTE enabled is divided +into one or more **shards** (see [RTE writes](/ingestion/realtime-write#primary-key) +for enabling and sizing them), and each shard holds: + +- A **memtable**: the active, in-memory table for that shard's newest rows, + queryable as soon as a write lands in it. +- A **WAL buffer**: the same writes, batched and flushed to object storage + before a write is acknowledged, so an unflushed memtable is never the only + copy of a row. +- Its own **in-memory indexes** (vector, full-text, BTree, and other scalar + types), kept current as rows land, independently of the base table's + indexes. + +A write commits in two stages, both before it is acknowledged: the WAL buffer +append makes it durable, then it lands in the shard's memtable. When a +memtable crosses a size or row-count threshold, it freezes and flushes as an +immutable **SSTable** -- an ordinary Lance data file -- and a fresh memtable +takes over. [RTE Compaction](/enterprise/realtime-engine-compaction) +later folds SSTables into the base table, catching its indexes up as it goes. + +## WAL nodes serve MemWAL shards {#wal-nodes} + +This section describes LanceDB Enterprise's serving layer. LanceDB Embedded +runs the same MemWAL mechanics directly against the local dataset, in one +process -- there is no separate node to route to or scale; see +[RTE writes](/ingestion/realtime-write#getting-started) and +[RTE reads](/search/realtime-read#embedded) for what that looks like. + +RTE's Enterprise serving layer is a dedicated component, separate from the +[query nodes and plan executors](/enterprise/distributed-search) +that serve ordinary queries: + +| Component | Responsibility | +| --- | --- | +| WAL node | Own one or more tables' shards; append their WAL, maintain their memtables and in-memory indexes, and serve reads and writes against them. | + +A query node routes every request for an RTE-enabled table -- reads and +writes alike -- to the WAL node that owns that table, by a consistent hash of +the database and table name. WAL node pods share nothing but the underlying +object storage; no pod talks to another one directly. + +One WAL node owns every shard of a given table. Splitting a table into more +shards parallelizes that table's own writes into more independent append +streams on the node that already owns it; adding more WAL node replicas +instead spreads ownership of more *tables* across more pods. Shard a large +table to raise its own ingest ceiling, and add WAL node replicas to raise the +cluster's overall capacity. + +If a WAL node pod is replaced, its successor must claim ownership of a shard, +by a version number that only ever increases, before writing to it -- so two +pods are never both appending to the same shard's WAL at once. + +## Reading a real time table {#reads} + +Every query runs against the base table and the fresh tier -- every shard's +memtable and not-yet-compacted SSTables -- in parallel. Fresh rows supersede +base rows with the same primary key, and the two are merged into one result. +See [RTE reads](/search/realtime-read) for what this means for query +results. ## Next steps {#next-steps} -- [Real Time writes](/ingestion/realtime-write) — enable RTE and write to a table -- [Real Time reads](/search/realtime-read) — query an RTE table and its performance -- [Background jobs](/maintenance/background-jobs#wal) +- [RTE writes](/ingestion/realtime-write) — enable RTE and write to a table +- [RTE reads](/search/realtime-read) — query an RTE table +- [Distributed RTE Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales writes +- [Distributed RTE Read](/enterprise/distributed-real-time-read) — how Enterprise combines reads across machines +- [RTE Compaction](/enterprise/realtime-engine-compaction) — how Enterprise folds shards into the base table diff --git a/docs/web/tools/cli.mdx b/docs/web/tools/cli.mdx index 97b058bd9..2d5104322 100644 --- a/docs/web/tools/cli.mdx +++ b/docs/web/tools/cli.mdx @@ -1,6 +1,6 @@ --- title: "LanceDB CLI" -sidebarTitle: "Command line" +sidebarTitle: "CLI" description: "Connect to LanceDB, run SQL, and manage connection profiles with the lancedb command-line client." icon: terminal keywords: ["cli", "command line", "sql", "profiles", "authentication"] @@ -12,19 +12,74 @@ statement, or execute a SQL file. SQL requires a running deployment with an ## Install -With Rust and Git installed, build the CLI from the LanceDB repository: +Download a CLI archive and `SHA256SUMS` from the +[LanceDB releases page](https://github.com/lancedb/lancedb/releases). The CLI +shares the SDK release version, including beta versions. + +| Platform | Target | Requirements | +| --- | --- | --- | +| Linux x86_64 | `x86_64-unknown-linux-gnu` | glibc 2.28 or newer; Haswell-compatible CPU with AVX2, FMA, and F16C | +| Linux ARM64 | `aarch64-unknown-linux-gnu` | glibc 2.28 or newer | +| macOS Apple Silicon | `aarch64-apple-darwin` | macOS 14 or newer | + +Set the version and target to match your chosen release and platform: ```sh +CLI_VERSION=X.Y.Z # Replace with the release version, for example X.Y.Z-beta.N +CLI_TARGET=aarch64-apple-darwin +CLI_STEM="lancedb-v${CLI_VERSION}-${CLI_TARGET}" +CLI_RELEASE_URL="https://github.com/lancedb/lancedb/releases/download/v${CLI_VERSION}" +curl -fLO "${CLI_RELEASE_URL}/${CLI_STEM}.tar.gz" +curl -fLO "${CLI_RELEASE_URL}/SHA256SUMS" +awk -v archive="${CLI_STEM}.tar.gz" '$2 == archive' SHA256SUMS > "${CLI_STEM}.sha256" +``` + +Verify the downloaded archive before extracting it. On Linux: + +```sh +sha256sum --check "${CLI_STEM}.sha256" +``` + +On macOS: + +```sh +shasum -a 256 --check "${CLI_STEM}.sha256" +``` + +After the checksum passes, install the executable into a directory on your `PATH`: + +```sh +tar -xzf "${CLI_STEM}.tar.gz" +mkdir -p "$HOME/.local/bin" +install -m 755 "${CLI_STEM}/lancedb" "$HOME/.local/bin/lancedb" +export PATH="$HOME/.local/bin:$PATH" +lancedb --version +``` + +Add `$HOME/.local/bin` to your shell's `PATH` configuration to use it in future +sessions. Each archive also contains the license and Rust third-party notices. + +### Build from source + +With Rust and Git installed, build the CLI from the LanceDB repository. Check +out a release tag to build that version: + + +```bash Bash icon="terminal" git clone https://github.com/lancedb/lancedb.git cd lancedb +git checkout vX.Y.Z # Replace with the desired release tag cargo install --locked --path rust/lancedb/cli ``` + Check the available options: -```sh + +```bash Bash icon="terminal" lancedb --help ``` + ## Connect to a deployment @@ -32,12 +87,14 @@ Get the Flight SQL endpoint, HTTP API endpoint, database name, and credentials from your deployment administrator. Create a named profile to save the connection settings: -```sh + +```bash Bash icon="terminal" lancedb profile create production \ --sql-server-url grpcs://sql.example.com:10025 \ --http-server-url https://query.example.com \ --database analytics ``` + The SQL endpoint executes statements. The HTTP endpoint supports shell commands that inspect table and index metadata. Replace both example URLs with the @@ -45,20 +102,24 @@ endpoints for your deployment; they may use different hosts or ports. For API-key authentication, set the credential in your environment: -```sh + +```bash Bash icon="terminal" export LANCEDB_API_KEY="YOUR_API_KEY" lancedb --profile production ``` + Use `grpcs://` or `https://` for a TLS-protected SQL connection. A bare `host:port` or a `grpc://` address selects a plaintext connection. ### Set the default profile -```sh + +```bash Bash icon="terminal" lancedb profile set production lancedb ``` + Running `lancedb` opens the SQL shell when the default profile has a Flight SQL @@ -69,9 +130,11 @@ guidance. Command and file execution also require a configured endpoint. To connect to an existing server on localhost, explicitly select the built-in local profile: -```sh + +```bash Bash icon="terminal" lancedb --profile local ``` + This profile uses Flight SQL on port `10025` and HTTP on port `10024`. @@ -79,23 +142,29 @@ This profile uses Flight SQL on port `10025` and HTTP on port `10024`. Execute a statement and exit: -```sh + +```bash Bash icon="terminal" lancedb --profile production --command 'SELECT 1' --format json ``` + To execute a file, separate its statements with semicolons. For example, save the following as `queries.sql`: -```sql + +```sql queries.sql icon="database" SELECT COUNT(*) FROM documents; SELECT id, text FROM documents LIMIT 10; ``` + Run the file with: -```sh + +```bash Bash icon="terminal" lancedb --profile production --file queries.sql ``` + Quoted strings and comments in SQL files are preserved when statements are split. `--command` and `--file` are mutually exclusive. @@ -111,9 +180,11 @@ For query results, `--format` accepts the following values: | `json` | A JSON array of rows | | `ndjson` | One JSON row per line | -```sh + +```bash Bash icon="terminal" lancedb --profile production --command 'SELECT id FROM documents' --format csv ``` + ## Use the SQL shell @@ -137,11 +208,13 @@ Large interactive results use a pager. Set `NO_PAGER=1` to disable paging. ### Inspect jobs with SQL -```sh + +```bash Bash icon="terminal" lancedb --profile production --command 'SHOW JOBS' lancedb --profile production --command "SHOW ERRORS ON documents FOR JOB 'JOB_ID'" lancedb --profile production --command "CANCEL JOB 'JOB_ID'" ``` + See the [job SQL reference](/sql/ddl/job) for syntax and deployment requirements, and the [SQL reference](/sql) for other supported statements. @@ -151,12 +224,14 @@ and the [SQL reference](/sql) for other supported statements. Profiles are stored in `~/.lancedb/config.toml`. The CLI reuses existing Enterprise profiles and cached OAuth sessions. -```sh + +```bash Bash icon="terminal" lancedb profile list lancedb profile show production lancedb profile edit production --database staging lancedb profile delete production ``` + Use `lancedb profile create NAME` without connection flags for interactive setup. For a single SQL invocation, flags such as `--database` and @@ -184,12 +259,14 @@ Choose one authentication method per profile. An OAuth profile cannot also contain `api_key` or `oidc_access_token_file`. Environment credentials override the profile, so clear API-key overrides before connecting with OAuth: -```sh + +```bash Bash icon="terminal" unset LANCEDB_API_KEY lancedb auth login --profile production lancedb auth status --profile production lancedb --profile production ``` + `auth login` follows the profile's OAuth flow. Browser and device-code sessions cache refresh tokens for later commands. Use `lancedb auth logout --profile @@ -202,16 +279,20 @@ available authentication methods. To trust a private certificate authority, pass its PEM certificate: -```sh + +```bash Bash icon="terminal" lancedb --profile production --ca-cert /path/to/ca.pem ``` + If the server requires mutual TLS, supply both a client certificate and its PKCS#8 private key. Save these settings in the profile with: -```sh + +```bash Bash icon="terminal" lancedb profile edit production \ --ca-cert /path/to/ca.pem \ --client-cert /path/to/client.pem \ --client-key /path/to/client-key.pem ``` + diff --git a/docs/web/training/checkpointing.mdx b/docs/web/training/checkpointing.mdx new file mode 100644 index 000000000..119601d98 --- /dev/null +++ b/docs/web/training/checkpointing.mdx @@ -0,0 +1,106 @@ +--- +title: "Checkpointing" +sidebarTitle: "Checkpointing" +description: "Save StreamingDataset's read position alongside your model, so a failed run can pick back up." +icon: floppy-disk +availability: + embedded: available + enterprise: available +--- + +[`StreamingDataset`](/training/data-loading) provides checkpointing in case your model training fails partway through a run. Use `StreamingDataset.state_dict()` to capture the current number of samples consumed from each split in a Python dictionary, save it alongside your model weights, and `load_state_dict()` to restore the last saved position -- see [Resuming](/training/resuming) for the load side. + +This page assumes the `rank`, `world_size`, `num_splits` and `shuffle_seed` +terminology from [Distributed Training](/training/distributed-training#parallelism-and-elasticity). + +A stored `StreamingDataset` state reflects only round-robin cycles that have been completed across all splits; samples completed partway through a cycle at the time of saving can be replayed. To ensure efficient saving, make sure `global_batch_size` is a multiple of `num_splits`, as in the example below. + + +```py Python icon=Python +import torch +from lancedb.streaming import StreamingDataset + +global_batch_size = 48 # one sample per split in each global step +batch_size = global_batch_size // world_size + +dataset = StreamingDataset( + table, + num_splits=48, + shuffle_seed=42, + epoch=current_epoch, + rank=rank, + world_size=world_size, +) +dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=batch_size, + num_workers=0, +) + +for step, batch in enumerate(dataloader): + train_step(batch) + + if (step + 1) % checkpoint_interval == 0: + torch.save( + {"model": model.state_dict(), "dataset": dataset.state_dict()}, + f"checkpoint_{step + 1}.pt", + ) +``` + + +## Checkpointing with Multiple DataLoader Workers {#checkpointing-with-multiple-dataloader-workers} + +Python's built-in `torch.utils.data.DataLoader` produces a safe checkpoint when `num_workers = 0`. With `num_workers > 0`, calling `state_dict()` often raises `RuntimeError`. In this case, use `StreamingDataLoader` for multi-worker prefetch and exact resumability. It carries a state snapshot +alongside every internal batch and commits it to the parent `StreamingDataset` only when that batch is returned to the +trainer. The trainer receives the same collated batch it would receive from a standard `DataLoader`. + + +```py Python icon=Python +from lancedb.streaming import StreamingDataset, StreamingDataLoader + +dataset = StreamingDataset( + table, + num_splits=48, + shuffle_seed=42, + epoch=current_epoch, + rank=rank, + world_size=world_size, +) +dataloader = StreamingDataLoader( + dataset, + batch_size=batch_size, + num_workers=4, +) + +for step, batch in enumerate(dataloader): + train_step(batch) + + if (step + 1) % checkpoint_interval == 0: + torch.save( + {"model": model.state_dict(), "dataset": dataset.state_dict()}, + f"checkpoint_{step + 1}.pt", + ) +``` + + +`StreamingDataLoader` accepts the same arguments as `torch.utils.data.DataLoader`, with a few restrictions: + +- `dataset` must be a `StreamingDataset` (subclasses that override `__iter__` are not supported). +- `in_order = True` is required so that consumer-committed checkpoints stay deterministic. +- `persistent_workers = True` is not supported, because prefetched worker copies cannot be restored from parent-committed state. +- `drop_last = True` is not supported, because incomplete tails discarded by worker replicas cannot be checkpointed topology-independently. + +With more than one worker, call `state_dict()` at a complete logical step boundary where every split assigned to the +rank has the same consumed-sample count. Calling it mid-step raises `RuntimeError` asking you to consume more batches +first. + +## Next steps {#next} + + + + Load a saved checkpoint back, on the same or a different topology. + + + The rank, world size and split terminology checkpointing builds on. + + diff --git a/docs/web/training/data-loading.mdx b/docs/web/training/data-loading.mdx index 47a3a6703..1e4989cf9 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -12,7 +12,6 @@ Advanced data loading scenarios can be handled by the `StreamingDataset`. This o ```py Python icon=Python -import lancedb import torch from lancedb.streaming import StreamingDataset @@ -227,7 +226,6 @@ or a secrets manager: ```py Python icon=Python -import lancedb import torch from lancedb.util import tbl_to_tensor @@ -262,14 +260,15 @@ inside each worker instead. Set it in the shell before starting the Python program, then replace the database URI, region and endpoint in the factory with your deployment details: -```shell + +```bash Bash icon="terminal" export LANCEDB_API_KEY="your-api-key" ``` + ```py Python icon=Python import os -import lancedb import torch from lancedb.permutation import Permutation @@ -296,60 +295,22 @@ dataloader = torch.utils.data.DataLoader( ``` -## Observability {#observability} - -Optimizing data loader performance can be tricky, as runtime bottlenecks are often difficult to locate across various stages of the I/O and CPU pipelines. To help distinguish bottlenecks, `StreamingDataset` exposes several pipeline counters: `raw_queue_depth` shows the number of loaded rows waiting to be transformed, -and `prefetch_queue_depth` is the number of transformed rows ready to be consumed. `unscanned_rows` and -`consumed_rows` show how far the current iterator has progressed. - -If the `prefetch_queue_depth` is consistently zero but the `raw_queue_depth` is not, then you likely have a CPU -transformation bottleneck. You should investigate GIL bottlenecks or look for ways to optimize your transformation. -This can often be done by batching the compute work. If both `prefetch_queue_depth` and `raw_queue_depth` are -consistently zero while the consumer is waiting, I/O is the likely bottleneck. A larger read batch size or clumped -shuffling could help. - - -```py Python icon=Python -import threading, time - -ds = StreamingDataset(table, shuffle_seed=42) - -def log_pipeline_health(): - while True: - print( - f"unscanned={ds.unscanned_rows} " - f"raw={ds.raw_queue_depth} " - f"cooked={ds.prefetch_queue_depth} " - f"consumed={ds.consumed_rows}" - ) - time.sleep(1.0) - -monitor = threading.Thread(target=log_pipeline_health, daemon=True) -monitor.start() - -for sample in ds: - train_step(sample) - -print( - f"bytes loaded: {ds.bytes_loaded} " - f"fetch time: {ds.fetch_time:.2f}s " - f"transform time: {ds.transform_time:.2f}s" -) -``` - - -`bytes_loaded` measures raw Arrow buffer bytes before transformation. `bytes_loaded`, `fetch_time`, and `transform_time` -are cumulative across iterations of the same dataset instance; because work runs concurrently, the summed stage times -can exceed wall-clock time. The queue depths report rows currently waiting in the pipeline, and the progress counters -reflect the latest iterator snapshot. - ## Next steps {#next} The lower-level row ordering StreamingDataset is built on. + + Pipeline counters for diagnosing loader bottlenecks. + - Multi-GPU sharding, elastic determinism, and checkpointing. + Multi-GPU sharding and elastic determinism. + + + Save progress so a failed run can pick back up. + + + How an Enterprise connection speeds up repeated epochs. diff --git a/docs/web/training/distributed-training.mdx b/docs/web/training/distributed-training.mdx index 549539591..12fecda43 100644 --- a/docs/web/training/distributed-training.mdx +++ b/docs/web/training/distributed-training.mdx @@ -1,7 +1,7 @@ --- title: "Distributed Training" sidebarTitle: "Distributed Training" -description: "Shard StreamingDataset across ranks and workers, with elastic determinism and checkpointing." +description: "Shard StreamingDataset across ranks and workers, with elastic determinism across topologies." icon: server availability: embedded: available @@ -23,7 +23,7 @@ processed, the GPUs exchange weights and the next batch is loaded. We fix the fo Other concepts, such as read batch size and `num_workers`, are introduced in [PyTorch Data Loader](/training/data-loading). -## Parallelism & Elasticity {#parallelism-&-elasticity} +## Parallelism & Elasticity {#parallelism-and-elasticity} When loading data, `StreamingDataset` partitions the source dataset among disjoint parallel threads called **splits**. Each rank is allocated a contiguous group of splits, and each DataLoader worker associated to a rank gets a contiguous subgroup of its rank's splits. @@ -52,6 +52,7 @@ For example, to switch between $8$ and $6$ GPUs, use a common multiple such as $ ```py Python icon=Python import torch.distributed as dist +from lancedb.streaming import StreamingDataset dist.init_process_group("nccl") rank = dist.get_rank() @@ -73,144 +74,13 @@ for sample in ds: ``` -## Checkpointing {#checkpointing} +## Next steps {#next} -`StreamingDataset` provides checkpointing in case your model training fails partway through a run. Use `StreamingDataset.state_dict()` to capture the current number of samples consumed from each split in a Python dictionary, and `load_state_dict()` to restore the last saved position. - -A stored `StreamingDataset` state reflects only round-robin cycles that have been completed across all splits; samples completed partway through a cycle at the time of saving can be replayed. To ensure efficient saving, make sure `global_batch_size` is a multiple of `num_splits`, as in the example below. - - -```py Python icon=Python -import torch - -global_batch_size = 48 # one sample per split in each global step -batch_size = global_batch_size // world_size - -dataset = StreamingDataset( - table, - num_splits=48, - shuffle_seed=42, - epoch=current_epoch, - rank=rank, - world_size=world_size, -) -dataloader = torch.utils.data.DataLoader( - dataset, - batch_size=batch_size, - num_workers=0, -) - -for step, batch in enumerate(dataloader): - train_step(batch) - - if (step + 1) % checkpoint_interval == 0: - torch.save( - {"model": model.state_dict(), "dataset": dataset.state_dict()}, - f"checkpoint_{step + 1}.pt", - ) - -# --- resuming after a crash --- -checkpoint = torch.load("checkpoint_100.pt") -model.load_state_dict(checkpoint["model"]) - -dataset_state = checkpoint["dataset"] -dataset = StreamingDataset( - table, - num_splits=dataset_state["num_splits"], - shuffle_seed=dataset_state["shuffle_seed"], - epoch=dataset_state["epoch"], - rank=rank, - world_size=world_size, # may differ from the run that saved the checkpoint -) -dataset.load_state_dict(dataset_state) -dataloader = torch.utils.data.DataLoader( - dataset, - batch_size=global_batch_size // world_size, - num_workers=0, -) - -for batch in dataloader: - train_step(batch) -``` - - -`load_state_dict()` rejects a checkpoint whose `num_splits` or `shuffle_seed` differs from the new dataset. For an -exact resume, also use the same table snapshot, `epoch`, `shuffle`, `filter`, and other data-selection settings. The -`world_size` and number of DataLoader workers may change as long as the split and batch-size divisibility constraints -still hold. - -### Checkpointing with Multiple DataLoader Workers {#checkpointing-with-multiple-dataloader-workers} - -Python's built-in `torch.utils.data.DataLoader` produces a safe checkpoint when `num_workers = 0`. With `num_workers > 0`, calling `state_dict()` often raises `RuntimeError`. In this case, use `StreamingDataLoader` for multi-worker prefetch and exact resumability. It carries a state snapshot -alongside every internal batch and commits it to the parent `StreamingDataset` only when that batch is returned to the -trainer. The trainer receives the same collated batch it would receive from a standard `DataLoader`. - - -```py Python icon=Python -from lancedb.streaming import StreamingDataset, StreamingDataLoader - -dataset = StreamingDataset( - table, - num_splits=48, - shuffle_seed=42, - epoch=current_epoch, - rank=rank, - world_size=world_size, -) -dataloader = StreamingDataLoader( - dataset, - batch_size=batch_size, - num_workers=4, -) - -for step, batch in enumerate(dataloader): - train_step(batch) - - if (step + 1) % checkpoint_interval == 0: - torch.save( - {"model": model.state_dict(), "dataset": dataset.state_dict()}, - f"checkpoint_{step + 1}.pt", - ) -``` - - -`StreamingDataLoader` accepts the same arguments as `torch.utils.data.DataLoader`, with a few restrictions: - -- `dataset` must be a `StreamingDataset` (subclasses that override `__iter__` are not supported). -- `in_order = True` is required so that consumer-committed checkpoints stay deterministic. -- `persistent_workers = True` is not supported, because prefetched worker copies cannot be restored from parent-committed state. -- `drop_last = True` is not supported, because incomplete tails discarded by worker replicas cannot be checkpointed topology-independently. - -With more than one worker, call `state_dict()` at a complete logical step boundary where every split assigned to the -rank has the same consumed-sample count. Calling it mid-step raises `RuntimeError` asking you to consume more batches -first. - -### Resuming Across Different Topologies {#resuming-across-different-topologies} - -When training across ranks, each rank owns its own subset of splits and only its own splits have exact progress. To -resume on a different `world_size`, collect the `state_dict()` from every rank of the previous run and merge them with -`StreamingDataset.merge_state_dicts` before calling `load_state_dict()` on the new run. The merge is topology-agnostic: -pass the full list of per-rank states in, and hand the identical merged dict to every rank of the resumed job, -regardless of whether the topology grew, shrank, or stayed the same. - - -```py Python icon=Python -# On each rank of the previous run: -state = dataset.state_dict() -# ...gather `state` from every rank into a single list `states` (for example -# via torch.distributed all-gather or by saving one file per rank). - -merged = StreamingDataset.merge_state_dicts(states) - -# On each rank of the resumed run (world_size may differ): -dataset = StreamingDataset( - table, - num_splits=merged["num_splits"], - shuffle_seed=merged["shuffle_seed"], - epoch=merged["epoch"], - rank=rank, - world_size=new_world_size, -) -dataset.load_state_dict(merged) -``` - + + + Save progress so a failed run can pick back up. + + + Load a saved checkpoint back, on the same or a different topology. + + diff --git a/docs/web/training/object-detection.mdx b/docs/web/training/object-detection.mdx index 6e9213a57..6dd0da9c4 100644 --- a/docs/web/training/object-detection.mdx +++ b/docs/web/training/object-detection.mdx @@ -48,7 +48,8 @@ Each curated slice becomes a [Geneva materialized view](/geneva/jobs/materialize The source table holds raw image bytes alongside structured annotations. Bounding boxes are stored as a parallel list (one element per box) rather than a nested struct so they remain directly queryable with SQL. -```py Python icon=Python + +```python Python icon="python" import pyarrow as pa BDD_SCHEMA = pa.schema([ @@ -69,6 +70,7 @@ BDD_SCHEMA = pa.schema([ pa.field("ann_occluded", pa.list_(pa.bool_())), ]) ``` + Ingestion streams `pa.RecordBatch`es of raw frames + annotations directly into a Lance table, with no intermediate preprocessing job. The table can live on local disk, S3, GCS, or Azure; everything downstream (backfills, views, the training loader) opens it in place via `lancedb.connect("s3://...")` with no local copy step. @@ -76,7 +78,8 @@ Ingestion streams `pa.RecordBatch`es of raw frames + annotations directly into a Curation signals are added as columns on the same table using [Geneva backfilling](/geneva/jobs/backfilling). Backfills are incremental and checkpointed: re-running the command after new footage arrives only computes the new rows. -```py Python icon=Python + +```python Python icon="python" import pyarrow as pa from geneva.transformer import udf @@ -99,10 +102,12 @@ class PersonBboxAreaPct: # lazy model load — runs once per Ray worker, then reused ... ``` + Run the backfill against the live table: -```py Python icon=Python + +```python Python icon="python" import geneva gconn = geneva.connect("data/bdd100k/lancedb") @@ -115,6 +120,7 @@ with gconn.local_ray_context(): tbl.backfill("has_rider") tbl.backfill("person_bbox_area_pct") ``` + Because the curation features are flat scalar columns on the same table, all four retrieval modes (SQL, full-text search, vector search, and SQL-filtered vector search) work directly without joins or exports. See [Geneva backfilling](/geneva/jobs/backfilling) for how a backfill fills only the rows that lack values. @@ -124,7 +130,8 @@ Because the curation features are flat scalar columns on the same table, all fou A training split is a named SQL filter, not a CSV manifest. Each view stays in sync with the source table and bumps its `version` on every refresh. That version is the link between a checkpoint and the exact data that produced it. -```py Python icon=Python + +```python Python icon="python" import geneva gconn = geneva.connect("data/bdd100k/lancedb") @@ -152,13 +159,14 @@ with gconn.local_ray_context(): mv.refresh() print(f"[{name}] {mv.count_rows()} rows (version {mv.version})") ``` + ## 4\. PyTorch DataLoader via the Permutation API {#4-pytorch-dataloader-via-the-permutation-api} The training script doesn't know about the filter: it opens a view by name and reads through the [`Permutation`](/training/permutation) API. Each DataLoader worker reopens its own connection lazily, reads Arrow batches directly from Lance (zero-copy, no intermediate file format), and the collate function decodes the whole batch in one pass. `Permutation` provides random-access indexing over the table, so shuffling is a cheap pointer rewrite rather than a full-dataset shuffle on disk. -```py Python icon=Python -import lancedb + +```python Python icon="python" import torch import torchvision.io as tio from lancedb.permutation import Permutation @@ -193,10 +201,12 @@ class LanceDetectionDataset(torch.utils.data.Dataset): self._ensure_open() return self._perm.__getitems__(indices) ``` + The collate function decodes JPEG bytes and converts BDD category strings into COCO class IDs (so the comparison against the pretrained checkpoint is valid): -```py Python icon=Python + +```python Python icon="python" BDD_LABEL_MAP = { "person": 1, "rider": 1, "bicycle": 2, "car": 3, "motorcycle": 4, "bus": 6, "train": 7, "truck": 8, "traffic light": 10, @@ -226,10 +236,12 @@ def detection_collate(batch): }) return images, targets ``` + Wire it into a standard `torch.utils.data.DataLoader`: -```py Python icon=Python + +```python Python icon="python" def make_loader(uri, table_name, batch_size=64, num_workers=8, shuffle=False): dataset = LanceDetectionDataset(uri, table_name) sampler = torch.utils.data.RandomSampler(dataset) if shuffle else None @@ -244,6 +256,7 @@ def make_loader(uri, table_name, batch_size=64, num_workers=8, shuffle=False): multiprocessing_context="spawn" if num_workers > 0 else None, ) ``` + `with_format("arrow")` keeps batches as zero-copy `pa.RecordBatch`es: no per-row Python boxing, no pickling between worker and main. Each DataLoader worker reopens its own `Permutation` after fork (the Rust async handle is cleared in `__getstate__`), so reads scale with `num_workers` and stream straight from the underlying object store. JPEG decode overlaps with GPU compute via `pin_memory` + `prefetch_factor`, which is what keeps the loader from becoming the bottleneck on a fast GPU. @@ -253,7 +266,8 @@ def make_loader(uri, table_name, batch_size=64, num_workers=8, shuffle=False): The training loop is plain PyTorch: the Lance integration ends at the loader. Mixed precision is enabled on CUDA for ~2× speedup on Ampere GPUs. -```py Python icon=Python + +```python Python icon="python" import time import torch from torchvision.models.detection import ( @@ -309,12 +323,14 @@ for epoch in range(1, 11): scheduler.step() print(f"epoch {epoch} ({time.time() - t0:.1f}s)") ``` + ## 6\. Pin the checkpoint to a data version {#6-pin-the-checkpoint-to-a-data-version} Every Lance table, including a materialized view, exposes a monotonically increasing `version`. Logging it next to the weights gives a permanent, deterministic link between a checkpoint and the exact data snapshot that produced it. -```py Python icon=Python + +```python Python icon="python" import json from pathlib import Path @@ -330,19 +346,23 @@ with open(out / "metadata.json", "w") as f: "row_count": len(train_tbl), }, f, indent=2) ``` + To reproduce a run, [time-travel](/management/table#versioning) the view to the recorded version before opening the loader: -```py Python icon=Python + +```python Python icon="python" tbl = lancedb.connect("data/bdd100k/lancedb").open_table("bdd100k_rider_train") tbl.checkout(version=7) # exact snapshot the checkpoint was trained on ``` + ## 7\. Continuous updates {#7-continuous-updates} When new footage arrives, the same three calls update every downstream view (no view definitions change, no training-script edits required): -```py Python icon=Python + +```python Python icon="python" # 1. ingest the new footage into the source table table.add(new_record_batches) @@ -360,6 +380,7 @@ for view_name in gconn.table_names(): mv.refresh() print(f"[{view_name}] {before} → {mv.count_rows()} rows (version {mv.version})") ``` + The next training run picks up the new data automatically and pins itself to the new `version`. diff --git a/docs/web/training/observability.mdx b/docs/web/training/observability.mdx new file mode 100644 index 000000000..d0907dd4f --- /dev/null +++ b/docs/web/training/observability.mdx @@ -0,0 +1,67 @@ +--- +title: "Observability" +sidebarTitle: "Observability" +description: "Pipeline counters for diagnosing StreamingDataset bottlenecks." +icon: gauge +availability: + embedded: available + enterprise: available +--- + +Optimizing data loader performance can be tricky, as runtime bottlenecks are often difficult to locate across various stages of the I/O and CPU pipelines. To help distinguish bottlenecks, [`StreamingDataset`](/training/data-loading) exposes several pipeline counters: `raw_queue_depth` shows the number of loaded rows waiting to be transformed, +and `prefetch_queue_depth` is the number of transformed rows ready to be consumed. `unscanned_rows` and +`consumed_rows` show how far the current iterator has progressed. + +If the `prefetch_queue_depth` is consistently zero but the `raw_queue_depth` is not, then you likely have a CPU +transformation bottleneck. You should investigate GIL bottlenecks or look for ways to optimize your transformation. +This can often be done by batching the compute work. If both `prefetch_queue_depth` and `raw_queue_depth` are +consistently zero while the consumer is waiting, I/O is the likely bottleneck. A larger read batch size or clumped +shuffling could help. + + +```py Python icon=Python +import threading, time + +from lancedb.streaming import StreamingDataset + +ds = StreamingDataset(table, shuffle_seed=42) + +def log_pipeline_health(): + while True: + print( + f"unscanned={ds.unscanned_rows} " + f"raw={ds.raw_queue_depth} " + f"cooked={ds.prefetch_queue_depth} " + f"consumed={ds.consumed_rows}" + ) + time.sleep(1.0) + +monitor = threading.Thread(target=log_pipeline_health, daemon=True) +monitor.start() + +for sample in ds: + train_step(sample) + +print( + f"bytes loaded: {ds.bytes_loaded} " + f"fetch time: {ds.fetch_time:.2f}s " + f"transform time: {ds.transform_time:.2f}s" +) +``` + + +`bytes_loaded` measures raw Arrow buffer bytes before transformation. `bytes_loaded`, `fetch_time`, and `transform_time` +are cumulative across iterations of the same dataset instance; because work runs concurrently, the summed stage times +can exceed wall-clock time. The queue depths report rows currently waiting in the pipeline, and the progress counters +reflect the latest iterator snapshot. + +## Next steps {#next} + + + + Stream, shuffle and transform training data with StreamingDataset. + + + Save progress so a failed run can pick back up. + + diff --git a/docs/web/training/permutation.mdx b/docs/web/training/permutation.mdx index 751056541..ebfcce0c6 100644 --- a/docs/web/training/permutation.mdx +++ b/docs/web/training/permutation.mdx @@ -14,7 +14,6 @@ in the order its rows are stored, through an identity `Permutation`. A table its ```py Python icon=Python -import lancedb from lancedb.permutation import Permutation db = lancedb.connect("file://some/db/path") @@ -78,12 +77,14 @@ It expects a list of tensors which it will then stack. This is what is output by requires a data copy. To avoid this error, and avoid data copies, you will need to provide a custom collation function in addition to specifying the `torch_col` format. -```py Python icon=Python + +```python Python icon="python" from lancedb.permutation import Permutation permutation = Permutation.identity(table).with_format("torch_col") dataloader = torch.utils.data.DataLoader(permutation, collate_fn=lambda x: x) ``` + This will now output a single two-dimensional tensor for each batch. @@ -93,8 +94,8 @@ By default, the `Table` class will return all columns in the table when used as a subset of columns, you can significantly reduce your I/O requirements by selecting only the columns you need. The `Permutation` class provides a `select_columns` method that provides this functionality. -```py Python icon=Python -import lancedb + +```python Python icon="python" import pyarrow as pa import torch from lancedb.permutation import Permutation @@ -119,5 +120,6 @@ dataloader = torch.utils.data.DataLoader( for batch in dataloader: print(sorted(batch)) # ['id', 'prompt']: the embedding is never read ``` + Each batch is a dict of the selected columns, the default `Permutation` format described above. diff --git a/docs/web/training/resuming.mdx b/docs/web/training/resuming.mdx new file mode 100644 index 000000000..a80a80a12 --- /dev/null +++ b/docs/web/training/resuming.mdx @@ -0,0 +1,96 @@ +--- +title: "Resuming" +sidebarTitle: "Resuming" +description: "Load a saved StreamingDataset checkpoint back, on the same topology or a different one." +icon: rotate-left +availability: + embedded: available + enterprise: available +--- + +Resuming loads a `StreamingDataset` checkpoint saved by [Checkpointing](/training/checkpointing) back into a fresh dataset and `DataLoader`, so a failed or restarted run picks up where it left off rather than rereading from the start. + +This page assumes the `rank`, `world_size`, `num_splits` and `shuffle_seed` +terminology from [Distributed Training](/training/distributed-training#parallelism-and-elasticity). + +## Resuming on the same topology {#same-topology} + + +```py Python icon=Python +import torch +from lancedb.streaming import StreamingDataset + +checkpoint = torch.load("checkpoint_100.pt") +model.load_state_dict(checkpoint["model"]) + +dataset_state = checkpoint["dataset"] +dataset = StreamingDataset( + table, + num_splits=dataset_state["num_splits"], + shuffle_seed=dataset_state["shuffle_seed"], + epoch=dataset_state["epoch"], + rank=rank, + world_size=world_size, # same as the run that saved the checkpoint +) +dataset.load_state_dict(dataset_state) + +# The combined batch size across every rank, the same value used when the +# checkpoint was saved; each rank's DataLoader gets its world_size share of it. +global_batch_size = 48 +dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=global_batch_size // world_size, + num_workers=0, +) + +for batch in dataloader: + train_step(batch) +``` + + +`load_state_dict()` rejects a checkpoint whose `num_splits` or `shuffle_seed` differs from the new dataset. For an +exact resume, also use the same table snapshot, `epoch`, `shuffle`, `filter`, and other data-selection settings, and +keep `world_size` the same -- changing it is a topology change, covered next. The number of DataLoader workers may +still change as long as the batch-size divisibility constraints from +[Distributed Training](/training/distributed-training#parallelism-and-elasticity) hold. + +## Resuming Across Different Topologies {#resuming-across-different-topologies} + +When training across ranks, each rank owns its own subset of splits and only its own splits have exact progress. To +resume on a different `world_size`, collect the `state_dict()` from every rank of the previous run and merge them with +`StreamingDataset.merge_state_dicts` before calling `load_state_dict()` on the new run. The merge is topology-agnostic: +pass the full list of per-rank states in, and hand the identical merged dict to every rank of the resumed job, +regardless of whether the topology grew, shrank, or stayed the same. + + +```py Python icon=Python +# On each rank of the previous run: +state = dataset.state_dict() +# ...gather `state` from every rank into a single list `states` (for example +# via torch.distributed all-gather or by saving one file per rank). + +merged = StreamingDataset.merge_state_dicts(states) + +# On each rank of the resumed run (world_size may differ): +dataset = StreamingDataset( + table, + num_splits=merged["num_splits"], + shuffle_seed=merged["shuffle_seed"], + epoch=merged["epoch"], + rank=rank, + world_size=new_world_size, +) +dataset.load_state_dict(merged) +``` + + +## Next steps {#next} + + + + Save progress, including with multiple DataLoader workers. + + + The rank, world size and split terminology resuming builds on. + + diff --git a/docs/web/training/training-cache.mdx b/docs/web/training/training-cache.mdx new file mode 100644 index 000000000..3f7e36877 --- /dev/null +++ b/docs/web/training/training-cache.mdx @@ -0,0 +1,102 @@ +--- +title: "Training Cache" +sidebarTitle: "Training Cache" +description: "Connect the PyTorch data loader to LanceDB Enterprise and training reads automatically benefit from the plan executor's data page cache." +icon: "gauge-high" +keywords: ["training", "dataloader", "cache", "data page cache", "enterprise", "epoch"] +availability: + embedded: unavailable + enterprise: available +--- + +The [PyTorch data loader](/training/data-loading) reads training data the +same way any other query does -- there is no training-specific read path. +Point `StreamingDataset` or a `DataLoader` at a table opened through an +Enterprise connection instead of a local one, and every read it makes +flows through the same [plan executors](/enterprise/data-page-cache) that +serve every other query, with the same data page cache in front of object +storage. No training-specific configuration turns this on; it's a +consequence of connecting to Enterprise at all. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + DL["PyTorch DataLoader
/ StreamingDataset"] --> T["Enterprise-connected table"] + T --> PE["Plan executor"] + PE --> C{"In data page cache?"} + C -->|hit| Fast["Served from memory
or local disk"] + C -->|miss| O[("Object storage")] + O --> Fill["Fills the cache,
served"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Fast accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + DL["PyTorch DataLoader
/ StreamingDataset"] --> T["Enterprise-connected table"] + T --> PE["Plan executor"] + PE --> C{"In data page cache?"} + C -->|hit| Fast["Served from memory
or local disk"] + C -->|miss| O[("Object storage")] + O --> Fill["Fills the cache,
served"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Fast accent +``` + +
+ +This covers the ordinary tabular columns a query reads -- the data page +cache's unit is a fixed-size page of table data. A [Blob v2](/management/table#managed-blobs) +column's payload is fetched through a separate range-request path keyed +to its own descriptor, not through this cache, so a training table mixing +plain feature columns with Blob v2 images or video gets this benefit only +for the former. A custom collate function or transform that does its own +file or network I/O -- decoding an image, say -- is also outside this +cache; only reads that go through the table query path benefit. + +## Why this matters for training specifically {#why} + +Training reads the same rows repeatedly: once per epoch, often for many +epochs. The first epoch's reads behave like any cold cache -- a miss per +page, each one filling the cache on the way. Every epoch after that reads +the same pages again, so a dataset that fits the cache's budget serves +almost entirely from memory or local disk after the first pass, instead of +re-reading object storage every epoch. A local-file or Embedded +connection has no equivalent remote cache to warm this way -- its +locality comes from whatever the local filesystem or OS page cache +already does. + +[Cache Prewarm](/enterprise/cache-prewarm) extends this further: a plan +executor can warm its cache at startup, before training even begins, +instead of paying the first-epoch cold-cache cost during the run itself. + +## What to read next {#next} + + + + Connecting a DataLoader to an Enterprise table. + + + How the cache a training read benefits from actually works. + + + Warming the cache before the first epoch instead of during it. + + diff --git a/docs/web/training/vlm-finetuning.mdx b/docs/web/training/vlm-finetuning.mdx index 89c385328..57c8494a3 100644 --- a/docs/web/training/vlm-finetuning.mdx +++ b/docs/web/training/vlm-finetuning.mdx @@ -86,7 +86,8 @@ The Colab notebook's workflow starts after all three tiers have been computed. I The base schema comes from the TextVQA Lance dataset. One row contains the image bytes, natural-language question, reference answers, OCR tokens, scene tags, and retrieval embeddings. -```py Python icon=Python + +```python Python icon="python" import pyarrow as pa BASE_SCHEMA = pa.schema([ @@ -104,6 +105,7 @@ BASE_SCHEMA = pa.schema([ pa.field("set_name", pa.string()), ]) ``` + Because the raw image, text, OCR, and embedding features live together, the same table supports curation, retrieval, feature engineering, and training. For example, the notebook can run a text-to-image retrieval demo by searching `image_emb` with a question embedding that already exists in the row. @@ -113,7 +115,8 @@ Geneva turns feature engineering into UDF definitions plus backfills. The UDFs c The Tier 1 features are ordinary CPU UDFs: -```py Python icon=Python + +```python Python icon="python" import re import pyarrow as pa from geneva.transformer import udf @@ -135,10 +138,12 @@ def question_type(question: str) -> str: def ocr_token_count(ocr_tokens: list[str] | None) -> int: return len(ocr_tokens) if ocr_tokens else 0 ``` + The Tier 3 feature is heavier: run Qwen2.5-VL's frozen vision tower once, then store the merged visual hidden states as a fixed-size fp16 list. -```py Python icon=Python + +```python Python icon="python" IMAGE_PX = 560 LLM_TOKENS_PER_IMAGE = 400 VISION_HIDDEN = 2048 @@ -172,16 +177,19 @@ class VisionTowerEmbedder: # and return fp16[400, 2048] flattened as one fixed-size list. ... ``` + The fixed shape matters. With `IMAGE_PX = 560`, Qwen2.5-VL produces 400 merged visual tokens, each with hidden size 2048. That becomes one `fp16[400 * 2048]` column per row. Training can scan and randomly access that column without decoding images or running the vision tower in the hot loop, saving GPU compute at training time. Run the tiered backfill with Geneva: -```bash bash icon="terminal" + +```bash Bash icon="terminal" python -m vlm.backfill_geneva --tier 1 # CPU text columns python -m vlm.backfill_geneva --tier 2 # image decode + dhash python -m vlm.backfill_geneva --tier 3 # vision tower + SFT tokens ``` + The same Tier 3 work can be done manually by creating PyArrow batches and calling Lance's column-evolution APIs directly. The demo repo includes [`backfill_direct.py`](https://github.com/lancedb/tmls-2026-demo/blob/main/vlm/backfill_direct.py) for that path. Geneva is the preferred abstraction when you want to scale the same feature code across CPU or GPU workers and keep backfills incremental. @@ -193,16 +201,19 @@ See the full UDF registry in [`vlm/geneva_udfs.py`](https://github.com/lancedb/t The demo uses a `text_dense` slice: TextVQA examples whose images contain many OCR tokens. The slice was chosen empirically because it gave the clearest LoRA lift over the already-strong base model. -```py Python icon=Python + +```python Python icon="python" TEXT_DENSE_OCR_THRESHOLD = 16 def matches_text_dense(row: dict) -> bool: return len(row.get("ocr_tokens") or []) >= TEXT_DENSE_OCR_THRESHOLD ``` + -The Colab-ready bake ingests a small train split, backfills Tier 3 on that train table, ingests a held-out validation split, and optionally pushes the result to Hugging Face: +The Colab-ready bake ingests a small train split, backfills Tier 3 on that train table, ingests a held-out validation split, and optionally pushes the result to HuggingFace: -```bash bash icon="terminal" + +```bash Bash icon="terminal" python -m vlm.colab_prepare \ --out data/colab \ --slice text_dense \ @@ -211,6 +222,7 @@ python -m vlm.colab_prepare \ --hf-repo lance-format/textvqa-lance-colab \ --push ``` + The train table contains cached Tier 3 columns because training reads them directly. The validation table keeps raw images because evaluation should run the full VLM on unseen images. @@ -255,9 +267,9 @@ Before training, it helps to look at the actual task. Each row pairs an image wi The notebook downloads the public pre-baked subset: -```py Python icon=Python + +```python Python icon="python" from huggingface_hub import snapshot_download -import lancedb import os local = snapshot_download( @@ -273,10 +285,12 @@ def open_tbl(path: str): train_tbl = open_tbl(f"{local}/textvqa_colab_train.lance") val_tbl = open_tbl(f"{local}/textvqa_colab_val.lance") ``` + Because the table also ships CLIP embeddings, you can run cross-modal retrieval without loading a model: -```py Python icon=Python + +```python Python icon="python" import numpy as np seed = ( @@ -298,6 +312,7 @@ hits = ( .to_pylist() ) ``` + This is the same table that later feeds training. There is no separate feature store, image directory, Parquet export, or manifest to keep synchronized. @@ -312,7 +327,8 @@ Many training pipelines start with Parquet. Parquet is excellent for columnar an The notebook mirrors those column groups to uncompressed Parquet, then measures sequential scans and shuffled random batches: -```py Python icon=Python + +```python Python icon="python" RAW = ["image", "question", "answer"] VEC = ["vision_tower_hiddens"] BATCH = 8 @@ -336,6 +352,7 @@ def shuf(ds, cols, num_batches=20): ds.take(idx, columns=cols) return (num_batches * BATCH) / (time.time() - t0) ``` + One Colab run produced the following throughput: @@ -359,7 +376,8 @@ The numbers shown above are central to the example. The Tier 3 feature is only u The training DataLoader projects only the columns needed by the cached training loop: -```py Python icon=Python + +```python Python icon="python" from lancedb.permutation import Permutation CACHED_COLS = [ @@ -397,6 +415,7 @@ class LancePermutationDataset(torch.utils.data.Dataset): self._ensure_open() return self._perm.__getitems__(indices) ``` + Each worker opens its own `Permutation`, reads Arrow batches directly from Lance, and avoids per-row Python object conversion until the collate function converts arrays into tensors. @@ -415,7 +434,8 @@ The training process loads the language-model side of Qwen2.5-VL in 4-bit, delet During the forward pass, the model embeds the token IDs, finds the `<|image_pad|>` positions, and inserts the cached visual hidden states into those positions: -```py Python icon=Python + +```python Python icon="python" def forward_cached(model, batch, image_pad_id: int): base = model.get_base_model() if hasattr(model, "get_base_model") else model inner = base.model @@ -438,10 +458,12 @@ def forward_cached(model, batch, image_pad_id: int): labels=batch.labels, ).loss ``` + At this point, the LanceDB integration is done. The rest is plain PyTorch: optimizer, gradient accumulation, checkpointing, and saving the LoRA adapter. -```py Python icon=Python + +```python Python icon="python" loader = make_cached_loader( "data/colab/textvqa_colab_train.lance", batch_size=2, @@ -454,6 +476,7 @@ for batch in loader: (loss / grad_accum).backward() ... ``` + This produces a training log like the following. The loss falls as the adapter learns from the cached features, and peak VRAM stays at 5.3 GB because QLoRA trains without keeping the vision tower active: @@ -474,7 +497,8 @@ The training loop pays zero per-step cost for image decode, vision-tower forward Evaluation uses the held-out validation table and loads the full VLM, including the vision tower. That is intentional: inference should see raw unseen images, not the cached train features. -```py Python icon=Python + +```python Python icon="python" rows = ( val_tbl.search() .select(["image", "question", "answer", "answers"]) @@ -489,6 +513,7 @@ tuned_model, processor = load_model(adapter_dir="runs/colab_lora/lora", load_4bi base_score = score_textvqa(base_model, processor, rows) tuned_score = score_textvqa(tuned_model, processor, rows) ``` + In this end-to-end example, the held-out curated validation split produced: diff --git a/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx b/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx index 19d1ec7c9..28f11669f 100644 --- a/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx +++ b/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx @@ -54,10 +54,12 @@ NVIDIA's containers. From the [recipe directory](https://github.com/lancedb/vectordb-recipes/tree/main/examples/nvidia-rag-blueprint-lancedb): -```bash + +```bash Bash icon="terminal" uv sync uv run prepare_lancedb.py --embedder demo-keyword --reranker mrr ``` + That script creates: @@ -85,13 +87,16 @@ NVIDIA's [RAG blueprint documentation](https://docs.nvidia.com/rag/latest/readme Set the absolute path to the recipe directory: -```bash + +```bash Bash icon="terminal" export LANCEDB_RECIPE_DIR=/absolute/path/to/vectordb-recipes/examples/nvidia-rag-blueprint-lancedb ``` + Then from the NVIDIA repo root: -```bash + +```bash Bash icon="terminal" docker compose \ -f deploy/compose/docker-compose-rag-server.yaml \ -f "$LANCEDB_RECIPE_DIR"/docker-compose.override.yml \ @@ -102,6 +107,7 @@ docker compose \ -f "$LANCEDB_RECIPE_DIR"/docker-compose.override.yml \ up -d --build ``` + The key environment values are: @@ -115,7 +121,8 @@ The key environment values are: ### Search {#search} -```bash + +```bash Bash icon="terminal" curl -X POST http://localhost:8081/v1/search \ -H 'Content-Type: application/json' \ -d '{ @@ -126,10 +133,12 @@ curl -X POST http://localhost:8081/v1/search \ "reranker_top_k": 0 }' ``` + ### Generate {#generate} -```bash + +```bash Bash icon="terminal" curl -N -X POST http://localhost:8081/v1/generate \ -H 'Content-Type: application/json' \ -d '{ @@ -140,6 +149,7 @@ curl -N -X POST http://localhost:8081/v1/generate \ "reranker_top_k": 0 }' ``` + ## Hybrid retrieval and rerankers {#hybrid-retrieval-and-rerankers} diff --git a/docs/web/tutorials/agents/time-travel-rag/index.mdx b/docs/web/tutorials/agents/time-travel-rag/index.mdx index c1cef0ca9..241693a84 100644 --- a/docs/web/tutorials/agents/time-travel-rag/index.mdx +++ b/docs/web/tutorials/agents/time-travel-rag/index.mdx @@ -45,7 +45,8 @@ It contains all new rules, proposed rules, and notices from federal agencies. It An example output of the workflow defined in main.py is shown below. -```bash main.py expandable + +```bash main.py expandable icon="terminal" --- Initializing Database Environment --- Removed old database at ./lancedb Loading embedding model: all-MiniLM-L6-v2... @@ -179,3 +180,4 @@ Control Centers. The 60-day notice comment period ended on July 23, 2024, with n ✅ A/B test complete. Notice the difference in relevance (distance score) between models. This showcases how LanceDB enables [experimentation with different embedding models](/docs/embeddings/) without disrupting production systems. ``` + diff --git a/docs/web/tutorials/index.mdx b/docs/web/tutorials/index.mdx index 6ada57c9a..b9aea29a2 100644 --- a/docs/web/tutorials/index.mdx +++ b/docs/web/tutorials/index.mdx @@ -21,7 +21,7 @@ are runnable in Colab; the rest are written up here. Retrieval-augmented generation and agent applications. - Deriving columns, materialized views, experimenting on branches. + Deriving columns and materialized views.{/* Draft until branching reaches early access: restore "Deriving columns, materialized views, experimenting on branches." */} Curating data and training models directly on a table. diff --git a/docs/web/tutorials/search/multivector-needle-in-a-haystack.mdx b/docs/web/tutorials/search/multivector-needle-in-a-haystack.mdx index 7b6e1318a..234a761d1 100644 --- a/docs/web/tutorials/search/multivector-needle-in-a-haystack.mdx +++ b/docs/web/tutorials/search/multivector-needle-in-a-haystack.mdx @@ -72,8 +72,8 @@ This is the pure, baseline late-interaction search. It offers the highest potent **LanceDB also integrates with ConteXtualized Token Retriever (XTR)** , an advanced retrieval model that prioritizes the most semantically important document tokens during search. This integration enhances the quality of search results by focusing on the most relevant token matches. **LanceDB Implementation:** + ```python Python icon="python" -import lancedb import pyarrow as pa # Schema for multivector data @@ -94,6 +94,7 @@ tbl.add([{"page_num": 1, "vector": multi_token_embeddings.tolist()}]) # query_multi_vector is also shape (num_query_tokens, 128) results = tbl.search(query_multi_vector).limit(5).to_list() ``` + ### 2\. `flatten`: Mean Pooling {#2-flatten-mean-pooling} @@ -101,6 +102,7 @@ This strategy "flattens" the set of token vectors into a single vector by averag **LanceDB Implementation:** + ```python Python icon="python" # Schema for single-vector data schema_flat = pa.schema([ @@ -117,6 +119,7 @@ tbl_flat.add([{"page_num": 1, "vector": mean_vector.tolist()}]) query_mean_vector = query_multi_vector.mean(axis=0) results = tbl_flat.search(query_mean_vector).limit(5).to_list() ``` + ### 3\. Max pooling {#3-max-pooling} @@ -128,6 +131,7 @@ This two-stage strategy aims for the best of both worlds. First, use a fast, poo **LanceDB Implementation:** This requires a table with two vector columns. + ```python Python icon="python" # Schema with both flat and multivector columns schema_rerank = pa.schema([ @@ -161,6 +165,7 @@ final_results = tbl_rerank.search(query_multi_vector, vector_column_name="vector .limit(5) \ .to_list() ``` + ### 5\. `hierarchical token pooling`: Compressing the Haystack {#5-hierarchical-token-pooling-compressing-the-haystack} @@ -172,6 +177,7 @@ This is an indexing-time strategy that aims to reduce the storage footprint and **LanceDB Implementation:** The schema is identical to the `base` multivector search, but the data is pre-processed before ingestion. + ```python Python icon="python" from utils import pool_embeddings_hierarchical import numpy as np @@ -197,6 +203,7 @@ tbl_hierarchical.add([{"page_num": 1, "vector": pooled_embeddings.tolist()}]) # Search is identical to the base multivector search results = tbl_hierarchical.search(query_multi_vector).limit(5).to_list() ``` + ## The Results {#the-results} diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index c89980194..f915a6a64 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.17 + 0.42.0-beta.9 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 2bccd2510..88b66b3ad 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.17 + 0.42.0-beta.9 pom ${project.artifactId} LanceDB Java SDK Parent POM @@ -28,8 +28,8 @@ UTF-8 15.0.0 - 15.0.0-beta.6 - 2.18.11 + 15.0.0-beta.15 + 2.18.12 false 2.30.0 1.7 diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 3ed65c704..d8f16adb1 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.41.0-beta.17" +version = "0.42.0-beta.9" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/__test__/arrow.test.ts b/nodejs/__test__/arrow.test.ts index 376533961..27dd14954 100644 --- a/nodejs/__test__/arrow.test.ts +++ b/nodejs/__test__/arrow.test.ts @@ -1567,11 +1567,17 @@ describe.each(arrowVersions)("Arrow %#", (arrow: ApacheArrow) => { const records = [ { text: "dog", vector: [0.1, 0.2] }, { text: "cat", vector: [0.3, 0.4] }, + { text: null, vector: null }, ]; - const table = await convertToTable(records); + const table = arrow.tableFromArrays({ + text: records.map((row) => row.text), + vector: records.map((row) => row.vector), + }); const batch = table.batches[0]; - const buffer = await fromRecordBatchToBuffer(batch); + const buffer = await fromRecordBatchToBuffer( + batch as Parameters[0], + ); const result = await fromBufferToRecordBatch(buffer); expect(JSON.stringify(batch.toArray())).toEqual( diff --git a/nodejs/__test__/connection.test.ts b/nodejs/__test__/connection.test.ts index 73f99803a..790e8554d 100644 --- a/nodejs/__test__/connection.test.ts +++ b/nodejs/__test__/connection.test.ts @@ -158,6 +158,33 @@ describe("given a connection", () => { await expect(tbl.countRows()).resolves.toBe(1); }); + it("should isolate local object-form table creation across connections", async () => { + const otherTmpDir = tmp.dirSync({ unsafeCleanup: true }); + const otherDb = await connect(otherTmpDir.name); + + try { + const firstTable = await db.createTable({ + name: "defaultTable", + data: [{ rowId: "id1", vector: Array(384).fill(0) }], + }); + const secondTable = await otherDb.createTable({ + name: "defaultTable", + data: [{ rowId: "id2", vector: Array(384).fill(0) }], + }); + + await expect(db.tableNames()).resolves.toEqual(["defaultTable"]); + await expect(otherDb.tableNames()).resolves.toEqual(["defaultTable"]); + + const firstRows = await firstTable.query().select(["rowId"]).toArray(); + const secondRows = await secondTable.query().select(["rowId"]).toArray(); + expect(firstRows.map((row) => row.rowId)).toEqual(["id1"]); + expect(secondRows.map((row) => row.rowId)).toEqual(["id2"]); + } finally { + otherDb.close(); + otherTmpDir.removeCallback(); + } + }); + it("should be able to drop tables`", async () => { await db.createTable("test", [{ id: 1 }, { id: 2 }]); await db.createTable("test2", [{ id: 1 }, { id: 2 }]); @@ -184,6 +211,7 @@ describe("given a connection", () => { const job = await db.dropTableAsync("async-drop"); expect(job.id).toBeNull(); await expect(job.status()).resolves.toBe("finished"); + await expect(job.progress()).resolves.toBeNull(); await job.wait(); await expect(db.tableNames()).resolves.toEqual([]); }); diff --git a/nodejs/__test__/query.test.ts b/nodejs/__test__/query.test.ts index 068e55c2f..c0b30ac63 100644 --- a/nodejs/__test__/query.test.ts +++ b/nodejs/__test__/query.test.ts @@ -564,7 +564,8 @@ describe("IVF search effort", () => { it.each([ [null, 6], [0, 1], - [0.25, 3], + [0.1, 2], + [0.25, 4], [0.5, 6], [0.75, 10], [1, 16], diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 8d5c21aa3..242be6101 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -32,6 +32,7 @@ import { StaticHeaderProvider, } from "../lancedb/header"; import { Index } from "../lancedb/indices"; +import type { JobProgress } from "../lancedb/job"; import { LocalTable } from "../lancedb/table"; // Test-only header providers @@ -115,14 +116,14 @@ describe("remote connection", () => { ...options, mode: "overwrite", }), - ).rejects.toThrow(/write_options.*LanceDB Distributed/); + ).rejects.toThrow(/write_options.*LanceDB Enterprise/); await expect( db.createEmptyTable( "test", new Schema([new Field("value", new Int64(), true)]), options, ), - ).rejects.toThrow(/write_options.*LanceDB Distributed/); + ).rejects.toThrow(/write_options.*LanceDB Enterprise/); }, ); expect(requests).toEqual([]); @@ -141,7 +142,7 @@ describe("remote connection", () => { await expect( db.openTable("test", undefined, options), ).rejects.toThrow( - /not supported for table access in LanceDB Distributed/, + /not supported for table access in LanceDB Enterprise/, ); }, ); @@ -311,14 +312,13 @@ describe("remote connection", () => { const cases: [() => Promise, string][] = [ [() => table.usesV2ManifestPaths(), "uses_v2_manifest_paths"], [() => table.migrateManifestPathsV2(), "migrate_manifest_paths_v2"], - [() => table.optimize(), "optimize"], [ () => table.createIndex("vector", { config: Index.hnswPq() }), "IVF_HNSW_PQ", ], ]; for (const [run, operation] of cases) { - let message = `LanceDBError: not supported: ${operation} is not supported in LanceDB Distributed.`; + let message = `LanceDBError: not supported: ${operation} is not supported in LanceDB Enterprise.`; if (operation === "IVF_HNSW_PQ") { message += " Please use IVF_HNSW_SQ instead."; } @@ -483,98 +483,6 @@ describe("remote connection", () => { expect(insertRequests).toBe(2); }); - it("creates a view and decodes the schema it resolved to", async () => { - await withMockDatabase( - (req, res) => { - expect(req.method).toBe("POST"); - expect(req.url).toBe("/v1/view/analytics$adults/create"); - res.writeHead(200, { "content-type": "application/json" }).end( - JSON.stringify({ - name: "adults", - namespace: ["analytics"], - query: "SELECT name FROM people", - // biome-ignore lint/style/useNamingConvention: the wire field is snake_case - default_database: "db", - // biome-ignore lint/style/useNamingConvention: the wire field is snake_case - default_namespace: ["analytics"], - schema: { - fields: [ - { name: "name", nullable: true, type: { type: "utf8" } }, - ], - }, - }), - ); - }, - async (db) => { - const view = await db.createView("adults", "SELECT name FROM people", [ - "analytics", - ]); - expect(view.name).toBe("adults"); - expect(view.namespacePath).toEqual(["analytics"]); - expect(view.query).toBe("SELECT name FROM people"); - expect(view.defaultDatabase).toBe("db"); - expect(view.defaultNamespacePath).toEqual(["analytics"]); - expect(view.schema.fields.map((f) => f.name)).toEqual(["name"]); - }, - ); - }); - - it("lists and drops views through their own routes", async () => { - await withMockDatabase( - (req, res) => { - expect(req.url).toBe("/v1/namespace/$/view/list"); - res - .writeHead(200, { "content-type": "application/json" }) - .end(JSON.stringify({ views: ["adults"] })); - }, - async (db) => { - expect(await collect(db.listViews())).toEqual(["adults"]); - }, - ); - - await withMockDatabase( - (req, res) => { - expect(req.method).toBe("POST"); - expect(req.url).toBe("/v1/view/adults/drop"); - res.writeHead(200, { "content-type": "application/json" }).end("{}"); - }, - async (db) => { - await db.dropView("adults"); - }, - ); - }); - - it("reports the cleanup job when a view drop is accepted", async () => { - await withMockDatabase( - (req, res) => { - expect(req.method).toBe("POST"); - expect(req.url).toBe("/v1/view/adults/drop"); - res - .writeHead(202, { "content-type": "application/json" }) - .end('{"job_id": "j1-do-abc"}'); - }, - async (db) => { - const job = await db.dropViewAsync("adults"); - expect(job.id).toBe("j1-do-abc"); - }, - ); - }); - - it("reports a finished job when a view drop had nothing to delete", async () => { - await withMockDatabase( - (req, res) => { - expect(req.url).toBe("/v1/view/adults/drop"); - res.writeHead(200, { "content-type": "application/json" }).end("{}"); - }, - async (db) => { - // A 200 means the name was not bound, so there is no cleanup to wait on. - const job = await db.dropViewAsync("adults"); - expect(job.id).toBeNull(); - await job.wait(); - }, - ); - }); - it("should accept partial connection options", async () => { await connect("db://test", { apiKey: "fake", @@ -739,6 +647,80 @@ describe("remote connection", () => { ]); }); + it("forwards refresh options to the backfill request", async () => { + const bodies: unknown[] = []; + await withMockDatabase( + (req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "docs", + version: 1, + schema: { fields: [] }, + }), + ); + return; + } + if (path === "/v1/table/docs/backfill_column") { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + bodies.push(JSON.parse(body)); + res + .writeHead(202, { "Content-Type": "application/json" }) + .end('{"job_id": "j-9"}'); + }); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("docs"); + const job = await table.refreshColumnAsync("embedding", { + where: "id % 2 = 0", + batchSize: 16, + gpuClass: "a10g", + gpuCount: 2, + errorPolicy: "skip", + maxFailedFraction: 0.01, + maxFailedRows: 50, + rowTimeoutSeconds: 30, + initTimeoutSeconds: 120, + maxExecutorProcessesPerWorker: 2, + }); + expect(job.id).toBe("j-9"); + await table.refreshColumnAsync("embedding"); + // Invalid options reject before any request is sent. + for (const [options, message] of [ + [{ maxFailedRows: -1 }, "maxFailedRows"], + [{ errorPolicy: "retry" }, "errorPolicy"], + [{ where: " " }, "where"], + [{ maxFailedFraction: 2 }, "max_failed_fraction"], + [{ rowTimeoutSeconds: 0 }, "row_timeout_seconds"], + [{ numWorkers: 0 }, "num_workers"], + [{ gpuCount: 0 }, "gpu_count"], + ] as const) { + await expect( + table.refreshColumnAsync("embedding", options), + ).rejects.toThrow(message); + } + }, + ); + expect(bodies).toEqual([ + JSON.parse( + `{"column": "embedding", "where": "id % 2 = 0", "batch_size": 16, + "gpu_class": "a10g", "gpu_count": 2, "error_policy": "skip", + "max_failed_fraction": 0.01, "max_failed_rows": 50, + "row_timeout_seconds": 30, "init_timeout_seconds": 120, + "max_executor_processes_per_worker": 2}`, + ), + { column: "embedding" }, + ]); + }); + it("surfaces JSON server errors from remote table operations", async () => { await withMockDatabase( (req, res) => { @@ -1533,7 +1515,9 @@ describe("remote connection jobs surface", () => { .end( '{"jobs": [{"job_id": "job-1", "table": "t1", ' + '"job_type": "create_index", "state": "in_progress", ' + - '"created_at_millis": 1000}], "page_token": "next"}', + '"created_at_millis": 1000, ' + + '"progress": {"rows_planned": 4, "rows_computed": 2}, ' + + '"phase": "running", "paused": false}], "page_token": "next"}', ); } else { res @@ -1564,6 +1548,9 @@ describe("remote connection jobs surface", () => { .end( '{"job_id": "job-1", "job_type": "create_index", ' + '"job_state": "FAILED", "creation_ms": 1000, ' + + '"progress": {"rows_planned": 4, "rows_computed": 2, ' + + '"vendor_extension": "kept"}, ' + + '"phase": "running", ' + '"spec": {"column": "vec"}, "failure": {"phase": "execute", ' + '"message": "worker died", "retryable": true}}', ); @@ -1610,6 +1597,19 @@ describe("remote connection jobs surface", () => { expect(jobs.map((job) => job.jobId)).toEqual(["job-1", "job-2"]); expect(jobs[0].state).toEqual("running"); expect(jobs[1].state).toEqual("finished"); + expect(jobs[0].progress).toEqual({ + // biome-ignore lint/style/useNamingConvention: server wire format + job_type: "create_index", + state: "running", + // biome-ignore lint/style/useNamingConvention: server wire format + creation_ms: 1000, + paused: false, + phase: "running", + // biome-ignore lint/style/useNamingConvention: server wire format + rows_planned: 4, + // biome-ignore lint/style/useNamingConvention: server wire format + rows_computed: 2, + }); expect(await db.cancelJob("job-1")).toBe(true); expect(await db.cancelJob("missing")).toBe(false); @@ -1638,6 +1638,21 @@ describe("remote connection jobs surface", () => { expect(job.spec).toEqual({ column: "vec" }); expect(job.result).toBeNull(); expect(job.failure?.message).toEqual("worker died"); + expect(await job.progress()).toEqual({ + // biome-ignore lint/style/useNamingConvention: server wire format + job_type: "create_index", + state: "failed", + // biome-ignore lint/style/useNamingConvention: server wire format + creation_ms: 1000, + paused: false, + phase: "running", + // biome-ignore lint/style/useNamingConvention: server wire format + rows_planned: 4, + // biome-ignore lint/style/useNamingConvention: server wire format + rows_computed: 2, + // biome-ignore lint/style/useNamingConvention: server wire format + vendor_extension: "kept", + }); // The handle reaches its own events, supplying its job id. const jobEvents = await job.events({ @@ -1679,6 +1694,207 @@ describe("remote connection jobs surface", () => { ); }); + it("observes structured progress through the existing wait poller", async () => { + const now = Date.now(); + const unknownFleet = { + desired: 2, + launched: 1, + // biome-ignore lint/style/useNamingConvention: server wire format + pending_workers: 1, + ready: 0, + // biome-ignore lint/style/useNamingConvention: server wire format + requested_gpus: 1, + // biome-ignore lint/style/useNamingConvention: server wire format + ready_gpus: 0, + // biome-ignore lint/style/useNamingConvention: server wire format + resource_classes: ["a10g"], + // biome-ignore lint/style/useNamingConvention: server wire format + first_launched_at_millis: now - 4000, + }; + const knownFleet = { + ...unknownFleet, + // biome-ignore lint/style/useNamingConvention: server wire format + warm_reused: true, + // biome-ignore lint/style/useNamingConvention: server wire format + wait_reason: "Job queued, waiting for GPU capacity in class 'a10g'", + }; + const progress = ( + rowsComputed: number, + rowsRemaining: number, + sampleOffset: number, + workerFleet: typeof knownFleet | typeof unknownFleet, + ) => + JSON.stringify({ + // biome-ignore lint/style/useNamingConvention: server wire format + rows_planned: 100, + // biome-ignore lint/style/useNamingConvention: server wire format + rows_computed: rowsComputed, + // biome-ignore lint/style/useNamingConvention: server wire format + rows_skipped: 0, + // biome-ignore lint/style/useNamingConvention: server wire format + rows_remaining: rowsRemaining, + // biome-ignore lint/style/useNamingConvention: server wire format + fragments_planned: 4, + // biome-ignore lint/style/useNamingConvention: server wire format + execution_epoch: 7, + // biome-ignore lint/style/useNamingConvention: server wire format + sample_at_millis: now - sampleOffset, + // biome-ignore lint/style/useNamingConvention: server wire format + worker_fleet: workerFleet, + // biome-ignore lint/style/useNamingConvention: server wire format + queue_reason: "Waiting for Function worker capacity", + }); + const descriptions = [ + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 3000, unknownFleet)}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 2000, knownFleet)}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(40, 60, 1000, unknownFleet)}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(60, 0, 0, unknownFleet)}}`, + ]; + let describeCount = 0; + + await withMockDatabase( + (req, res) => { + if (req.url === "/v1/jobs/describe") { + describeCount++; + const description = descriptions.shift(); + if (description === undefined) { + res.writeHead(500).end("unexpected describe"); + return; + } + res + .writeHead(200, { "Content-Type": "application/json" }) + .end(description); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const job = await db.openJob("job-wait"); + const first = await job.progress(); + expect(first).toMatchObject({ + state: "running", + // biome-ignore lint/style/useNamingConvention: server wire format + rows_computed: 20, + // biome-ignore lint/style/useNamingConvention: server wire format + rows_remaining: 80, + }); + expect(first?.worker_fleet).toMatchObject(knownFleet); + expect( + (first?.worker_fleet as Record | null | undefined) + ?.warm_reused, + ).toBe(true); + expect(first?.queue_reason).toBe( + "Waiting for Function worker capacity", + ); + expect(first).not.toHaveProperty("estimated_remaining_time_millis"); + + const observed: JobProgress[] = []; + await job.wait((progress) => observed.push(progress)); + + expect(observed).toHaveLength(2); + expect(observed[0]).toMatchObject({ + state: "running", + // biome-ignore lint/style/useNamingConvention: server wire format + rows_computed: 40, + // biome-ignore lint/style/useNamingConvention: server wire format + estimated_remaining_time_millis: 3000, + }); + expect(observed[0].worker_fleet).toEqual(unknownFleet); + expect(observed[0].worker_fleet).not.toHaveProperty("warm_reused"); + expect(observed[0].queue_reason).toBe( + "Waiting for Function worker capacity", + ); + expect(observed[1]).toMatchObject({ + state: "finished", + // biome-ignore lint/style/useNamingConvention: server wire format + rows_remaining: 0, + // biome-ignore lint/style/useNamingConvention: server wire format + estimated_remaining_time_millis: 0, + }); + }, + ); + + expect(describeCount).toBe(4); + }); + + it("does not derive ETA across a zero-rate, epoch, or pause boundary", async () => { + const now = Date.now(); + const descriptions = [ + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 5000}}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 4000}}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 3000}}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 2000}}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1500}}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1000}}}`, + ]; + + await withMockDatabase( + (req, res) => { + if (req.url === "/v1/jobs/describe") { + const description = descriptions.shift(); + if (description === undefined) { + res.writeHead(500).end("unexpected describe"); + return; + } + res + .writeHead(200, { "Content-Type": "application/json" }) + .end(description); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const job = await db.openJob("job-eta"); + for (let i = 0; i < 5; i++) { + const progress = await job.progress(); + expect(progress).not.toHaveProperty( + "estimated_remaining_time_millis", + ); + } + }, + ); + }); + + it("keeps a thrown progress observer from escaping wait", async () => { + const descriptions = [ + '{"job_id":"job-throw","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":4,"rows_computed":2}}', + '{"job_id":"job-throw","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{}}', + ]; + + await withMockDatabase( + (req, res) => { + if (req.url === "/v1/jobs/describe") { + const description = descriptions.shift(); + if (description === undefined) { + res.writeHead(500).end("unexpected describe"); + return; + } + res + .writeHead(200, { "Content-Type": "application/json" }) + .end(description); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const job = await db.openJob("job-throw"); + const warn = jest + .spyOn(console, "warn") + .mockImplementation(() => undefined); + try { + await expect( + job.wait(() => { + throw new Error("observer failed"); + }), + ).resolves.toBeUndefined(); + expect(warn).toHaveBeenCalled(); + } finally { + warn.mockRestore(); + } + }, + ); + }); + it("leaves numDeletedRows absent when the server omits it", async () => { // A server that predates num_deleted_rows says nothing about deleted rows const statsReply = @@ -1710,13 +1926,12 @@ async function collect(items: AsyncIterable): Promise { } describe("lazy resource listings", () => { - for (const kind of ["views", "jobs"] as const) { + for (const kind of ["jobs"] as const) { const listing = ( db: Connection, options: { pageToken?: string; pageLimit?: number } = {}, ) => { - if (kind === "jobs") return db.listJobs(options); - return db.listViews(["team"], options); + return db.listJobs(options); }; const page = (names: string[], token?: string) => { const items = diff --git a/nodejs/__test__/rerankers.test.ts b/nodejs/__test__/rerankers.test.ts index 256ef686c..8e3a36f98 100644 --- a/nodejs/__test__/rerankers.test.ts +++ b/nodejs/__test__/rerankers.test.ts @@ -1,13 +1,42 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -import { spawn } from "node:child_process"; +import { execFileSync, spawn } from "node:child_process"; import * as path from "node:path"; import { RecordBatch } from "apache-arrow"; import * as tmp from "tmp"; import { Connection, Index, Table, connect, makeArrowTable } from "../lancedb"; import { RRFReranker } from "../lancedb/rerankers"; +it("reranks record batches created by an ESM Arrow import", () => { + const script = ` +import assert from "node:assert/strict"; +import { tableFromArrays } from "apache-arrow"; +import { rerankers } from "./dist/index.js"; + +const ids = [1n, 9007199254740993n]; +const batch = tableFromArrays({ _rowid: new BigUint64Array(ids) }).batches[0]; +const reranker = await rerankers.RRFReranker.create(); +const result = await reranker.rerankHybrid("", batch, batch); + +assert.equal(result.numRows, 2); +assert.deepEqual(Array.from(result.getChild("_rowid").toArray()), ids); +const scores = result.getChild("_relevance_score").toArray(); +assert.ok(Math.abs(scores[0] - 2 / 61) < 1e-8); +assert.ok(Math.abs(scores[1] - 2 / 62) < 1e-8); + +const oneSide = await reranker.rerankHybrid("", batch, batch.slice(0, 0)); +assert.deepEqual(Array.from(oneSide.getChild("_rowid").toArray()), ids); +const oneSideScores = oneSide.getChild("_relevance_score").toArray(); +assert.ok(Math.abs(oneSideScores[0] - 1 / 61) < 1e-8); +assert.ok(Math.abs(oneSideScores[1] - 1 / 62) < 1e-8); +`; + execFileSync(process.execPath, ["--input-type=module", "-e", script], { + cwd: path.resolve(__dirname, ".."), + timeout: 10_000, + }); +}); + describe("rerankers", function () { let tmpDir: tmp.DirResult; let conn: Connection; diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index b41d98767..c3888d6c0 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -11,6 +11,7 @@ import { AutoQuery, type BlobInput, type BlobMode, + type CompactionOptions, Connection, MatchQuery, PhraseQuery, @@ -1626,6 +1627,23 @@ describe("When creating an index", () => { // test ef rst = await tbl.query().limit(2).nearestTo(queryVec).ef(100).toArrow(); expect(rst.numRows).toBe(2); + + // test approxMode + for (const mode of ["fast", "normal", "accurate"] as const) { + rst = await tbl + .query() + .limit(2) + .nearestTo(queryVec) + .approxMode(mode) + .toArrow(); + expect(rst.numRows).toBe(2); + } + expect(() => + tbl + .query() + .nearestTo(queryVec) + .approxMode("turbo" as "fast"), + ).toThrow("approx_mode must be one of"); }); it("should be able to query unindexed data", async () => { @@ -3980,7 +3998,93 @@ it("passes cleanupOlderThan to the native binding as an absolute timestamp", asy await table.optimize({ cleanupOlderThan: cutoff, deleteUnverified: true }); - expect(optimize).toHaveBeenCalledWith(cutoff.getTime(), true); + expect(optimize).toHaveBeenCalledWith(cutoff.getTime(), true, undefined); +}); + +it("forwards per-job compaction options to the native binding", async () => { + const optimize = jest.fn().mockResolvedValue({}); + const table = new LocalTable({ optimize } as never); + const compactionOptions = { + targetRowsPerFragment: 20, + maxSourceRows: 25, + ioBufferSize: 0, + batchSize: 8, + }; + await table.optimize({ compactionOptions }); + expect(optimize).toHaveBeenCalledWith( + undefined, + undefined, + compactionOptions, + ); +}); + +it("rejects unsupported JavaScript compaction options before native submission", async () => { + const optimize = jest.fn(); + const table = new LocalTable({ optimize } as never); + await expect( + table.optimize({ + compactionOptions: { + maxSourceBytes: 1024, + } as unknown as CompactionOptions, + }), + ).rejects.toThrow("Unsupported compaction option: maxSourceBytes"); + expect(optimize).not.toHaveBeenCalled(); +}); + +describe("per-job compaction options", () => { + let tmpDir: tmp.DirResult; + let table: Table; + beforeEach(async () => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + const db = await connect(tmpDir.name); + table = await db.createTable( + "bounded", + Array.from({ length: 10 }, (_, id) => ({ id })), + ); + for (let f = 1; f < 8; f++) { + await table.add( + Array.from({ length: 10 }, (_, id) => ({ id: f * 10 + id })), + ); + } + }); + afterEach(() => { + tmpDir.removeCallback(); + }); + it("bounds source work and preserves zero I/O buffering", async () => { + const stats = await table.optimize({ + compactionOptions: { + targetRowsPerFragment: 20, + maxSourceRows: 25, + ioBufferSize: 0, + batchSize: 8, + }, + }); + expect(stats.compaction.fragmentsRemoved).toBe(2); + expect(stats.compaction.fragmentsAdded).toBe(1); + expect(await table.countRows()).toBe(80); + const defaults = await table.optimize(); + expect(defaults.compaction.fragmentsRemoved).toBe(7); + expect(defaults.compaction.fragmentsAdded).toBe(1); + expect(await table.countRows()).toBe(80); + }); + const invalid: CompactionOptions[] = [ + { targetRowsPerFragment: 0 }, + { maxSourceRows: 0 }, + { batchSize: 0 }, + { ioBufferSize: -1 }, + { batchSize: 1.5 }, + { maxSourceRows: Number.NaN }, + { ioBufferSize: Number.POSITIVE_INFINITY }, + { maxSourceRows: Number.MAX_SAFE_INTEGER + 1 }, + { targetRowsPerFragment: 2 ** 32 }, + { batchSize: 2 ** 32 }, + ]; + it.each(invalid)("rejects invalid settings %p", async (compactionOptions) => { + await expect(table.optimize({ compactionOptions })).rejects.toThrow( + /safe integer/, + ); + expect(await table.countRows()).toBe(80); + }); }); describe.each(arrowVersions)( @@ -4559,14 +4663,14 @@ describe.each(arrowVersions)( ]; const table = await db.createTable("prewarm_data_test", data); - // prewarmData is only supported in LanceDB Distributed. We verify the call + // 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 Distributed", + "prewarm_data is currently only supported in LanceDB Enterprise", ); await expect(table.prewarmData(["text"])).rejects.toThrow( - "prewarm_data is currently only supported in LanceDB Distributed", + "prewarm_data is currently only supported in LanceDB Enterprise", ); }); @@ -4973,6 +5077,44 @@ describe("column name options", () => { expect(results[0].camelCase).toBe(1); }); + test("can filter on an unquoted camelCase column", async () => { + const results = await table.query().where("camelCase = 1").toArray(); + expect(results[0].camelCase).toBe(1); + }); + + test("can update and delete by camelCase column", async () => { + await table.update({ where: "camelCase = 1", values: { camelCase: 2 } }); + expect(await table.query().where("camelCase = 2").toArray()).toHaveLength( + 1, + ); + await table.delete("camelCase = 2"); + expect(await table.countRows()).toBe(0); + }); + + test("can mergeInsert on a camelCase join key", async () => { + await table + .mergeInsert("camelCase") + .whenMatchedUpdateAll() + .whenNotMatchedInsertAll() + .execute([ + { camelCase: 1, vector: [0.3, 0.4] }, + { camelCase: 5, vector: [0.5, 0.6] }, + ]); + expect(await table.countRows()).toBe(2); + const inserted = await table.query().where("camelCase = 5").toArray(); + expect(inserted).toHaveLength(1); + }); + + test("can reference a camelCase column in addColumns sql", async () => { + await table.addColumns([{ name: "doubled", valueSql: "camelCase * 2" }]); + const results = await table.query().select(["doubled"]).toArray(); + expect(results[0].doubled).toBe(2); + }); + + test("can createIndex on a camelCase column", async () => { + await table.createIndex("camelCase"); + }); + test("can make multiple vector queries in one go", async () => { const results = await table .query() @@ -5535,11 +5677,22 @@ describe("computed columns", () => { expect(rows.map((r) => r.doubled).sort()).toEqual([2, 4]); }); + it("rejects Enterprise refresh options on local tables", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("refresh_options_local", [{ x: 1 }]); + await expect(table.refreshColumn("x", { where: "x > 0" })).rejects.toThrow( + "where requires a LanceDB Enterprise refresh", + ); + await expect( + table.refreshColumnAsync("x", { errorPolicy: "skip" }), + ).rejects.toThrow("error_policy requires a LanceDB Enterprise refresh"); + }); + it("records Function errors only on remote tables", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("errors_local", [{ x: 1 }]); await expect(table.functionErrors()).rejects.toThrow( - "recorded only in LanceDB Distributed", + "recorded only in LanceDB Enterprise", ); }); diff --git a/nodejs/examples/package.json b/nodejs/examples/package.json index c3f962b79..5b514aaf8 100644 --- a/nodejs/examples/package.json +++ b/nodejs/examples/package.json @@ -19,10 +19,10 @@ "license": "Apache-2.0", "packageManager": "pnpm@11.1.1", "dependencies": { - "@huggingface/transformers": "3.0.2", + "@huggingface/transformers": "4.3.2", "@lancedb/lancedb": "file:../dist", "openai": "4.29.2", - "sharp": "0.33.5" + "sharp": "0.35.5" }, "devDependencies": { "@biomejs/biome": "^1.7.3", diff --git a/nodejs/examples/pnpm-lock.yaml b/nodejs/examples/pnpm-lock.yaml index 6adbd99d1..408cf7ebb 100644 --- a/nodejs/examples/pnpm-lock.yaml +++ b/nodejs/examples/pnpm-lock.yaml @@ -9,8 +9,8 @@ importers: .: dependencies: '@huggingface/transformers': - specifier: 3.0.2 - version: 3.0.2 + specifier: 4.3.2 + version: 4.3.2(@types/node@25.7.0) '@lancedb/lancedb': specifier: file:../dist version: file:../dist @@ -18,8 +18,8 @@ importers: specifier: 4.29.2 version: 4.29.2 sharp: - specifier: 0.33.5 - version: 0.33.5 + specifier: 0.35.5 + version: 0.35.5(@types/node@25.7.0) devDependencies: '@biomejs/biome': specifier: ^1.7.3 @@ -264,137 +264,181 @@ packages: cpu: [x64] os: [win32] - '@emnapi/runtime@1.10.0': - resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==} + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} - '@huggingface/jinja@0.3.4': - resolution: {integrity: sha512-kFFQWJiWwvxezKQnvH1X7GjsECcMljFx+UZK9hx6P26aVHwwidJVTB0ptLfRVZQvVkOGHoMmTGvo4nT0X9hHOA==} + '@huggingface/jinja@0.5.11': + resolution: {integrity: sha512-YzEzwM5oQf4r0vs7ifWQ+yuVR1YkAHrjERQ+a8WRsStHHp4NRBg+NesjiFc+X2AFUpRvvrIeHDS1xFy9jY/IjQ==} engines: {node: '>=18'} - '@huggingface/transformers@3.0.2': - resolution: {integrity: sha512-lTyS81eQazMea5UCehDGFMfdcNRZyei7XQLH5X6j4AhA/18Ka0+5qPgMxUxuZLU4xkv60aY2KNz9Yzthv6WVJg==} + '@huggingface/tokenizers@0.2.0': + resolution: {integrity: sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==} - '@img/sharp-darwin-arm64@0.33.5': - resolution: {integrity: sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@huggingface/transformers@4.3.2': + resolution: {integrity: sha512-V3+dqf3iWlRYJ9I9GreM3zGQd0lAXnnoPeddmkOQYWAEE4l/+Fi6p7tx/qVUJlKQgLXGim2W76rTOzz+eC0i7g==} + + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} + engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] - '@img/sharp-darwin-x64@0.33.5': - resolution: {integrity: sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] - '@img/sharp-libvips-darwin-arm64@1.0.4': - resolution: {integrity: sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==} + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} + engines: {node: '>=20.9.0'} + os: [freebsd] + + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.0.4': - resolution: {integrity: sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==} + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] - '@img/sharp-libvips-linux-arm64@1.0.4': - resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==} + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-arm@1.0.5': - resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==} + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-s390x@1.0.4': - resolution: {integrity: sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==} + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-x64@1.0.4': - resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==} + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linuxmusl-arm64@1.0.4': - resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==} + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-libvips-linuxmusl-x64@1.0.4': - resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==} + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-linux-arm64@0.33.5': - resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} + engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-linux-arm@0.33.5': - resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} + engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-linux-s390x@0.33.5': - resolution: {integrity: sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} + engines: {node: '>=20.9.0'} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} + engines: {node: '>=20.9.0'} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} + engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-linux-x64@0.33.5': - resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-linuxmusl-arm64@0.33.5': - resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} + engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-linuxmusl-x64@0.33.5': - resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-wasm32@0.33.5': - resolution: {integrity: sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} + engines: {node: '>=20.9.0'} + + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} + engines: {node: '>=20.9.0'} cpu: [wasm32] - '@img/sharp-win32-ia32@0.33.5': - resolution: {integrity: sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} + engines: {node: ^20.9.0} cpu: [ia32] os: [win32] - '@img/sharp-win32-x64@0.33.5': - resolution: {integrity: sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] - '@isaacs/fs-minipass@4.0.1': - resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} - engines: {node: '>=18.0.0'} - '@istanbuljs/load-nyc-config@1.1.0': resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} engines: {node: '>=8'} @@ -573,6 +617,10 @@ packages: resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==} engines: {node: '>=6.5'} + adm-zip@0.6.1: + resolution: {integrity: sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==} + engines: {node: '>=14.0'} + agentkeepalive@4.6.0: resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==} engines: {node: '>= 8.0.0'} @@ -691,10 +739,6 @@ packages: charenc@0.0.2: resolution: {integrity: sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==} - chownr@3.0.0: - resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} - engines: {node: '>=18'} - ci-info@3.9.0: resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==} engines: {node: '>=8'} @@ -720,13 +764,6 @@ packages: color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} - color-string@1.9.1: - resolution: {integrity: sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==} - - color@4.2.3: - resolution: {integrity: sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==} - engines: {node: '>=12.5.0'} - combined-stream@1.0.8: resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} engines: {node: '>= 0.8'} @@ -770,6 +807,14 @@ packages: resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} engines: {node: '>=0.10.0'} + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + delayed-stream@1.0.0: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} @@ -830,6 +875,10 @@ packages: resolution: {integrity: sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==} engines: {node: '>=8'} + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + esprima@4.0.1: resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} engines: {node: '>=4'} @@ -865,8 +914,8 @@ packages: resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} engines: {node: '>=8'} - flatbuffers@1.12.0: - resolution: {integrity: sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==} + flatbuffers@25.9.23: + resolution: {integrity: sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==} form-data-encoder@1.7.2: resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==} @@ -918,6 +967,14 @@ packages: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + global-agent@4.1.6: + resolution: {integrity: sha512-V9u791atI/bS7RryfRTK2oixDWo6/RCrIikjwuQ4kADPRZZml1C6LUJXc7y6qRhaAF8geo3bIvE/siAGJCw38A==} + engines: {node: '>=10.0'} + + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + gopd@1.2.0: resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} engines: {node: '>= 0.4'} @@ -937,6 +994,9 @@ packages: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + has-symbols@1.1.0: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} @@ -978,9 +1038,6 @@ packages: is-arrayish@0.2.1: resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==} - is-arrayish@0.3.4: - resolution: {integrity: sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==} - is-buffer@1.1.6: resolution: {integrity: sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==} @@ -1218,6 +1275,10 @@ packages: makeerror@1.0.12: resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==} + matcher@4.0.0: + resolution: {integrity: sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==} + engines: {node: '>=10'} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -1250,14 +1311,6 @@ packages: minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - minipass@7.1.3: - resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} - engines: {node: '>=16 || 14 >=14.17'} - - minizlib@3.1.0: - resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} - engines: {node: '>= 18'} - ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -1295,6 +1348,10 @@ packages: resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} engines: {node: '>=8'} + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} @@ -1302,18 +1359,18 @@ packages: resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} engines: {node: '>=6'} - onnxruntime-common@1.19.2: - resolution: {integrity: sha512-a4R7wYEVFbZBlp0BfhpbFWqe4opCor3KM+5Wm22Az3NGDcQMiU2hfG/0MfnBs+1ZrlSGmlgWeMcXQkDk1UFb8Q==} + onnxruntime-common@1.30.0: + resolution: {integrity: sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==} - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: - resolution: {integrity: sha512-KZK8b6zCYGZFjd4ANze0pqBnqnFTS3GIVeclQpa2qseDpXrCQJfkWBixRcrZShNhm3LpFOZ8qJYFC5/qsJK9WQ==} + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: + resolution: {integrity: sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==} - onnxruntime-node@1.19.2: - resolution: {integrity: sha512-9eHMP/HKbbeUcqte1JYzaaRC8JPn7ojWeCeoyShO86TOR97OCyIyAIOGX3V95ErjslVhJRXY8Em/caIUc0hm1Q==} + onnxruntime-node@1.30.0: + resolution: {integrity: sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==} os: [win32, darwin, linux] - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: - resolution: {integrity: sha512-ANSQfMALvCviN3Y4tvTViKofKToV1WUb2r2VjZVCi3uUBPaK15oNJyIxhsNyEckBr/Num3JmSXlkHOD8HfVzSQ==} + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: + resolution: {integrity: sha512-Iy7rtadoBgxS/LLvDr3QW38DB1PNXRnr0GJMcL0TAt7c9qjgVQl83UlGCVyeAnK2InpmW8Uc3PL8XIuqtDeF6g==} openai@4.29.2: resolution: {integrity: sha512-cPkT6zjEcE4qU5OW/SoDDuXEsdOLrXlAORhzmaguj5xZSPlgKvLhi27sFWhLKj07Y6WKNWxcwIbzm512FzTBNQ==} @@ -1415,14 +1472,23 @@ packages: resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} hasBin: true - semver@7.8.0: - resolution: {integrity: sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==} + semver@7.8.6: + resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} engines: {node: '>=10'} hasBin: true - sharp@0.33.5: - resolution: {integrity: sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + serialize-error@8.1.0: + resolution: {integrity: sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==} + engines: {node: '>=10'} + + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} + engines: {node: '>=20.9.0'} + peerDependencies: + '@types/node': '*' + peerDependenciesMeta: + '@types/node': + optional: true shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} @@ -1435,9 +1501,6 @@ packages: signal-exit@3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} - simple-swizzle@0.2.4: - resolution: {integrity: sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==} - sisteransi@1.0.5: resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} @@ -1495,10 +1558,6 @@ packages: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} - tar@7.5.15: - resolution: {integrity: sha512-dzGK0boVlC4W5QFuQN1EFSl3bIDYsk7Tj40U6eIBnK2k/8ml7TZ5agbI5j5+qnoVcAA+rNtBml8SEiLxZpNqRQ==} - engines: {node: '>=18'} - test-exclude@6.0.0: resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==} engines: {node: '>=8'} @@ -1547,6 +1606,10 @@ packages: resolution: {integrity: sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==} engines: {node: '>=4'} + type-fest@0.20.2: + resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==} + engines: {node: '>=10'} + type-fest@0.21.3: resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==} engines: {node: '>=10'} @@ -1624,10 +1687,6 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} - yallist@5.0.0: - resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} - engines: {node: '>=18'} - yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} @@ -1866,98 +1925,130 @@ snapshots: '@biomejs/cli-win32-x64@1.9.4': optional: true - '@emnapi/runtime@1.10.0': + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 optional: true - '@huggingface/jinja@0.3.4': {} + '@huggingface/jinja@0.5.11': {} - '@huggingface/transformers@3.0.2': + '@huggingface/tokenizers@0.2.0': {} + + '@huggingface/transformers@4.3.2(@types/node@25.7.0)': dependencies: - '@huggingface/jinja': 0.3.4 - onnxruntime-node: 1.19.2 - onnxruntime-web: 1.21.0-dev.20241024-d9ca84ef96 - sharp: 0.33.5 + '@huggingface/jinja': 0.5.11 + '@huggingface/tokenizers': 0.2.0 + onnxruntime-node: 1.30.0 + onnxruntime-web: 1.31.0-dev.20260914-8d85527a0 + sharp: 0.35.5(@types/node@25.7.0) + transitivePeerDependencies: + - '@types/node' - '@img/sharp-darwin-arm64@0.33.5': + '@img/colour@1.1.0': {} + + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.0.4 + '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true - '@img/sharp-darwin-x64@0.33.5': + '@img/sharp-darwin-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.0.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true - '@img/sharp-libvips-darwin-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-darwin-x64@1.0.4': - optional: true - - '@img/sharp-libvips-linux-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-linux-arm@1.0.5': - optional: true - - '@img/sharp-libvips-linux-s390x@1.0.4': - optional: true - - '@img/sharp-libvips-linux-x64@1.0.4': - optional: true - - '@img/sharp-libvips-linuxmusl-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-linuxmusl-x64@1.0.4': - optional: true - - '@img/sharp-linux-arm64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.0.4 - optional: true - - '@img/sharp-linux-arm@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.0.5 - optional: true - - '@img/sharp-linux-s390x@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.0.4 - optional: true - - '@img/sharp-linux-x64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.0.4 - optional: true - - '@img/sharp-linuxmusl-arm64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.0.4 - optional: true - - '@img/sharp-linuxmusl-x64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.0.4 - optional: true - - '@img/sharp-wasm32@0.33.5': + '@img/sharp-freebsd-wasm32@0.35.5': dependencies: - '@emnapi/runtime': 1.10.0 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-win32-ia32@0.33.5': + '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true - '@img/sharp-win32-x64@0.33.5': + '@img/sharp-libvips-darwin-x64@1.3.4': optional: true - '@isaacs/fs-minipass@4.0.1': + '@img/sharp-libvips-linux-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-arm@1.3.4': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-s390x@1.3.4': + optional: true + + '@img/sharp-libvips-linux-x64@1.3.4': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + optional: true + + '@img/sharp-linux-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.3.4 + optional: true + + '@img/sharp-linux-arm@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.3.4 + optional: true + + '@img/sharp-linux-ppc64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.3.4 + optional: true + + '@img/sharp-linux-riscv64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.3.4 + optional: true + + '@img/sharp-linux-s390x@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.3.4 + optional: true + + '@img/sharp-linux-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.3.4 + optional: true + + '@img/sharp-linuxmusl-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + optional: true + + '@img/sharp-linuxmusl-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + optional: true + + '@img/sharp-wasm32@0.35.5': dependencies: - minipass: 7.1.3 + '@emnapi/runtime': 1.11.3 + optional: true + + '@img/sharp-webcontainers-wasm32@0.35.5': + dependencies: + '@img/sharp-wasm32': 0.35.5 + optional: true + + '@img/sharp-win32-arm64@0.35.5': + optional: true + + '@img/sharp-win32-ia32@0.35.5': + optional: true + + '@img/sharp-win32-x64@0.35.5': + optional: true '@istanbuljs/load-nyc-config@1.1.0': dependencies: @@ -2222,7 +2313,7 @@ snapshots: '@types/node-fetch@2.6.13': dependencies: - '@types/node': 18.19.130 + '@types/node': 25.7.0 form-data: 4.0.5 '@types/node@18.19.130': @@ -2245,6 +2336,8 @@ snapshots: dependencies: event-target-shim: 5.0.1 + adm-zip@0.6.1: {} + agentkeepalive@4.6.0: dependencies: humanize-ms: 1.2.1 @@ -2382,8 +2475,6 @@ snapshots: charenc@0.0.2: {} - chownr@3.0.0: {} - ci-info@3.9.0: {} cjs-module-lexer@1.4.3: {} @@ -2404,16 +2495,6 @@ snapshots: color-name@1.1.4: {} - color-string@1.9.1: - dependencies: - color-name: 1.1.4 - simple-swizzle: 0.2.4 - - color@4.2.3: - dependencies: - color-convert: 2.0.1 - color-string: 1.9.1 - combined-stream@1.0.8: dependencies: delayed-stream: 1.0.0 @@ -2453,6 +2534,18 @@ snapshots: deepmerge@4.3.1: {} + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + delayed-stream@1.0.0: {} detect-libc@2.1.2: {} @@ -2501,6 +2594,8 @@ snapshots: escape-string-regexp@2.0.0: {} + escape-string-regexp@4.0.0: {} + esprima@4.0.1: {} event-target-shim@5.0.1: {} @@ -2542,7 +2637,7 @@ snapshots: locate-path: 5.0.0 path-exists: 4.0.0 - flatbuffers@1.12.0: {} + flatbuffers@25.9.23: {} form-data-encoder@1.7.2: {} @@ -2601,6 +2696,18 @@ snapshots: once: 1.4.0 path-is-absolute: 1.0.1 + global-agent@4.1.6: + dependencies: + globalthis: 1.0.4 + matcher: 4.0.0 + semver: 7.8.6 + serialize-error: 8.1.0 + + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + gopd@1.2.0: {} graceful-fs@4.2.11: {} @@ -2618,6 +2725,10 @@ snapshots: has-flag@4.0.0: {} + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + has-symbols@1.1.0: {} has-tostringtag@1.0.2: @@ -2652,8 +2763,6 @@ snapshots: is-arrayish@0.2.1: {} - is-arrayish@0.3.4: {} - is-buffer@1.1.6: {} is-core-module@2.16.2: @@ -2688,7 +2797,7 @@ snapshots: '@babel/parser': 7.29.3 '@istanbuljs/schema': 0.1.6 istanbul-lib-coverage: 3.2.2 - semver: 7.8.0 + semver: 7.8.6 transitivePeerDependencies: - supports-color @@ -2971,7 +3080,7 @@ snapshots: jest-util: 29.7.0 natural-compare: 1.4.0 pretty-format: 29.7.0 - semver: 7.8.0 + semver: 7.8.6 transitivePeerDependencies: - supports-color @@ -3056,7 +3165,7 @@ snapshots: make-dir@4.0.0: dependencies: - semver: 7.8.0 + semver: 7.8.6 make-error@1.3.6: {} @@ -3064,6 +3173,10 @@ snapshots: dependencies: tmpl: 1.0.5 + matcher@4.0.0: + dependencies: + escape-string-regexp: 4.0.0 + math-intrinsics@1.1.0: {} md5@2.3.0: @@ -3093,12 +3206,6 @@ snapshots: minimist@1.2.8: {} - minipass@7.1.3: {} - - minizlib@3.1.0: - dependencies: - minipass: 7.1.3 - ms@2.1.3: {} natural-compare@1.4.0: {} @@ -3121,6 +3228,8 @@ snapshots: dependencies: path-key: 3.1.1 + object-keys@1.1.1: {} + once@1.4.0: dependencies: wrappy: 1.0.2 @@ -3129,21 +3238,22 @@ snapshots: dependencies: mimic-fn: 2.1.0 - onnxruntime-common@1.19.2: {} + onnxruntime-common@1.30.0: {} - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: {} + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: {} - onnxruntime-node@1.19.2: + onnxruntime-node@1.30.0: dependencies: - onnxruntime-common: 1.19.2 - tar: 7.5.15 + adm-zip: 0.6.1 + global-agent: 4.1.6 + onnxruntime-common: 1.30.0 - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: dependencies: - flatbuffers: 1.12.0 + flatbuffers: 25.9.23 guid-typescript: 1.0.9 long: 5.3.2 - onnxruntime-common: 1.20.0-dev.20241016-2b8fc5529b + onnxruntime-common: 1.31.0-dev.20260911-2a43ec07e platform: 1.3.6 protobufjs: 7.5.7 @@ -3251,33 +3361,44 @@ snapshots: semver@6.3.1: {} - semver@7.8.0: {} + semver@7.8.6: {} - sharp@0.33.5: + serialize-error@8.1.0: dependencies: - color: 4.2.3 + type-fest: 0.20.2 + + sharp@0.35.5(@types/node@25.7.0): + dependencies: + '@img/colour': 1.1.0 detect-libc: 2.1.2 - semver: 7.8.0 + semver: 7.8.6 optionalDependencies: - '@img/sharp-darwin-arm64': 0.33.5 - '@img/sharp-darwin-x64': 0.33.5 - '@img/sharp-libvips-darwin-arm64': 1.0.4 - '@img/sharp-libvips-darwin-x64': 1.0.4 - '@img/sharp-libvips-linux-arm': 1.0.5 - '@img/sharp-libvips-linux-arm64': 1.0.4 - '@img/sharp-libvips-linux-s390x': 1.0.4 - '@img/sharp-libvips-linux-x64': 1.0.4 - '@img/sharp-libvips-linuxmusl-arm64': 1.0.4 - '@img/sharp-libvips-linuxmusl-x64': 1.0.4 - '@img/sharp-linux-arm': 0.33.5 - '@img/sharp-linux-arm64': 0.33.5 - '@img/sharp-linux-s390x': 0.33.5 - '@img/sharp-linux-x64': 0.33.5 - '@img/sharp-linuxmusl-arm64': 0.33.5 - '@img/sharp-linuxmusl-x64': 0.33.5 - '@img/sharp-wasm32': 0.33.5 - '@img/sharp-win32-ia32': 0.33.5 - '@img/sharp-win32-x64': 0.33.5 + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 + '@types/node': 25.7.0 shebang-command@2.0.0: dependencies: @@ -3287,10 +3408,6 @@ snapshots: signal-exit@3.0.7: {} - simple-swizzle@0.2.4: - dependencies: - is-arrayish: 0.3.4 - sisteransi@1.0.5: {} slash@3.0.0: {} @@ -3339,14 +3456,6 @@ snapshots: supports-preserve-symlinks-flag@1.0.0: {} - tar@7.5.15: - dependencies: - '@isaacs/fs-minipass': 4.0.1 - chownr: 3.0.0 - minipass: 7.1.3 - minizlib: 3.1.0 - yallist: 5.0.0 - test-exclude@6.0.0: dependencies: '@istanbuljs/schema': 0.1.6 @@ -3370,7 +3479,7 @@ snapshots: json5: 2.2.3 lodash.memoize: 4.1.2 make-error: 1.3.6 - semver: 7.8.0 + semver: 7.8.6 type-fest: 4.41.0 typescript: 5.9.3 yargs-parser: 21.1.1 @@ -3386,6 +3495,8 @@ snapshots: type-detect@4.0.8: {} + type-fest@0.20.2: {} + type-fest@0.21.3: {} type-fest@4.41.0: {} @@ -3449,8 +3560,6 @@ snapshots: yallist@3.1.1: {} - yallist@5.0.0: {} - yargs-parser@21.1.1: {} yargs@17.7.2: diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index 56c8e1897..f920eecb8 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -1386,7 +1386,9 @@ export async function fromBufferToRecordBatch( export async function fromRecordBatchToBuffer( batch: RecordBatch, ): Promise { - const writer = new RecordBatchFileWriter().writeAll([batch]); + // Arrow writers require data types from their own library instance. + const table = sanitizeTable({ schema: batch.schema, batches: [batch] }); + const writer = new RecordBatchFileWriter().writeAll(table); return Buffer.from(await writer.toUint8Array()); } diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index 4cfcaf990..67e662175 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -274,7 +274,7 @@ export class BlobFile { export type BlobReadOptions = { /** * Cancels the read. The call rejects with `signal.reason`, and the native - * read stops, including in-flight requests to a LanceDB Distributed table. + * read stops, including in-flight requests to a LanceDB Enterprise table. */ signal?: AbortSignal; }; diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index d5a856894..9c83d833f 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -272,7 +272,7 @@ export abstract class Connection { * * LanceDB Embedded creation and refresh require a source build with the * `experimental-functions` Cargo feature, disabled in published packages. - * LanceDB Distributed operations do not require this feature. + * LanceDB Enterprise operations do not require this feature. * * The view is populated before creation returns. Set `withNoData` to create * only its definition and empty backing table. The view is a normal table: @@ -356,19 +356,18 @@ export abstract class Connection { ): Promise; /** - * Drop the view named `name` and wait for its definition to be deleted. + * Drop the view named `name` and wait for catalog removal. * * The tables it reads are untouched: a view holds no rows of its own. Use - * {@link dropViewAsync} to retain the cleanup job instead of waiting on it. + * {@link dropViewAsync} to retain its SQL query job. Completion confirms + * catalog removal; physical cleanup continues in the background. */ abstract dropView(name: string, namespacePath?: string[]): Promise; /** - * Start dropping the view named `name` and return the job deleting its - * definition, without waiting for completion. - * - * The name is free before this resolves. When nothing was bound to it, the - * returned job is already finished and has no id. + * Drop a view and return its SQL query job. + * The job has type `query` and its ID is the SQL query UUID. Waiting confirms + * catalog removal; physical cleanup continues in the background. */ abstract dropViewAsync(name: string, namespacePath?: string[]): Promise; @@ -559,9 +558,10 @@ export abstract class Connection { /** * Rename a table. * - * Currently only supported in LanceDB Distributed. LanceDB Embedded connections and - * namespace-backed connections (via {@link connectNamespace}) reject with - * a "not supported" error. + * Supported in LanceDB Enterprise and by namespace backends that implement + * renaming. Directory namespaces support renaming tables resolved through their + * manifest, including tables within or across child namespaces. LanceDB Embedded + * connections and directory-listing root tables reject with a "not supported" error. * * @param {string} currentName - The current name of the table. * @param {string} newName - The new name for the table. diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 52f94f554..9644b0060 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -56,6 +56,7 @@ export { MergeResult, AddResult, AddColumnsResult, + RefreshColumnOptions, RefreshColumnResult, FunctionErrors, FunctionErrorsOptions, @@ -108,7 +109,11 @@ export { export { JobFailureInfo, JobInfo, Session } from "./native.js"; -export { Job, JobEventsOptions } from "./job"; +export { + Job, + JobEventsOptions, +} from "./job"; +export type { JobProgress, JobProgressCallback } from "./job"; export { AutoQuery, @@ -160,6 +165,7 @@ export { AddDataOptions, UpdateOptions, OptimizeOptions, + CompactionOptions, Version, WriteProgress, FtsToken, diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts index 4b1b422bf..53cbf8a4d 100644 --- a/nodejs/lancedb/indices.ts +++ b/nodejs/lancedb/indices.ts @@ -816,7 +816,7 @@ export class Index { * Create a label list index. * * LabelList index is a scalar index that can be used on `List` columns to - * support queries with `array_contains_all` and `array_contains_any` + * support queries with `array_has_all` and `array_has_any` * using an underlying bitmap index. */ static labelList() { @@ -939,7 +939,10 @@ export interface IndexOptions { /** * Timeout in seconds to wait for index creation to complete. * - * If not specified, the method will return immediately after starting the index creation. + * Only applies to LanceDB Enterprise tables, which build the index in the + * background. + * If not specified, `createIndex` returns once the build is scheduled. + * LanceDB Embedded tables always build the index before `createIndex` returns. */ waitTimeoutSeconds?: number; diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index 1c8d74ad2..f38d8d7fa 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -12,6 +12,48 @@ export interface JobEventsOptions { filter?: string; } +/** + * A forward-compatible structured progress snapshot for a server-side job. + * + * Fields are optional because older servers and different job types report + * different counters. A missing counter is unknown; it is not zero. + */ +export interface JobProgress { + /** Lifecycle state, including states from newer servers. */ + state?: string; + /** Coarse server-derived phase, including phases from newer servers. */ + phase?: string | null; + /** Whether an operator has parked the job. */ + paused?: boolean; + /** + * Planned, computed, skipped, remaining, and failed row counters, when the + * server reports them. + */ + // biome-ignore lint/style/useNamingConvention: server wire format + rows_planned?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + rows_computed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + rows_skipped?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + rows_remaining?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + rows_failed?: 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; + // biome-ignore lint/style/useNamingConvention: server wire format + sample_at_millis?: number | null; + /** Best-effort remaining milliseconds, present only for a reliable sample. */ + // biome-ignore lint/style/useNamingConvention: server wire format + estimated_remaining_time_millis?: number; + /** Retain job-type-specific and newer-server fields without interpretation. */ + [field: string]: unknown; +} + +/** Callback for progress snapshots observed while waiting for a job. */ +export type JobProgressCallback = (progress: JobProgress) => void; + /** * A handle to an operation that may still be running. * @@ -98,9 +140,39 @@ export class Job { return this.inner.status(); } - /** Wait until the operation reaches a terminal state. */ - async wait(): Promise { - return this.inner.wait(); + /** + * Fetch a structured progress snapshot. + * + * Registry jobs include lifecycle and queue metadata even when their job + * type does not report counters. The returned object is forward-compatible + * with newer servers and job types. In-process operations return null. + */ + async progress(): Promise { + const progress = await this.inner.progress(); + return progress === null ? null : this.enrichProgress(progress); + } + + /** + * Wait until the operation reaches a terminal state. + * + * The optional callback observes the same snapshots fetched by the backend + * poller that drives completion; it does not start another poller. Without a + * callback, this preserves the original wait behavior. The callback is a + * 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`. + */ + async wait(progressCallback?: JobProgressCallback): Promise { + if (progressCallback === undefined) { + return this.inner.wait(); + } + return this.inner.wait((progress) => { + try { + progressCallback(this.enrichProgress(progress)); + } catch (error) { + console.warn("Job progress callback threw:", error); + } + }); } /** Request cancellation. Cancelling a finished operation is a no-op. */ @@ -138,6 +210,17 @@ export class Job { return tableFromIPC(buf); } + private lastProgress: JobProgress | null = null; + + private enrichProgress(progress: Record): JobProgress { + const enriched = withProgressEta( + this.lastProgress, + progress as JobProgress, + ); + this.lastProgress = enriched; + return enriched; + } + /** * Every field the handle currently knows, one per line, with the JSON * payloads indented -- a refresh job's spec and result are the point of @@ -180,6 +263,108 @@ export class Job { const REPR_INDENT = " "; +const ETA_MAX_SAMPLE_INTERVAL_MILLIS = 10 * 60 * 1_000; + +function withProgressEta( + previous: JobProgress | null, + current: JobProgress, +): JobProgress { + const snapshot = { ...current }; + const estimate = progressEta(previous, current); + if (estimate !== null) { + snapshot.estimated_remaining_time_millis = estimate; + } + return snapshot; +} + +function progressEta( + previous: JobProgress | null, + current: JobProgress, +): number | null { + if ( + previous === null || + (current.state !== "running" && current.state !== "finished") + ) { + return null; + } + const remaining = integerValue(current.rows_remaining); + if (current.state === "finished") { + return remaining === 0 ? 0 : null; + } + if ( + current.paused === true || + previous.paused === true || + isTransitionalPhase(current.phase) || + isTransitionalPhase(previous.phase) + ) { + return null; + } + const epoch = integerValue(current.execution_epoch); + const previousEpoch = integerValue(previous.execution_epoch); + if (epoch === null || previousEpoch !== epoch) { + return null; + } + const sampleAt = integerValue(current.sample_at_millis); + const previousAt = integerValue(previous.sample_at_millis); + if (sampleAt === null || previousAt === null) { + return null; + } + const elapsed = sampleAt - previousAt; + if ( + elapsed <= 0 || + elapsed > ETA_MAX_SAMPLE_INTERVAL_MILLIS || + Date.now() - sampleAt > ETA_MAX_SAMPLE_INTERVAL_MILLIS + ) { + return null; + } + const planned = integerValue(current.rows_planned); + const currentRemaining = integerValue(current.rows_remaining); + const previousRemaining = integerValue(previous.rows_remaining); + if ( + planned === null || + currentRemaining === null || + previousRemaining === null + ) { + return null; + } + if (currentRemaining === 0) { + return 0; + } + if (planned !== previous.rows_planned) { + return null; + } + if (current.fragments_planned !== previous.fragments_planned) { + return null; + } + const currentComputed = integerValue(current.rows_computed); + const previousComputed = integerValue(previous.rows_computed); + if (currentComputed === null || previousComputed === null) { + return null; + } + const currentAccounted = + currentComputed + (integerValue(current.rows_skipped) ?? 0); + const previousAccounted = + previousComputed + (integerValue(previous.rows_skipped) ?? 0); + const advanced = currentAccounted - previousAccounted; + if (advanced <= 0 || currentRemaining > previousRemaining) { + return null; + } + return Math.floor((currentRemaining * elapsed) / advanced); +} + +function integerValue(value: unknown): number | null { + return typeof value === "number" && Number.isInteger(value) ? value : null; +} + +function isTransitionalPhase(phase: unknown): boolean { + return ( + phase === "queued" || + phase === "starting" || + phase === "initializing" || + phase === "paused" + ); +} + // biome-ignore lint/suspicious/noExplicitAny: shape varies by job type function indentJson(value: any): string { return JSON.stringify(value, null, 4).replace(/\n/g, `\n${REPR_INDENT}`); diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index 27133a326..bb845276f 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -237,6 +237,9 @@ export interface QueryExecutionOptions { /** * Timeout for query execution in milliseconds + * + * The timeout also covers reading the results, so consuming them slowly can + * exceed it. */ timeoutMs?: number; @@ -854,6 +857,11 @@ export class VectorQuery extends StandardQueryBase { /** * Set the initial IVF search effort to a finite value in [0, 1]. * + * Efforts 0.1 and 0.25 target empirical mean partition-routing recall of + * 80% and 90% for L2, cosine and dot through k=100000. The probe budget + * adapts to the metric and k. Hamming and larger k remain uncalibrated; + * 100000 is not an API limit. Remote queries also require server support. + * * The default, null, uses Auto (internally 0.5). Zero starts at the caller * minimum; one searches all partitions within the caller maximum. Later * probing may continue when too few candidates are found. @@ -926,6 +934,27 @@ export class VectorQuery extends StandardQueryBase { return this; } + /** + * Set the speed / accuracy tradeoff to use for approximate search + * + * This currently affects RQ-quantized indexes, such as IVF_RQ, and + * prefiltered search on HNSW indexes, where "fast" enables the ACORN + * traversal. Other index types ignore this setting. + * + * "fast" favors lower latency and may reduce recall, "normal" (the default) + * uses the index's default balance, and "accurate" favors higher recall and + * may increase latency. + * + * @example + * ```ts + * table.vectorSearch([0.1, 0.2]).approxMode("fast").limit(10); + * ``` + */ + approxMode(approxMode: "fast" | "normal" | "accurate"): VectorQuery { + super.doCall((inner) => inner.approxMode(approxMode)); + return this; + } + /** * Set the vector column to query * diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 0806f7c6d..5ef298c8c 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -38,6 +38,7 @@ import { Branches as NativeBranches, OptimizeStats, RTEStats, + RefreshColumnOptions, RefreshColumnResult, RefreshMaterializedViewResult, TableStatistics, @@ -129,7 +130,7 @@ export interface AddDataOptions { * Whether blob URIs outside registered external bases may be written. * * Defaults to `false`. This option is supported only in LanceDB Embedded; - * LanceDB Distributed returns an error when it is enabled. An enabled write + * LanceDB Enterprise returns an error when it is enabled. An enabled write * stores the absolute URI reference without registering a base or copying * the external object into the database. The object must remain accessible * when the blob is read later. @@ -151,7 +152,31 @@ export interface UpdateOptions { where: string; } +/** Per-invocation compaction settings. Values must be safe integers. */ +export interface CompactionOptions { + /** Positive target rows per output fragment; also affects candidate selection. */ + targetRowsPerFragment?: number; + /** Positive live-source-row budget across whole tasks; an oversized first task can produce no work. */ + maxSourceRows?: number; + /** Scanner I/O read-ahead budget in bytes; zero disables byte-based I/O backpressure. */ + ioBufferSize?: number; + /** Positive scanner batch size in rows. */ + batchSize?: number; +} + export interface OptimizeOptions { + /** + * Compaction settings for this invocation. Omitted remote values inherit table + * tuning, then deployment/built-in defaults. + * Remote tables require a server supporting these SQL options; settings do + * not change table policy. This is not a runtime or total-memory limit. + * @example + * await tbl.optimize({ compactionOptions: { + * targetRowsPerFragment: 1000, maxSourceRows: 5000, + * ioBufferSize: 64 * 1024 * 1024, batchSize: 128, + * } }); + */ + compactionOptions?: CompactionOptions; /** * If set then all versions older than the given date * be removed. The current version will never be removed. @@ -365,6 +390,24 @@ export abstract class Table { * We currently don't support custom named indexes. * The index name will always be `${column}_idx`. * + * On LanceDB Embedded tables the index is built before the returned promise + * resolves. On LanceDB Enterprise tables it resolves once the build is + * scheduled. Until the build finishes, a vector index may be missing from + * {@link Table.listIndices}, a scalar or FTS index may be listed with 0 + * indexed rows, and queries won't use the index. To wait until the index is + * ready, set {@link IndexOptions.waitTimeoutSeconds}, call + * {@link Table.waitForIndex}, or use {@link Table.createIndexAsync} and wait + * on its job when the server returned a job ID. + * + * `waitTimeoutSeconds` waits for the submitted build when the server returns + * a job ID. On older servers that don't return one, it falls back to polling + * the index by name. {@link Table.waitForIndex} always waits by name. When + * replacing an existing index, those name-based waits may return before the + * new build finishes because the old index can still match. + * `createIndexAsync` can track a specific build only when the server returned + * a job ID; otherwise it returns an already-complete job and callers must + * use {@link Table.waitForIndex} for that build. + * * @example * // If the column has a vector (fixed size list) data type then * // an IvfPq vector index will be created. @@ -399,6 +442,11 @@ export abstract class Table { * * The job may already be complete when returned; callers must not assume * the index exists until {@link Job.wait} resolves. + * + * In LanceDB Enterprise, the returned job tracks this submission only if the + * server returns a job ID. If it does not, the job is already complete and + * does not wait for the background build; use {@link Table.waitForIndex} and + * account for the replacement caveat described in {@link Table.createIndex}. */ abstract createIndexAsync( column: string, @@ -443,7 +491,7 @@ export abstract class Table { * Large columns (e.g. high-dimensional vectors or binary data) may not be * practical to prewarm. * - * This feature is currently only supported in LanceDB Distributed. + * This feature is currently only supported in LanceDB Enterprise. */ abstract prewarmData(columns?: string[]): Promise; @@ -601,7 +649,7 @@ export abstract class Table { * * LanceDB Embedded computed-column declaration and refresh require a source * build with the `experimental-functions` Cargo feature. Published packages - * disable it; LanceDB Distributed operations remain available. + * disable it; LanceDB Enterprise operations remain available. * * The `{ computed }` form stores the expression rather than evaluating it * now: the column is committed with no values, and rows get them from @@ -613,7 +661,7 @@ export abstract class Table { * declaration reads a column, that column cannot be renamed, retyped or * dropped. * - * In LanceDB Distributed the expression is planned by the + * In LanceDB Enterprise the expression is planned by the * server, and the refresh runs as a server job -- see * {@link Table#refreshColumnAsync}. * @param {AddColumnsSql[] | Field | Field[] | Schema} newColumnTransforms Either: @@ -646,34 +694,55 @@ export abstract class Table { * Rows appended since the last refresh are filled by the next one, and * rows whose inputs changed since they were computed are recomputed; * everything else is left as it is. LanceDB Embedded only: in LanceDB - * Distributed a refresh runs as a server job, through {@link Table#refreshColumnAsync}. + * Enterprise a refresh runs as a server job, through {@link Table#refreshColumnAsync}. * @param {string} column The name of the computed column to fill. + * @param {RefreshColumnOptions} options Refresh options, all LanceDB + * Enterprise only; see {@link Table#refreshColumnAsync}. * @returns {Promise} A promise that resolves to the * number of rows filled and the new version number of the table. */ - abstract refreshColumn(column: string): Promise; + abstract refreshColumn( + column: string, + options?: RefreshColumnOptions, + ): Promise; /** * Like {@link Table#refreshColumn}, but returns a handle to the refresh * job instead of blocking until it completes. * LanceDB Embedded refresh requires a source build with - * `experimental-functions`. LanceDB Distributed jobs do not require this + * `experimental-functions`. LanceDB Enterprise jobs do not require this * feature. * * The job may already be complete when returned; callers must not assume * the column is filled until {@link Job.wait} resolves. Invalid input -- * an unknown column, or one that is not computed -- rejects here rather * than failing the job. In LanceDB Embedded the job runs in-process; in - * LanceDB Distributed it is the server's backfill job. + * LanceDB Enterprise it is the server's backfill job. * @param {string} column The name of the computed column to fill. + * @param {RefreshColumnOptions} options Refresh options, mirroring the SQL + * `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, + * `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` + * and `initTimeoutSeconds` govern failing rows, and `batchSize`, + * `gpuClass`, `gpuCount`, `numWorkers` and `maxExecutorProcessesPerWorker` + * size the workers. All are LanceDB Enterprise only; a LanceDB Embedded + * refresh rejects every option other than `batchSize`, `gpuClass` and + * `gpuCount`. * @example * ```ts - * const job = await table.refreshColumnAsync("doubled"); + * const job = await table.refreshColumnAsync("embedding", { + * where: "published_at > '2026-01-01'", + * errorPolicy: "skip", + * maxFailedFraction: 0.01, + * rowTimeoutSeconds: 30, + * }); * await job.wait(); * console.log(await job.status()); // "finished" * ``` */ - abstract refreshColumnAsync(column: string): Promise; + abstract refreshColumnAsync( + column: string, + options?: RefreshColumnOptions, + ): Promise; /** * The per-row errors Function refreshes recorded on this table. @@ -681,7 +750,7 @@ export abstract class 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 Distributed only; reading errors needs read + * capped. LanceDB Enterprise only; reading errors needs read * access to the table, since a message carries the value that failed. * @param {FunctionErrorsOptions} options Optional filters: `jobId`, * `column`, and `limit` (server default 10000, cap 100000). @@ -713,6 +782,9 @@ export abstract class Table { /** * Alter the name or nullability of columns. + * + * Local tables reject renaming source or vector columns referenced by + * `embedding_functions` schema metadata, preserving the embedding binding. * @param {ColumnAlteration[]} columnAlterations One or more alterations to * apply to columns. * @returns {Promise} A promise that resolves to an object @@ -750,6 +822,9 @@ export abstract class Table { * underlying storage. In order to remove the data, you must subsequently * call ``compact_files`` to rewrite the data without the removed columns and * then call ``cleanup_files`` to remove the old files. + * + * Local tables reject dropping source or vector columns referenced by + * `embedding_functions` schema metadata, preserving the embedding binding. * @param {string[]} columnNames The names of the columns to drop. These can * be nested column references (e.g. "a.b.c") or top-level column names * (e.g. "a"). @@ -990,9 +1065,25 @@ export abstract class Table { * optimize should be run frequently. A good rule of thumb is to run optimize if * you have added or modified 100,000 or more records or run more than 20 data * modification operations. + * + * On a LanceDB Enterprise (remote) table, only compaction is currently + * supported. Pruning old versions and index optimization are silently + * skipped there instead of being attempted, so this call resolves + * successfully, with zeroed pruning statistics, once the compaction job + * has been submitted; it does not wait for that job to finish. + * `compactionOptions` can tune the four per-job settings documented in + * {@link CompactionOptions}. Older-server errors are propagated without + * retrying with the settings removed. */ abstract optimize(options?: Partial): Promise; - /** List all indices that have been created with {@link Table.createIndex} */ + /** + * List all indices that have been created with {@link Table.createIndex} + * + * On LanceDB Enterprise tables, an index whose build hasn't finished may be + * missing (vector indices) or listed with 0 indexed rows (scalar and FTS + * indices), and `numUnindexedRows` may be undefined. Use + * {@link Table.waitForIndex} to wait until an index is ready. + */ abstract listIndices(): Promise; /** * Tokenize a full-text search query using the tokenizer configured on an FTS index. @@ -1000,7 +1091,7 @@ export abstract class Table { * Specify exactly one of `column` or `indexName`. * * Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in - * the client process from index metadata. In LanceDB Distributed, this means the + * the client process from index metadata. In LanceDB Enterprise, this means the * same tokenizer model files must also exist locally (under * `LANCE_LANGUAGE_MODEL_HOME`) and must match the files the server uses. A * mismatch cannot be detected: the returned tokens may differ from what the @@ -1430,12 +1521,18 @@ export class LocalTable extends Table { throw new Error("Invalid input type for addColumns"); } - async refreshColumn(column: string): Promise { - return await this.inner.refreshColumn(column); + async refreshColumn( + column: string, + options?: RefreshColumnOptions, + ): Promise { + return await this.inner.refreshColumn(column, options); } - async refreshColumnAsync(column: string): Promise { - return new Job(await this.inner.refreshColumnAsync(column)); + async refreshColumnAsync( + column: string, + options?: RefreshColumnOptions, + ): Promise { + return new Job(await this.inner.refreshColumnAsync(column, options)); } async functionErrors( @@ -1576,9 +1673,23 @@ export class LocalTable extends Table { } 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}`); + } + } return await this.inner.optimize( options?.cleanupOlderThan?.getTime(), options?.deleteUnverified, + options?.compactionOptions, ); } diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index e417308eb..f04147d46 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.41.0-beta.17", + "version": "0.42.0-beta.9", "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 d7dfa44be..af781ae92 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.41.0-beta.17", + "version": "0.42.0-beta.9", "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 f4a768871..c08a81137 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.41.0-beta.17", + "version": "0.42.0-beta.9", "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 a2266260d..624b22de3 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.41.0-beta.17", + "version": "0.42.0-beta.9", "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 6af065156..d200c24c3 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.41.0-beta.17", + "version": "0.42.0-beta.9", "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 694449160..a0b3cfd48 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.41.0-beta.17", + "version": "0.42.0-beta.9", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index d852a1e3e..0544af0c7 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.41.0-beta.17", + "version": "0.42.0-beta.9", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index cf0c7682e..c2424cd55 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.17", + "version": "0.42.0-beta.9", "main": "dist/index.js", "exports": { ".": "./dist/index.js", @@ -102,7 +102,7 @@ "reflect-metadata": "^0.2.2" }, "optionalDependencies": { - "@huggingface/transformers": "3.0.2", + "@huggingface/transformers": "4.3.2", "openai": "4.29.2" }, "peerDependencies": { diff --git a/nodejs/pnpm-lock.yaml b/nodejs/pnpm-lock.yaml index faf0ad428..e57bb68d3 100644 --- a/nodejs/pnpm-lock.yaml +++ b/nodejs/pnpm-lock.yaml @@ -4,9 +4,6 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false -overrides: - sharp: ^0.35.4 - importers: .: @@ -104,8 +101,8 @@ importers: version: 7.18.0(eslint@8.57.1)(typescript@5.5.4) optionalDependencies: '@huggingface/transformers': - specifier: 3.0.2 - version: 3.0.2(@types/node@22.7.4) + specifier: 4.3.2 + version: 4.3.2(@types/node@22.7.4) openai: specifier: 4.29.2 version: 4.29.2 @@ -569,12 +566,15 @@ packages: resolution: {integrity: sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - '@huggingface/jinja@0.3.4': - resolution: {integrity: sha512-kFFQWJiWwvxezKQnvH1X7GjsECcMljFx+UZK9hx6P26aVHwwidJVTB0ptLfRVZQvVkOGHoMmTGvo4nT0X9hHOA==} + '@huggingface/jinja@0.5.11': + resolution: {integrity: sha512-YzEzwM5oQf4r0vs7ifWQ+yuVR1YkAHrjERQ+a8WRsStHHp4NRBg+NesjiFc+X2AFUpRvvrIeHDS1xFy9jY/IjQ==} engines: {node: '>=18'} - '@huggingface/transformers@3.0.2': - resolution: {integrity: sha512-lTyS81eQazMea5UCehDGFMfdcNRZyei7XQLH5X6j4AhA/18Ka0+5qPgMxUxuZLU4xkv60aY2KNz9Yzthv6WVJg==} + '@huggingface/tokenizers@0.2.0': + resolution: {integrity: sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==} + + '@huggingface/transformers@4.3.2': + resolution: {integrity: sha512-V3+dqf3iWlRYJ9I9GreM3zGQd0lAXnnoPeddmkOQYWAEE4l/+Fi6p7tx/qVUJlKQgLXGim2W76rTOzz+eC0i7g==} '@humanwhocodes/config-array@0.13.0': resolution: {integrity: sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==} @@ -593,160 +593,160 @@ packages: resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} - '@img/sharp-darwin-arm64@0.35.4': - resolution: {integrity: sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==} + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] - '@img/sharp-darwin-x64@0.35.4': - resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==} + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] - '@img/sharp-freebsd-wasm32@0.35.4': - resolution: {integrity: sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==} + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} engines: {node: '>=20.9.0'} os: [freebsd] - '@img/sharp-libvips-darwin-arm64@1.3.3': - resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==} + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.3.3': - resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==} + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] - '@img/sharp-libvips-linux-arm64@1.3.3': - resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==} + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-arm@1.3.3': - resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==} + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-ppc64@1.3.3': - resolution: {integrity: sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==} + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-riscv64@1.3.3': - resolution: {integrity: sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==} + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} cpu: [riscv64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-s390x@1.3.3': - resolution: {integrity: sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==} + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-x64@1.3.3': - resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==} + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linuxmusl-arm64@1.3.3': - resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==} + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-libvips-linuxmusl-x64@1.3.3': - resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==} + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-linux-arm64@0.35.4': - resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==} + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-linux-arm@0.35.4': - resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==} + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-linux-ppc64@0.35.4': - resolution: {integrity: sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==} + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} engines: {node: '>=20.9.0'} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-linux-riscv64@0.35.4': - resolution: {integrity: sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==} + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} engines: {node: '>=20.9.0'} cpu: [riscv64] os: [linux] libc: [glibc] - '@img/sharp-linux-s390x@0.35.4': - resolution: {integrity: sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==} + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-linux-x64@0.35.4': - resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==} + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-linuxmusl-arm64@0.35.4': - resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==} + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-linuxmusl-x64@0.35.4': - resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==} + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-wasm32@0.35.4': - resolution: {integrity: sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==} + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} engines: {node: '>=20.9.0'} - '@img/sharp-webcontainers-wasm32@0.35.4': - resolution: {integrity: sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==} + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} engines: {node: '>=20.9.0'} cpu: [wasm32] - '@img/sharp-win32-arm64@0.35.4': - resolution: {integrity: sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==} + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [win32] - '@img/sharp-win32-ia32@0.35.4': - resolution: {integrity: sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==} + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} engines: {node: ^20.9.0} cpu: [ia32] os: [win32] - '@img/sharp-win32-x64@0.35.4': - resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==} + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] @@ -885,10 +885,6 @@ packages: '@types/node': optional: true - '@isaacs/fs-minipass@4.0.1': - resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} - engines: {node: '>=18.0.0'} - '@istanbuljs/load-nyc-config@1.1.0': resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} engines: {node: '>=8'} @@ -1805,6 +1801,10 @@ packages: engines: {node: '>=0.4.0'} hasBin: true + adm-zip@0.6.1: + resolution: {integrity: sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==} + engines: {node: '>=14.0'} + agent-base@6.0.2: resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} engines: {node: '>= 6.0.0'} @@ -2001,10 +2001,6 @@ packages: charenc@0.0.2: resolution: {integrity: sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==} - chownr@3.0.0: - resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} - engines: {node: '>=18'} - ci-info@3.9.0: resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==} engines: {node: '>=8'} @@ -2108,6 +2104,14 @@ packages: resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} engines: {node: '>=0.10.0'} + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + delayed-stream@1.0.0: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} @@ -2331,9 +2335,6 @@ packages: resolution: {integrity: sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==} engines: {node: ^10.12.0 || >=12.0.0} - flatbuffers@1.12.0: - resolution: {integrity: sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==} - flatbuffers@23.5.26: resolution: {integrity: sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ==} @@ -2413,10 +2414,18 @@ packages: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + global-agent@4.1.6: + resolution: {integrity: sha512-V9u791atI/bS7RryfRTK2oixDWo6/RCrIikjwuQ4kADPRZZml1C6LUJXc7y6qRhaAF8geo3bIvE/siAGJCw38A==} + engines: {node: '>=10.0'} + globals@13.24.0: resolution: {integrity: sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==} engines: {node: '>=8'} + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + globby@11.1.0: resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==} engines: {node: '>=10'} @@ -2443,6 +2452,9 @@ packages: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + has-symbols@1.1.0: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} @@ -2809,6 +2821,10 @@ packages: resolution: {integrity: sha512-RCEsPjR+sr0x+AuYp601tKTkgFG4YEPLCzHST3cQ/fhlJkqAkz1L2/Qbp1j9qw5SBwQHFBoW8+hoN5xssOF0Tw==} hasBin: true + matcher@4.0.0: + resolution: {integrity: sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==} + engines: {node: '>=10'} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -2870,14 +2886,6 @@ packages: minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - minipass@7.1.3: - resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} - engines: {node: '>=16 || 14 >=14.17'} - - minizlib@3.1.0: - resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} - engines: {node: '>= 18'} - mnemonist@0.38.3: resolution: {integrity: sha512-2K9QYubXx/NAjv4VLq1d1Ly8pWNC5L3BrixtdkyTegXWJIqY+zLNDhhX/A+ZwWt70tB1S8H4BE8FLYEFyNoOBw==} @@ -2923,6 +2931,10 @@ packages: resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} engines: {node: '>=8'} + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + obliterator@1.6.1: resolution: {integrity: sha512-9WXswnqINnnhOG/5SLimUlzuU1hFJUc8zkwyD59Sd+dPOMf05PmnYG/d6Q7HZ+KmgkZJa1PxRso6QdM3sTNHig==} @@ -2939,18 +2951,18 @@ packages: oniguruma-to-es@2.3.0: resolution: {integrity: sha512-bwALDxriqfKGfUufKGGepCzu9x7nJQuoRoAFp4AnwehhC2crqrDIAP/uN2qdlsAvSMpeRC3+Yzhqc7hLmle5+g==} - onnxruntime-common@1.19.2: - resolution: {integrity: sha512-a4R7wYEVFbZBlp0BfhpbFWqe4opCor3KM+5Wm22Az3NGDcQMiU2hfG/0MfnBs+1ZrlSGmlgWeMcXQkDk1UFb8Q==} + onnxruntime-common@1.30.0: + resolution: {integrity: sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==} - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: - resolution: {integrity: sha512-KZK8b6zCYGZFjd4ANze0pqBnqnFTS3GIVeclQpa2qseDpXrCQJfkWBixRcrZShNhm3LpFOZ8qJYFC5/qsJK9WQ==} + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: + resolution: {integrity: sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==} - onnxruntime-node@1.19.2: - resolution: {integrity: sha512-9eHMP/HKbbeUcqte1JYzaaRC8JPn7ojWeCeoyShO86TOR97OCyIyAIOGX3V95ErjslVhJRXY8Em/caIUc0hm1Q==} + onnxruntime-node@1.30.0: + resolution: {integrity: sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==} os: [win32, darwin, linux] - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: - resolution: {integrity: sha512-ANSQfMALvCviN3Y4tvTViKofKToV1WUb2r2VjZVCi3uUBPaK15oNJyIxhsNyEckBr/Num3JmSXlkHOD8HfVzSQ==} + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: + resolution: {integrity: sha512-Iy7rtadoBgxS/LLvDr3QW38DB1PNXRnr0GJMcL0TAt7c9qjgVQl83UlGCVyeAnK2InpmW8Uc3PL8XIuqtDeF6g==} openai@4.29.2: resolution: {integrity: sha512-cPkT6zjEcE4qU5OW/SoDDuXEsdOLrXlAORhzmaguj5xZSPlgKvLhi27sFWhLKj07Y6WKNWxcwIbzm512FzTBNQ==} @@ -3139,8 +3151,12 @@ packages: engines: {node: '>=10'} hasBin: true - sharp@0.35.4: - resolution: {integrity: sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==} + serialize-error@8.1.0: + resolution: {integrity: sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==} + engines: {node: '>=10'} + + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} engines: {node: '>=20.9.0'} peerDependencies: '@types/node': '*' @@ -3246,10 +3262,6 @@ packages: resolution: {integrity: sha512-iK5/YhZxq5GO5z8wb0bY1317uDF3Zjpha0QFFLA8/trAoiLbQD0HUbMesEaxyzUgDxi2QlcbM8IvqOlEjgoXBA==} engines: {node: '>=12.17'} - tar@7.5.22: - resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==} - engines: {node: '>=18'} - test-exclude@6.0.0: resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==} engines: {node: '>=8'} @@ -3310,6 +3322,9 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tslib@2.9.1: + resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} + typanion@3.14.0: resolution: {integrity: sha512-ZW/lVMRabETuYCd9O9ZvMhAh8GslSqaUjxmK/JLPCh6l73CvLBiuXswj/+7LdnWOgYsQ130FqLzFz5aGT4I3Ug==} @@ -3481,10 +3496,6 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} - yallist@5.0.0: - resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} - engines: {node: '>=18'} - yaml@2.9.0: resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} engines: {node: '>= 14.6'} @@ -4327,17 +4338,17 @@ snapshots: '@emnapi/core@1.10.0': dependencies: '@emnapi/wasi-threads': 1.2.1 - tslib: 2.8.1 + tslib: 2.9.1 optional: true '@emnapi/runtime@1.11.3': dependencies: - tslib: 2.8.1 + tslib: 2.9.1 optional: true '@emnapi/wasi-threads@1.2.1': dependencies: - tslib: 2.8.1 + tslib: 2.9.1 optional: true '@eslint-community/eslint-utils@4.9.1(eslint@8.57.1)': @@ -4363,15 +4374,19 @@ snapshots: '@eslint/js@8.57.1': {} - '@huggingface/jinja@0.3.4': + '@huggingface/jinja@0.5.11': optional: true - '@huggingface/transformers@3.0.2(@types/node@22.7.4)': + '@huggingface/tokenizers@0.2.0': + optional: true + + '@huggingface/transformers@4.3.2(@types/node@22.7.4)': dependencies: - '@huggingface/jinja': 0.3.4 - onnxruntime-node: 1.19.2 - onnxruntime-web: 1.21.0-dev.20241024-d9ca84ef96 - sharp: 0.35.4(@types/node@22.7.4) + '@huggingface/jinja': 0.5.11 + '@huggingface/tokenizers': 0.2.0 + onnxruntime-node: 1.30.0 + onnxruntime-web: 1.31.0-dev.20260914-8d85527a0 + sharp: 0.35.5(@types/node@22.7.4) transitivePeerDependencies: - '@types/node' optional: true @@ -4391,108 +4406,108 @@ snapshots: '@img/colour@1.1.0': optional: true - '@img/sharp-darwin-arm64@0.35.4': + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.3.3 + '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true - '@img/sharp-darwin-x64@0.35.4': + '@img/sharp-darwin-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.3.3 + '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true - '@img/sharp-freebsd-wasm32@0.35.4': + '@img/sharp-freebsd-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.4 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-libvips-darwin-arm64@1.3.3': + '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true - '@img/sharp-libvips-darwin-x64@1.3.3': + '@img/sharp-libvips-darwin-x64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm64@1.3.3': + '@img/sharp-libvips-linux-arm64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm@1.3.3': + '@img/sharp-libvips-linux-arm@1.3.4': optional: true - '@img/sharp-libvips-linux-ppc64@1.3.3': + '@img/sharp-libvips-linux-ppc64@1.3.4': optional: true - '@img/sharp-libvips-linux-riscv64@1.3.3': + '@img/sharp-libvips-linux-riscv64@1.3.4': optional: true - '@img/sharp-libvips-linux-s390x@1.3.3': + '@img/sharp-libvips-linux-s390x@1.3.4': optional: true - '@img/sharp-libvips-linux-x64@1.3.3': + '@img/sharp-libvips-linux-x64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-arm64@1.3.3': + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-x64@1.3.3': + '@img/sharp-libvips-linuxmusl-x64@1.3.4': optional: true - '@img/sharp-linux-arm64@0.35.4': + '@img/sharp-linux-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.3.3 + '@img/sharp-libvips-linux-arm64': 1.3.4 optional: true - '@img/sharp-linux-arm@0.35.4': + '@img/sharp-linux-arm@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.3.3 + '@img/sharp-libvips-linux-arm': 1.3.4 optional: true - '@img/sharp-linux-ppc64@0.35.4': + '@img/sharp-linux-ppc64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-ppc64': 1.3.3 + '@img/sharp-libvips-linux-ppc64': 1.3.4 optional: true - '@img/sharp-linux-riscv64@0.35.4': + '@img/sharp-linux-riscv64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-riscv64': 1.3.3 + '@img/sharp-libvips-linux-riscv64': 1.3.4 optional: true - '@img/sharp-linux-s390x@0.35.4': + '@img/sharp-linux-s390x@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.3.3 + '@img/sharp-libvips-linux-s390x': 1.3.4 optional: true - '@img/sharp-linux-x64@0.35.4': + '@img/sharp-linux-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.3.3 + '@img/sharp-libvips-linux-x64': 1.3.4 optional: true - '@img/sharp-linuxmusl-arm64@0.35.4': + '@img/sharp-linuxmusl-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 optional: true - '@img/sharp-linuxmusl-x64@0.35.4': + '@img/sharp-linuxmusl-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.3.3 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 optional: true - '@img/sharp-wasm32@0.35.4': + '@img/sharp-wasm32@0.35.5': dependencies: '@emnapi/runtime': 1.11.3 optional: true - '@img/sharp-webcontainers-wasm32@0.35.4': + '@img/sharp-webcontainers-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.4 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-win32-arm64@0.35.4': + '@img/sharp-win32-arm64@0.35.5': optional: true - '@img/sharp-win32-ia32@0.35.4': + '@img/sharp-win32-ia32@0.35.5': optional: true - '@img/sharp-win32-x64@0.35.4': + '@img/sharp-win32-x64@0.35.5': optional: true '@inquirer/ansi@2.0.5': {} @@ -4614,11 +4629,6 @@ snapshots: optionalDependencies: '@types/node': 22.7.4 - '@isaacs/fs-minipass@4.0.1': - dependencies: - minipass: 7.1.3 - optional: true - '@istanbuljs/load-nyc-config@1.1.0': dependencies: camelcase: 5.3.1 @@ -5659,6 +5669,9 @@ snapshots: acorn@8.16.0: {} + adm-zip@0.6.1: + optional: true + agent-base@6.0.2: dependencies: debug: 4.4.3 @@ -5933,9 +5946,6 @@ snapshots: charenc@0.0.2: optional: true - chownr@3.0.0: - optional: true - ci-info@3.9.0: {} cjs-module-lexer@1.4.3: {} @@ -6029,6 +6039,20 @@ snapshots: deepmerge@4.3.1: {} + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + optional: true + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + optional: true + delayed-stream@1.0.0: {} dequal@2.0.3: {} @@ -6274,9 +6298,6 @@ snapshots: keyv: 4.5.4 rimraf: 3.0.2 - flatbuffers@1.12.0: - optional: true - flatbuffers@23.5.26: {} flatbuffers@24.12.23: {} @@ -6354,10 +6375,24 @@ snapshots: once: 1.4.0 path-is-absolute: 1.0.1 + global-agent@4.1.6: + dependencies: + globalthis: 1.0.4 + matcher: 4.0.0 + semver: 7.8.5 + serialize-error: 8.1.0 + optional: true + globals@13.24.0: dependencies: type-fest: 0.20.2 + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + optional: true + globby@11.1.0: dependencies: array-union: 2.1.0 @@ -6387,6 +6422,11 @@ snapshots: has-flag@4.0.0: {} + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + optional: true + has-symbols@1.1.0: {} has-tostringtag@1.0.2: @@ -6928,6 +6968,11 @@ snapshots: punycode.js: 2.3.1 uc.micro: 2.1.0 + matcher@4.0.0: + dependencies: + escape-string-regexp: 4.0.0 + optional: true + math-intrinsics@1.1.0: {} md5@2.3.0: @@ -6995,14 +7040,6 @@ snapshots: minimist@1.2.8: {} - minipass@7.1.3: - optional: true - - minizlib@3.1.0: - dependencies: - minipass: 7.1.3 - optional: true - mnemonist@0.38.3: dependencies: obliterator: 1.6.1 @@ -7033,6 +7070,9 @@ snapshots: dependencies: path-key: 3.1.1 + object-keys@1.1.1: + optional: true + obliterator@1.6.1: {} obug@2.1.1: {} @@ -7051,24 +7091,25 @@ snapshots: regex: 5.1.1 regex-recursion: 5.1.1 - onnxruntime-common@1.19.2: + onnxruntime-common@1.30.0: optional: true - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: optional: true - onnxruntime-node@1.19.2: + onnxruntime-node@1.30.0: dependencies: - onnxruntime-common: 1.19.2 - tar: 7.5.22 + adm-zip: 0.6.1 + global-agent: 4.1.6 + onnxruntime-common: 1.30.0 optional: true - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: dependencies: - flatbuffers: 1.12.0 + flatbuffers: 25.9.23 guid-typescript: 1.0.9 long: 5.3.2 - onnxruntime-common: 1.20.0-dev.20241016-2b8fc5529b + onnxruntime-common: 1.31.0-dev.20260911-2a43ec07e platform: 1.3.6 protobufjs: 7.6.5 optional: true @@ -7247,37 +7288,42 @@ snapshots: semver@7.8.5: {} - sharp@0.35.4(@types/node@22.7.4): + serialize-error@8.1.0: + dependencies: + type-fest: 0.20.2 + optional: true + + sharp@0.35.5(@types/node@22.7.4): dependencies: '@img/colour': 1.1.0 detect-libc: 2.1.2 semver: 7.8.5 optionalDependencies: - '@img/sharp-darwin-arm64': 0.35.4 - '@img/sharp-darwin-x64': 0.35.4 - '@img/sharp-freebsd-wasm32': 0.35.4 - '@img/sharp-libvips-darwin-arm64': 1.3.3 - '@img/sharp-libvips-darwin-x64': 1.3.3 - '@img/sharp-libvips-linux-arm': 1.3.3 - '@img/sharp-libvips-linux-arm64': 1.3.3 - '@img/sharp-libvips-linux-ppc64': 1.3.3 - '@img/sharp-libvips-linux-riscv64': 1.3.3 - '@img/sharp-libvips-linux-s390x': 1.3.3 - '@img/sharp-libvips-linux-x64': 1.3.3 - '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 - '@img/sharp-libvips-linuxmusl-x64': 1.3.3 - '@img/sharp-linux-arm': 0.35.4 - '@img/sharp-linux-arm64': 0.35.4 - '@img/sharp-linux-ppc64': 0.35.4 - '@img/sharp-linux-riscv64': 0.35.4 - '@img/sharp-linux-s390x': 0.35.4 - '@img/sharp-linux-x64': 0.35.4 - '@img/sharp-linuxmusl-arm64': 0.35.4 - '@img/sharp-linuxmusl-x64': 0.35.4 - '@img/sharp-webcontainers-wasm32': 0.35.4 - '@img/sharp-win32-arm64': 0.35.4 - '@img/sharp-win32-ia32': 0.35.4 - '@img/sharp-win32-x64': 0.35.4 + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 '@types/node': 22.7.4 optional: true @@ -7375,15 +7421,6 @@ snapshots: array-back: 6.2.3 wordwrapjs: 5.1.1 - tar@7.5.22: - dependencies: - '@isaacs/fs-minipass': 4.0.1 - chownr: 3.0.0 - minipass: 7.1.3 - minizlib: 3.1.0 - yallist: 5.0.0 - optional: true - test-exclude@6.0.0: dependencies: '@istanbuljs/schema': 0.1.6 @@ -7431,6 +7468,9 @@ snapshots: tslib@2.8.1: {} + tslib@2.9.1: + optional: true + typanion@3.14.0: {} type-check@0.4.0: @@ -7588,9 +7628,6 @@ snapshots: yallist@3.1.1: {} - yallist@5.0.0: - optional: true - yaml@2.9.0: {} yargs-parser@21.1.1: {} diff --git a/nodejs/pnpm-workspace.yaml b/nodejs/pnpm-workspace.yaml index b6be57977..222b3fb1c 100644 --- a/nodejs/pnpm-workspace.yaml +++ b/nodejs/pnpm-workspace.yaml @@ -47,10 +47,3 @@ minimumReleaseAgeExclude: - js-yaml@4.3.1 - tar@7.5.21 - '@opentelemetry/core@2.8.0' - -# @huggingface/transformers pins sharp ^0.33.5 and no released version has moved -# past ^0.34.5, all of which inherit the libvips CVEs in GHSA-f88m-g3jw-g9cj. -# Force the patched line. sharp is only reached by transformers' image pipeline, -# which LanceDB's text embedding function never uses. -overrides: - sharp: ^0.35.4 diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 320812128..485035d33 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -6,10 +6,14 @@ use std::sync::Arc; use arrow_array::RecordBatch; use lancedb::job::JobEventsRequest; use napi::bindgen_prelude::Buffer; +use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; use crate::error::NapiErrorExt; +type JobProgressFn = + ThreadsafeFunction; + /// A handle to an operation that may still be running. #[napi] pub struct Job { @@ -47,10 +51,38 @@ impl Job { self.inner.status().await.default_error() } - /// Wait until the operation reaches a terminal state. - #[napi(catch_unwind)] - pub async fn wait(&self) -> napi::Result<()> { - self.inner.wait().await.default_error() + /// The current structured progress snapshot, or null for an in-process + /// operation. Registry snapshots include lifecycle and queue metadata even + /// when the job type or server does not report counters. + #[napi( + catch_unwind, + ts_return_type = "Promise | null>" + )] + pub async fn progress(&self) -> napi::Result> { + self.inner.progress().await.default_error() + } + + /// Wait until the operation reaches a terminal state. When a callback is + /// supplied, observe the same progress snapshots fetched by the existing + /// backend poller without starting another polling loop. + #[napi( + catch_unwind, + ts_args_type = "progressCallback?: (progress: Record) => void" + )] + 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() + } } /// Request cancellation. Cancelling a finished operation is a no-op. @@ -109,6 +141,7 @@ impl Job { self.inner.failure().map(|failure| JobFailureInfo { phase: failure.phase, message: failure.message, + traceback: failure.traceback, retryable: failure.retryable, }) } @@ -159,16 +192,24 @@ pub struct JobInfo { pub state: String, /// When the job was created, in milliseconds since the epoch. pub created_at_millis: i64, + /// Structured lifecycle, queue, pause, and job-type-specific progress. + #[napi(ts_type = "Record")] + pub progress: serde_json::Value, + /// Whether an operator has parked this job. + pub paused: bool, } impl From for JobInfo { fn from(info: lancedb::database::JobInfo) -> Self { + let progress = info.progress_snapshot(); Self { job_id: info.job_id, table: info.table, job_type: info.job_type, state: info.state, created_at_millis: info.created_at_millis, + progress, + paused: info.paused, } } } @@ -178,5 +219,7 @@ impl From for JobInfo { pub struct JobFailureInfo { pub phase: Option, pub message: Option, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, pub retryable: Option, } diff --git a/nodejs/src/lib.rs b/nodejs/src/lib.rs index 368a3530c..fab225992 100644 --- a/nodejs/src/lib.rs +++ b/nodejs/src/lib.rs @@ -115,6 +115,7 @@ pub struct ConnectNamespaceOptions { #[napi_derive::module_init] fn init() { + lancedb::docs::set_sdk_ident("nodejs", env!("CARGO_PKG_VERSION")); let env = Env::new() .filter_or("LANCEDB_LOG", "warn") .write_style("LANCEDB_LOG_STYLE"); diff --git a/nodejs/src/query.rs b/nodejs/src/query.rs index c2987f259..93c4f0f8e 100644 --- a/nodejs/src/query.rs +++ b/nodejs/src/query.rs @@ -15,6 +15,7 @@ use arrow_array::{ }; use arrow_buffer::ScalarBuffer; use half::f16; +use lancedb::ApproxMode; use lancedb::index::scalar::{ BooleanQuery, BoostQuery, FtsQuery, FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery, @@ -352,6 +353,13 @@ impl VectorQuery { self.inner = self.inner.clone().ef(ef as usize); } + #[napi] + pub fn approx_mode(&mut self, approx_mode: String) -> napi::Result<()> { + let approx_mode = ApproxMode::try_from(approx_mode.as_str()).default_error()?; + self.inner = self.inner.clone().approx_mode(approx_mode); + Ok(()) + } + #[napi] pub fn bypass_vector_index(&mut self) { self.inner = self.inner.clone().bypass_vector_index() diff --git a/nodejs/src/remote.rs b/nodejs/src/remote.rs index df882334b..5c0517641 100644 --- a/nodejs/src/remote.rs +++ b/nodejs/src/remote.rs @@ -276,7 +276,7 @@ impl TryFrom for lancedb::remote::oauth::OAuthConfig { } OAuthFlow::AuthorizationCode(options) } - "device_code" => OAuthFlow::DeviceCode, + "device_code" => OAuthFlow::DeviceCode(Default::default()), "azure_managed_identity" => OAuthFlow::AzureManagedIdentity { client_id: config.managed_identity_client_id, }, @@ -560,7 +560,7 @@ mod tests { let converted = lancedb::remote::oauth::OAuthConfig::try_from(config).unwrap(); assert!(matches!( converted.flow, - lancedb::remote::oauth::OAuthFlow::DeviceCode + lancedb::remote::oauth::OAuthFlow::DeviceCode(options) if !options.use_pkce )); } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index ec16ea5b5..ebbc4a060 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -9,7 +9,7 @@ use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema}; use lancedb::table::{ AddDataMode, ColumnAlteration as LanceColumnAlteration, FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken, - NewColumnTransform, OptimizeAction, OptimizeOptions, Ref, Table as LanceDbTable, + NewColumnTransform, Ref, Table as LanceDbTable, }; use napi::Env; use napi::bindgen_prelude::*; @@ -23,6 +23,63 @@ use crate::merge::NativeMergeInsertBuilder; use crate::query::{Query, TakeQuery, VectorQuery}; use crate::util::schema_to_buffer; +/// Per-invocation file-compaction settings. All numbers must be safe integers. +#[napi(object)] +pub struct CompactionOptions { + pub target_rows_per_fragment: Option, + pub max_source_rows: Option, + pub io_buffer_size: Option, + pub batch_size: Option, +} + +impl CompactionOptions { + fn into_overrides(self) -> napi::Result { + const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; + fn integer( + value: Option, + name: &str, + max: u64, + allow_zero: bool, + ) -> napi::Result> { + let Some(value) = value else { + return Ok(None); + }; + let min = if allow_zero { 0 } else { 1 }; + let max = max.min(MAX_SAFE_INTEGER); + if !value.is_finite() + || value.fract() != 0.0 + || value < min as f64 + || value > max as f64 + { + return Err(napi::Error::from_reason(format!( + "{name} must be a safe integer between {min} and {max}" + ))); + } + Ok(Some(value as u64)) + } + let mut options = lancedb::table::optimize::CompactionOverrides::default(); + if let Some(target) = integer( + self.target_rows_per_fragment, + "targetRowsPerFragment", + u32::MAX as u64, + false, + )? { + options.target_rows_per_fragment = Some(target as usize); + } + options.max_source_rows = integer( + self.max_source_rows, + "maxSourceRows", + usize::MAX as u64, + false, + )? + .map(|v| v as usize); + options.io_buffer_size = integer(self.io_buffer_size, "ioBufferSize", u64::MAX, true)?; + options.batch_size = + integer(self.batch_size, "batchSize", u32::MAX as u64, false)?.map(|v| v as usize); + Ok(options) + } +} + #[napi] pub struct Table { // We keep a duplicate of the table name so we can use it for error @@ -421,20 +478,30 @@ impl Table { } #[napi(catch_unwind)] - pub async fn refresh_column(&self, column: String) -> napi::Result { + pub async fn refresh_column( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default().try_into()?; let res = self .inner_ref()? - .refresh_column(column) + .refresh_column_with_options(column, options) .await .default_error()?; Ok(res.into()) } #[napi(catch_unwind)] - pub async fn refresh_column_async(&self, column: String) -> napi::Result { + pub async fn refresh_column_async( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default().try_into()?; let job = self .inner_ref()? - .refresh_column_async(column) + .refresh_column_async_with_options(column, options) .await .default_error()?; Ok(crate::job::Job::new(job)) @@ -722,6 +789,7 @@ impl Table { &self, before_timestamp_ms: Option, delete_unverified: Option, + compaction_options: Option, ) -> napi::Result { let inner = self.inner_ref()?; @@ -735,37 +803,20 @@ impl Table { }) .transpose()?; - let compaction_stats = inner - .optimize(OptimizeAction::Compact { - options: lancedb::table::CompactionOptions::default(), - remap_options: None, - }) - .await - .default_error()? - .compaction - .unwrap(); - let prune_stats = if let Some(before_timestamp) = before_timestamp { - inner - .optimize_prune_before(before_timestamp, delete_unverified, None) - .await - } else { - inner - .optimize(OptimizeAction::Prune { - older_than: None, - delete_unverified, - error_if_tagged_old_versions: None, - }) - .await - } - .default_error()? - .prune - .unwrap(); - inner - .optimize(lancedb::table::OptimizeAction::Index( - OptimizeOptions::default(), - )) + let stats = inner + .optimize_full_with_overrides( + compaction_options + .map(CompactionOptions::into_overrides) + .transpose()? + .unwrap_or_default(), + None, + before_timestamp, + delete_unverified, + ) .await .default_error()?; + let compaction_stats = stats.compaction.unwrap(); + let prune_stats = stats.prune.unwrap(); Ok(OptimizeStats { compaction: CompactionStats { files_added: compaction_stats.files_added as i64, @@ -831,7 +882,7 @@ impl Table { self.inner_ref()? .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "uses_v2_manifest_paths is not supported in LanceDB Distributed.".into(), + message: "uses_v2_manifest_paths is not supported in LanceDB Enterprise.".into(), }) .default_error()? .uses_v2_manifest_paths() @@ -844,8 +895,7 @@ impl Table { self.inner_ref()? .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "migrate_manifest_paths_v2 is not supported in LanceDB Distributed." - .into(), + message: "migrate_manifest_paths_v2 is not supported in LanceDB Enterprise.".into(), }) .default_error()? .migrate_manifest_paths_v2() @@ -868,40 +918,40 @@ pub struct IndexConfig { pub columns: Vec, /// The UUID of the first segment of the index. /// - /// `undefined` in LanceDB Distributed, which does not yet surface this. + /// `undefined` in LanceDB Enterprise, which does not yet surface this. pub index_uuid: Option, /// The protobuf type URL, a precise type identifier for the index. /// - /// `undefined` in LanceDB Distributed. + /// `undefined` in LanceDB Enterprise. pub type_url: Option, /// When the index was created. /// - /// `undefined` in LanceDB Distributed or indices created before timestamps were tracked. + /// `undefined` in LanceDB Enterprise or indices created before timestamps were tracked. pub created_at: Option>, /// The number of rows indexed, across all segments. /// - /// May be `undefined` in LanceDB Distributed if the server does not report it. + /// May be `undefined` in LanceDB Enterprise if the server does not report it. pub num_indexed_rows: Option, /// The number of rows not yet covered by this index. /// - /// May be `undefined` in LanceDB Distributed if the server does not report it. + /// May be `undefined` in LanceDB Enterprise if the server does not report it. pub num_unindexed_rows: Option, /// The total size in bytes of all index files across all segments. /// - /// `undefined` in LanceDB Distributed or indices without size tracking. + /// `undefined` in LanceDB Enterprise or indices without size tracking. pub size_bytes: Option, /// The number of segments that make up the index. /// - /// `undefined` in LanceDB Distributed. + /// `undefined` in LanceDB Enterprise. pub num_segments: Option, /// The on-disk index format version. /// - /// `undefined` in LanceDB Distributed. + /// `undefined` in LanceDB Enterprise. pub index_version: Option, /// Index-type-specific details parsed as a JavaScript object. /// /// Falls back to a raw string if JSON parsing fails. `undefined` in - /// LanceDB Distributed or when details are unavailable. + /// LanceDB Enterprise or when details are unavailable. pub index_details: Option, } @@ -1536,6 +1586,76 @@ pub struct FunctionErrorsOptions { pub limit: Option, } +/// 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. +#[napi(object)] +#[derive(Clone, Debug, Default)] +pub struct RefreshColumnOptions { + /// Only refresh the rows matching this SQL filter. + #[napi(js_name = "where")] + pub where_clause: Option, + /// Maximum rows per Function call; must be greater than zero. + pub batch_size: Option, + /// GPU class for Function workers. + pub gpu_class: Option, + /// Positive aggregate GPU budget for Function workers. + pub gpu_count: Option, + /// `"fail"` (default) stops on a row error; `"skip"` writes null and + /// records the error, subject to the failure limits. + pub error_policy: Option, + /// Under a skip policy, fail the job once more than this share of rows + /// (0 to 1) has failed. + pub max_failed_fraction: Option, + /// Under a skip policy, fail the job once more than this many rows have + /// failed. + pub max_failed_rows: Option, + /// Deadline for one Function call, in seconds. + pub row_timeout_seconds: Option, + /// Deadline for Function initialization, in seconds. + pub init_timeout_seconds: Option, + /// Worker count for an expression column; Function columns reject it. + pub num_workers: Option, + /// Cap on executor processes per Function worker. + pub max_executor_processes_per_worker: Option, +} + +impl TryFrom for lancedb::table::RefreshColumnOptions { + type Error = napi::Error; + + fn try_from(value: RefreshColumnOptions) -> napi::Result { + let mut options = Self::default(); + options.where_clause = value.where_clause; + options.batch_size = value.batch_size.map(|size| size as usize); + options.gpu_class = value.gpu_class; + options.gpu_count = value.gpu_count; + options.error_policy = match value.error_policy.as_deref() { + None => None, + Some("fail") => Some(lancedb::function::FunctionErrorPolicy::Fail), + Some("skip") => Some(lancedb::function::FunctionErrorPolicy::Skip), + Some(other) => { + return Err(napi::Error::from_reason(format!( + "errorPolicy must be \"fail\" or \"skip\", got \"{other}\"" + ))); + } + }; + options.max_failed_fraction = value.max_failed_fraction; + options.max_failed_rows = value + .max_failed_rows + .map(|rows| { + u64::try_from(rows).map_err(|_| { + napi::Error::from_reason("maxFailedRows must be a non-negative integer") + }) + }) + .transpose()?; + options.row_timeout_seconds = value.row_timeout_seconds; + options.init_timeout_seconds = value.init_timeout_seconds; + options.num_workers = value.num_workers.map(|workers| workers as usize); + options.max_executor_processes_per_worker = value.max_executor_processes_per_worker; + Ok(options) + } +} + /// One row a Function refresh skipped, as the server recorded it. #[napi(object)] #[derive(Clone, Debug)] @@ -1551,6 +1671,8 @@ pub struct FunctionErrorRecord { pub table_version: i64, pub error_type: String, pub error_message: String, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, pub created_at_millis: i64, } @@ -1566,6 +1688,7 @@ impl From for FunctionErrorRecord { table_version: record.table_version as i64, error_type: record.error_type, error_message: record.error_message, + traceback: record.traceback, created_at_millis: record.created_at_millis, } } @@ -1617,11 +1740,11 @@ impl From for FunctionErrors { #[napi(object)] pub struct RefreshMaterializedViewResult { - /// How the view was brought up to date: "rebuild", or absent for LanceDB Distributed SQL refreshes. + /// How the view was brought up to date: "rebuild", or absent for LanceDB Enterprise SQL refreshes. pub mode: Option, - /// Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes. + /// Rows written by this refresh, or absent for LanceDB Enterprise SQL refreshes. pub rows_written: Option, - /// Source version refreshed to, or absent for LanceDB Distributed SQL refreshes. + /// Source version refreshed to, or absent for LanceDB Enterprise SQL refreshes. pub source_version: Option, pub version: i64, } diff --git a/python/Cargo.toml b/python/Cargo.toml index 0695180cd..2c577766b 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.17" +version = "0.42.0-beta.9" publish = false edition.workspace = true description = "Python bindings for LanceDB" @@ -36,6 +36,7 @@ pyo3-async-runtimes = { version = "0.29", features = [ "attributes", "tokio-runtime", ] } +reqwest.workspace = true pin-project.workspace = true futures.workspace = true serde.workspace = true diff --git a/python/README.md b/python/README.md index 0b640d27c..3db34bc13 100644 --- a/python/README.md +++ b/python/README.md @@ -20,7 +20,7 @@ For those hosts, install the `lancedb-compat` package instead: pip install lancedb-compat ``` -Same Python API (`import lancedb` works as usual). The compat wheel is compiled at the `x86-64-v2` baseline (Nehalem-class) and uses runtime SIMD dispatch in the embedded lance crate to pick the right kernel tier (scalar / AVX / AVX+FMA / AVX2+FMA / AVX-512) at load time, so it still goes fast on modern hardware while running cleanly on the pre-Haswell silicon. Use `lance.simd_info()` from Python to verify which tier was selected. +Same Python API (`import lancedb` works as usual). The compat wheel is compiled at the `x86-64-v2` baseline (Nehalem-class) and uses runtime SIMD dispatch in the embedded lance crate to pick the right kernel tier (scalar / AVX / AVX+FMA / AVX2+FMA / AVX-512) at load time, so it still goes fast on modern hardware while running cleanly on the pre-Haswell silicon (if `pylance` is installed, `lance.simd_info()` reports which tier was selected). `lancedb` and `lancedb-compat` install to the same `lancedb/` namespace and conflict at install time. Pick one. To switch, `pip uninstall lancedb` first, then `pip install lancedb-compat` (or vice-versa). @@ -40,8 +40,10 @@ Stable releases are created about every 2 weeks. For the latest features and bug pip install --pre --extra-index-url https://pypi.fury.io/lancedb/ lancedb ``` -If you also need the optional `lance` Python API, install the `pylance` extra -and include the Lance preview index: +Most applications only need `lancedb`. Install the optional `pylance` extra and +include the Lance preview index only when building query engines or connectors, +calling format-level `lance` APIs directly, or converting plain-scan lazy or +legacy blob columns with `to_pandas()`: ```bash pip install --pre \ diff --git a/python/pyproject.toml b/python/pyproject.toml index 1a6c64cee..153d138b4 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -62,9 +62,9 @@ tests = [ "duckdb>=0.9.0", "pytz>=2023.3", "polars>=0.19, <=1.32.3", - "pyarrow<25", + "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b6", + "pylance==15.0.0b15", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", @@ -95,6 +95,7 @@ embeddings = [ "awscli>=1.44.38", "botocore>=1.31.57", 'ibm-watsonx-ai>=1.1.2; python_version >= "3.10"', + "oci>=2.165.1", "ollama>=0.3.0", "sentencepiece>=0.1.99" ] diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 74f37fc2e..2208fd612 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -3,16 +3,24 @@ import os +import warnings from concurrent.futures import ThreadPoolExecutor from datetime import timedelta -from typing import Dict, Optional, Union, Any, List, Iterable, TYPE_CHECKING +from typing import Dict, Optional, Union, Any, List, Iterable, Literal, TYPE_CHECKING + +from packaging.version import Version as _Version + +from ._lancedb import __version__ as _native_version + +# Match Python package metadata without requiring the lancedb distribution. +__version__ = str(_Version(_native_version)) -from ._lancedb import __version__ as __version__ from ._lancedb import connect as lancedb_connect from ._lancedb import FtsToken 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 from .common import URI, sanitize_uri @@ -32,21 +40,26 @@ from .functions import ( FunctionArtifactRequest as FunctionArtifactRequest, FunctionApplication as FunctionApplication, FunctionBinding as FunctionBinding, + FunctionDefinition as FunctionDefinition, FunctionRegistrationRequest as FunctionRegistrationRequest, + FunctionRetryPolicy as FunctionRetryPolicy, FunctionVersion as FunctionVersion, + HuggingFaceModel as HuggingFaceModel, PythonRuntimeSpec as PythonRuntimeSpec, RefreshColumnResult as RefreshColumnResult, - UdfDefinition as UdfDefinition, + function as function, udf as udf, ) from .secrets import EnvVarSecret as EnvVarSecret from .secrets import SecretInfo as SecretInfo +from .storage_integration import StorageIntegrationInfo as StorageIntegrationInfo from .materialized_view import ( AsyncMaterializedView, MaterializedView, MaterializedViewDefinition, ) from .view import ViewDescription as ViewDescription +from .graph import PropertyGraph, PropertyGraphDescription from .table import AsyncTable, CompactionOptions, Table from .types import BaseTokenizerType from ._lancedb import Session @@ -67,6 +80,7 @@ from .catalog import ( if TYPE_CHECKING: from lance.blob import BlobType as BlobType + from .functions import UdfDefinition as UdfDefinition def __getattr__(name: str): @@ -75,6 +89,13 @@ def __getattr__(name: str): globals()["BlobType"] = BlobType return BlobType + if name == "UdfDefinition": + from . import functions + + warnings.warn( + functions.UDF_DEFINITION_DEPRECATION, DeprecationWarning, stacklevel=2 + ) + return functions.FunctionDefinition raise AttributeError(f"module {__name__!r} has no attribute {name!r}") @@ -291,11 +312,11 @@ def connect( raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}") if session is not None: raise NotImplementedError( - "session is not supported for LanceDB Distributed connections" + "session is not supported for LanceDB Enterprise connections" ) if manifest_enabled: raise NotImplementedError( - "manifest_enabled is not supported for LanceDB Distributed connections" + "manifest_enabled is not supported for LanceDB Enterprise connections" ) if api_key is None: api_key = os.environ.get("LANCEDB_API_KEY") @@ -345,13 +366,31 @@ def tokenize( ngram_min_length: int = 3, ngram_max_length: int = 3, prefix_only: bool = False, + analyzer: Optional[Literal["text", "code"]] = None, + split_identifiers: Optional[bool] = None, + split_on_numerics: Optional[bool] = None, + preserve_original: Optional[bool] = None, + index_operators: Optional[bool] = None, ) -> Iterable[FtsToken]: """Tokenize a full-text search query using an explicit tokenizer. This does not require an FTS index. The tokenizer options match :class:`lancedb.index.FTS`. ``custom_stop_words`` accepts a list of strings. When ``stem`` or ``remove_stop_words`` is None, the base tokenizer's default - applies: False for ``code`` and ``ngram``, True otherwise. + applies: False for ``code`` and ``ngram``, True otherwise. ``analyzer`` and the + code flags (``split_identifiers``, ``split_on_numerics``, ``preserve_original`` + and ``index_operators``) behave as they do on :class:`lancedb.index.FTS`. + + Examples + -------- + Inspect the identifier and subwords produced by the code analyzer: + + >>> import lancedb + >>> tokens = lancedb.tokenize( + ... "parseHTTPRequest", analyzer="code", split_identifiers=True + ... ) + >>> [token.text for token in tokens] + ['parsehttprequest', 'parse', 'http', 'request'] """ return _tokenize( @@ -367,6 +406,11 @@ def tokenize( ngram_min_length=ngram_min_length, ngram_max_length=ngram_max_length, prefix_only=prefix_only, + analyzer=analyzer, + split_identifiers=split_identifiers, + split_on_numerics=split_on_numerics, + preserve_original=preserve_original, + index_operators=index_operators, ) @@ -602,6 +646,8 @@ __all__ = [ "MaterializedView", "MaterializedViewDefinition", "ViewDescription", + "PropertyGraph", + "PropertyGraphDescription", "connect", "connect_async", "tokenize", diff --git a/python/python/lancedb/_blob_reader.py b/python/python/lancedb/_blob_reader.py index c47f8074d..dbc6d4a5e 100644 --- a/python/python/lancedb/_blob_reader.py +++ b/python/python/lancedb/_blob_reader.py @@ -26,6 +26,26 @@ class BlobReader(io.RawIOBase): For local calls, construct a reader from a range-reading callable and the blob's size. The callable accepts an offset and length and returns bytes. + This is also the interface for a reader backed by another engine. + + Examples + -------- + ```python + payload = b"hello world" + + def read_range(offset, length): + return payload[offset : offset + length] + + with BlobReader(read_range, len(payload)) as reader: + assert reader.read_range(6, 5) == b"world" + assert reader.tell() == 0 + assert reader.read(5) == b"hello" + assert reader.tell() == 5 + ``` + + ``read_range`` does not change the sequential cursor. Use ``size()`` for + the declared payload size and close the reader when done; a local reader + owns no server state. """ def __init__(self, read_range: Callable[[int, int], bytes], size: int): diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 2b8d1655a..2ac4dde58 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1,6 +1,17 @@ from datetime import date, datetime, timedelta from decimal import Decimal -from typing import Dict, List, Optional, Sequence, Tuple, Any, TypedDict, Union, Literal +from typing import ( + Callable, + Dict, + List, + Optional, + Sequence, + Tuple, + Any, + TypedDict, + Union, + Literal, +) from uuid import UUID import pyarrow as pa @@ -13,6 +24,7 @@ from .index import ( Bitmap, LabelList, Fm, + NGram, HnswPq, HnswSq, HnswFlat, @@ -26,8 +38,13 @@ from lance_namespace import ( from .remote import ClientConfig from .types import BaseTokenizerType +__version__: str _experimental_functions_enabled: bool +def _doc_url(campaign: str) -> str: ... +def _append_doc_url(message: str, campaign: str) -> str: ... +def _parse_field_path(path: str) -> List[str]: ... + IvfHnswPq: type[HnswPq] = HnswPq IvfHnswSq: type[HnswSq] = HnswSq IvfHnswFlat: type[HnswFlat] = HnswFlat @@ -66,6 +83,11 @@ def tokenize( ngram_min_length: int = 3, ngram_max_length: int = 3, prefix_only: bool = False, + analyzer: Optional[Literal["text", "code"]] = None, + split_identifiers: Optional[bool] = None, + split_on_numerics: Optional[bool] = None, + preserve_original: Optional[bool] = None, + index_operators: Optional[bool] = None, ) -> List["FtsToken"]: ... class PyExpr: @@ -111,6 +133,16 @@ class Session: @property def approx_num_items(self) -> int: ... +class GpuClass: + name: str + resource_name: str + gpu_model: Optional[str] + gpu_memory_bytes: Optional[int] + max_gpu_count_per_worker: Optional[int] + cpu_millis: Optional[int] + memory_bytes: Optional[int] + ephemeral_storage_bytes: Optional[int] + class Connection(object): uri: str async def is_open(self): ... @@ -152,6 +184,7 @@ class Connection(object): limit: Optional[int], ) -> list[str]: ... # Deprecated: Use list_tables instead async def open_job(self, job_id: str) -> Job: ... + async def list_gpu_classes(self) -> list[GpuClass]: ... async def create_function_async( self, request_json: str, namespace_path: Optional[List[str]] = None ) -> Job: ... @@ -168,9 +201,28 @@ class Connection(object): async def drop_function( self, name: str, version: str, namespace_path: Optional[List[str]] = None ) -> bool: ... + async def _drop_function_with_warnings( + self, name: str, version: str, namespace_path: Optional[List[str]] = None + ) -> Tuple[bool, list[str]]: ... async def drop_function_async( self, name: str, version: str, namespace_path: Optional[List[str]] = None ) -> Tuple[bool, Job]: ... + async def create_storage_integration( + self, name: str, request: str, namespace_path: Optional[List[str]] = None + ) -> str: ... + async def describe_storage_integration( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> str: ... + def list_storage_integrations( + self, + *, + namespace_path: Optional[List[str]] = None, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + ) -> NameListing: ... + async def drop_storage_integration( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> None: ... async def create_secret( self, name: str, value: str, namespace_path: Optional[List[str]] = None ) -> None: ... @@ -209,6 +261,25 @@ class Connection(object): page_token: Optional[str] = None, page_limit: Optional[int] = None, ) -> NameListing: ... + async def create_property_graph( + self, + name: str, + definition_json: str, + namespace_path: Optional[List[str]] = None, + ) -> str: ... + async def describe_property_graph( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> str: ... + async def drop_property_graph( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> None: ... + def list_property_graphs( + self, + namespace_path: Optional[List[str]] = None, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + ) -> NameListing: ... def list_jobs( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None ) -> JobListing: ... @@ -331,7 +402,10 @@ class Job: @property def _description(self) -> Optional[JobDescription]: ... async def status(self) -> str: ... - async def wait(self) -> Optional[str]: ... + async def wait( + self, + progress: Optional[Callable[[dict[str, Any]], None]] = None, + ) -> Optional[str]: ... async def cancel(self) -> None: ... async def refresh(self) -> None: ... async def events( @@ -352,6 +426,10 @@ class JobInfo: def state(self) -> str: ... @property def created_at_millis(self) -> int: ... + @property + def progress(self) -> Optional[dict[str, Any]]: ... + @property + def paused(self) -> bool: ... class SessionStatus: @property @@ -390,7 +468,13 @@ class JobFailureInfo: @property def message(self) -> Optional[str]: ... @property + def traceback(self) -> Optional[str]: + """User-code traceback, possibly truncated by the server.""" + ... + @property def retryable(self) -> Optional[bool]: ... + @property + def sql_job_id(self) -> Optional[str]: ... class JobDescription: @property @@ -410,6 +494,8 @@ class JobDescription: @property def result(self) -> Optional[Any]: ... @property + def progress(self) -> Optional[dict[str, Any]]: ... + @property def failure(self) -> Optional[JobFailureInfo]: ... class SqlQuery: @@ -462,6 +548,7 @@ class Table: Bitmap, LabelList, Fm, + NGram, FTS, ], replace: Optional[bool], @@ -484,6 +571,7 @@ class Table: Bitmap, LabelList, Fm, + NGram, FTS, ], replace: Optional[bool], @@ -509,6 +597,9 @@ class Table: ) -> list[FtsToken]: ... async def delete(self, filter: Union[str, PyExpr]) -> DeleteResult: ... async def add_columns(self, columns: list[tuple[str, str]]) -> AddColumnsResult: ... + async def add_columns_from_reader( + self, data: pa.RecordBatchReader + ) -> AddColumnsResult: ... async def add_computed_columns( self, columns: list[tuple[str, str]], @@ -522,8 +613,40 @@ class Table: auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[int] = None, ) -> AddColumnsResult: ... - async def refresh_column(self, column: str) -> RefreshColumnResult: ... - async def refresh_column_async(self, column: str) -> Job: ... + async def refresh_column( + self, + column: str, + *, + where: Optional[str] = None, + batch_size: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + retry_policy: Optional[str] = None, + error_policy: Optional[str] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, + ) -> RefreshColumnResult: ... + async def refresh_column_async( + self, + column: str, + *, + where: Optional[str] = None, + batch_size: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + retry_policy: Optional[str] = None, + error_policy: Optional[str] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, + ) -> Job: ... async def function_errors( self, job_id: Optional[str] = None, @@ -531,10 +654,24 @@ class Table: limit: Optional[int] = None, ) -> FunctionErrors: ... async def refresh_materialized_view( - self, source_version: Optional[int] = None, *, full: bool = False + self, + source_version: Optional[int] = None, + *, + full: bool = False, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> RefreshMaterializedViewResult: ... async def refresh_materialized_view_async( - self, source_version: Optional[int] = None, *, full: bool = False + self, + source_version: Optional[int] = None, + *, + full: bool = False, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> Job: ... async def materialized_view_definition(self) -> str: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... @@ -558,6 +695,9 @@ class Table: async def enable_rte(self, spec: RTEWriteSpec) -> None: ... async def disable_rte(self) -> None: ... async def get_rte_spec(self) -> Optional[RTEWriteSpec]: ... + async def get_table_overrides(self) -> str: ... + async def update_table_overrides(self, overrides_json: str) -> str: ... + async def reset_table_overrides(self) -> str: ... # WAL-PK-FUSION: delete both. def hybrid_pk_fusion_learned(self) -> bool: ... def note_hybrid_pk_fusion(self) -> None: ... @@ -749,6 +889,7 @@ class VectorQuery: def search_effort(self, search_effort: Optional[float]): ... def minimum_nprobes(self, minimum_nprobes: int): ... def maximum_nprobes(self, maximum_nprobes: int): ... + def approx_mode(self, approx_mode: str): ... def bypass_vector_index(self): ... def nearest_to_text(self, query: dict) -> HybridQuery: ... def order_by(self, ordering: Optional[List[ColumnOrdering]]): ... @@ -775,6 +916,7 @@ class HybridQuery: def search_effort(self, search_effort: Optional[float]): ... def minimum_nprobes(self, minimum_nprobes: int): ... def maximum_nprobes(self, maximum_nprobes: int): ... + def approx_mode(self, approx_mode: str): ... def bypass_vector_index(self): ... def order_by(self, ordering: Optional[List[ColumnOrdering]]): ... def to_vector_query(self) -> VectorQuery: ... @@ -790,6 +932,7 @@ class PyQueryRequest: limit: Optional[int] offset: Optional[int] take_offsets: Optional[List[int]] + take_row_ids: Optional[List[int]] filter: Optional[Union[str, bytes]] full_text_search: Optional[FullTextQuery] select: Optional[Union[str, List[str]]] @@ -806,6 +949,7 @@ class PyQueryRequest: lower_bound: Optional[float] upper_bound: Optional[float] ef: Optional[int] + approx_mode: Optional[str] refine_factor: Optional[int] distance_type: Optional[str] bypass_vector_index: Optional[bool] @@ -899,15 +1043,20 @@ class RefreshColumnResult: version: int class FunctionErrorRecord: + attempts: Optional[int] job_id: str fragment_id: int row_offset: Optional[int] + row_id: Optional[int] + row_address: Optional[int] column: str function: str function_version: str table_version: int error_type: str error_message: str + traceback: Optional[str] + """User-code traceback, possibly truncated by the server.""" created_at_millis: int class FunctionErrorFragment: @@ -1080,6 +1229,10 @@ class AuthzObject: database: str, namespace_path: Sequence[str], name: str ) -> AuthzObject: ... @staticmethod + def storage_integration( + database: str, namespace: Sequence[str], name: str + ) -> AuthzObject: ... + @staticmethod def secret( database: str, namespace_path: Sequence[str], name: str ) -> AuthzObject: ... @@ -1089,3 +1242,5 @@ class AuthzObject: ) -> AuthzObject: ... def __str__(self) -> str: ... def __repr__(self) -> str: ... + +def validate_function_retry_policy(json: str) -> None: ... diff --git a/python/python/lancedb/authz.py b/python/python/lancedb/authz.py index e62a276cf..cb7d04ed2 100644 --- a/python/python/lancedb/authz.py +++ b/python/python/lancedb/authz.py @@ -172,6 +172,17 @@ class Object: """A secret, defaulting to the database's public namespace.""" return cls(str(_lancedb.AuthzObject.secret(database, namespace_path, name))) + @classmethod + def storage_integration( + cls, *, database: str, name: str, namespace_path: Sequence[str] = ("public",) + ) -> "Object": + """A database storage integration, defaulting to its public namespace.""" + return cls( + str( + _lancedb.AuthzObject.storage_integration(database, namespace_path, name) + ) + ) + @classmethod def function( cls, *, database: str, name: str, namespace_path: Sequence[str] = ("public",) @@ -217,6 +228,7 @@ class Privilege(str, Enum): CREATE_SECRET = "CREATE_SECRET" CREATE_FUNCTION = "CREATE_FUNCTION" OPERATE = "OPERATE" + CREATE_STORAGE_INTEGRATION = "CREATE_STORAGE_INTEGRATION" @dataclass(frozen=True) diff --git a/python/python/lancedb/catalog.py b/python/python/lancedb/catalog.py index 9a0dc3412..338be98b8 100644 --- a/python/python/lancedb/catalog.py +++ b/python/python/lancedb/catalog.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Remote catalogs manage databases through a server's root namespace.""" +"""Remote catalogs manage databases.""" from functools import cached_property from datetime import timedelta diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index e13e3dc9c..e73a44aec 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -8,7 +8,10 @@ from abc import abstractmethod import asyncio from datetime import timedelta from pathlib import Path +from dataclasses import asdict +import json import sys +import warnings from typing import ( TYPE_CHECKING, Any, @@ -55,9 +58,17 @@ from lance_namespace import ( from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from . import __version__ -from ._lancedb import connect as lancedb_connect # type: ignore -from .functions import FunctionVersion, UdfDefinition +from ._lancedb import _append_doc_url, connect as lancedb_connect # type: ignore +from .functions import FunctionVersion, FunctionDefinition +from .graph import ( + AsyncPropertyGraph, + EdgeTable, + NodeTable, + PropertyGraph, + _definition_json, +) from .job import AsyncJob, Job, _typed_job +from .storage_integration import SecretReference, StorageIntegrationInfo from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery from .sql import QueryDescription, QueryParameters, to_parameter_batch @@ -94,6 +105,7 @@ if TYPE_CHECKING: from .pydantic import LanceModel from ._lancedb import Connection as LanceDbConnection + from ._lancedb import GpuClass from ._lancedb import JobInfo from .common import DATA, URI from .embeddings import EmbeddingFunctionConfig @@ -375,6 +387,45 @@ class DBConnection(EnforceOverrides): """ pass + def create_storage_integration( + self, + name: str, + storage_prefix: str, + *, + aws_role_arn: Optional[str] = None, + aws_access_key_id_secret: Optional[Union[str, SecretReference]] = None, + aws_secret_access_key_secret: Optional[Union[str, SecretReference]] = None, + aws_region: Optional[str] = None, + storage_provider: Literal["S3", "AZURE", "GCP", "HUGGINGFACE"] = "S3", + azure_storage_account: Optional[str] = None, + azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None, + azure_client_id_secret: Optional[Union[str, SecretReference]] = None, + azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, + gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, + huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + namespace_path: Optional[List[str]] = None, + ) -> StorageIntegrationInfo: + raise NotImplementedError + + def describe_storage_integration( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> StorageIntegrationInfo: + raise NotImplementedError + + def list_storage_integrations( + self, + *, + namespace_path: Optional[List[str]] = None, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + ) -> Listing[str]: + raise NotImplementedError + + def drop_storage_integration( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> None: + raise NotImplementedError + @abstractmethod def create_table( self, @@ -632,7 +683,7 @@ class DBConnection(EnforceOverrides): LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it - disabled; LanceDB Distributed operations remain available. + disabled; LanceDB Enterprise operations remain available. The view is populated before creation returns. Pass ``with_no_data=True`` to create only its definition and empty backing @@ -656,11 +707,11 @@ class DBConnection(EnforceOverrides): with_no_data: bool, default False Skip the initial refresh and leave the backing table empty. auto_refresh_enabled: bool, optional - Enable or disable automatic refresh in LanceDB Distributed. + Enable or disable automatic refresh in LanceDB Enterprise. When omitted, the server determines whether automatic refresh is enabled. LanceDB Embedded does not support automatic refresh. auto_refresh_interval_seconds: float, optional - Positive, finite refresh interval in seconds in LanceDB Distributed. + Positive, finite refresh interval in seconds in LanceDB Enterprise. When omitted, the server determines when to refresh. Returns @@ -668,7 +719,10 @@ class DBConnection(EnforceOverrides): MaterializedView """ raise NotImplementedError( - "materialized views are not supported on this connection type" + _append_doc_url( + "materialized views are not supported on this connection type", + "materialized_views", + ) ) def create_materialized_view_async( @@ -686,14 +740,20 @@ class DBConnection(EnforceOverrides): """Submit materialized-view creation and return its job. The job may already be complete in LanceDB Embedded. In LanceDB - Distributed, creation - submits CREATE MATERIALIZED VIEW through the SQL server. Its job has - ``job_type == "query"`` and ``id`` identifies the connection-scoped - query. Registry event history is unavailable. + Distributed, creation submits CREATE MATERIALIZED VIEW through the SQL + server and the returned ``id`` is the registry job ID. That ID can be + reopened with :meth:`open_job`, and the handle supports registry + progress, events, cancellation, and ``wait`` while the job runs. Wait for the job before opening or querying the view. + + Servers without early registry-handle support return a connection-scoped + query job instead. Its ID cannot be reopened with :meth:`open_job`. """ raise NotImplementedError( - "materialized views are not supported on this connection type" + _append_doc_url( + "materialized views are not supported on this connection type", + "materialized_views", + ) ) def open_materialized_view(self, name: str) -> MaterializedView: @@ -703,7 +763,10 @@ class DBConnection(EnforceOverrides): view. """ raise NotImplementedError( - "materialized views are not supported on this connection type" + _append_doc_url( + "materialized views are not supported on this connection type", + "materialized_views", + ) ) def list_materialized_views( @@ -718,7 +781,10 @@ class DBConnection(EnforceOverrides): iteration. See [pagination state][lancedb.listing.AsyncListing]. """ raise NotImplementedError( - "materialized views are not supported on this connection type" + _append_doc_url( + "materialized views are not supported on this connection type", + "materialized_views", + ) ) def drop_materialized_view( @@ -726,12 +792,15 @@ class DBConnection(EnforceOverrides): ) -> None: """Drop a materialized view. - In LanceDB Distributed, drops wait for the SQL command to remove the + In LanceDB Enterprise, drops wait for the SQL command to remove the catalog binding. Physical cleanup continues in the background. """ raise NotImplementedError( - "materialized views are not supported on this connection type" + _append_doc_url( + "materialized views are not supported on this connection type", + "materialized_views", + ) ) def drop_materialized_view_async( @@ -740,12 +809,15 @@ class DBConnection(EnforceOverrides): """Start dropping a materialized view and return its job. The job may already be complete in LanceDB Embedded. In LanceDB - Distributed, jobs have + Enterprise, jobs have type ``query`` and use the SQL query ID as ``id``. Waiting confirms catalog removal; physical cleanup continues in the background. """ raise NotImplementedError( - "materialized views are not supported on this connection type" + _append_doc_url( + "materialized views are not supported on this connection type", + "materialized_views", + ) ) def drop_table(self, name: str, namespace_path: Optional[List[str]] = None): @@ -816,8 +888,7 @@ class DBConnection(EnforceOverrides): """ Drop all tables from the database - LanceDB Distributed does not currently support this operation. Use - ``list_tables()`` and ``drop_table()`` to drop tables individually. + Lists the tables in the selected namespace and drops them one at a time. Parameters ---------- @@ -888,12 +959,12 @@ class DBConnection(EnforceOverrides): def create_function( self, - definition: UdfDefinition, + definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, namespace_path: Optional[List[str]] = None, ) -> FunctionVersion: - """Build and register a scalar Python UDF, then return its version. + """Build and register a scalar Python function, then return its version. The server builds the OCI image and registers the completed artifact. This is the blocking counterpart of :meth:`create_function_async`. @@ -901,8 +972,8 @@ class DBConnection(EnforceOverrides): Parameters ---------- - definition : UdfDefinition - A callable decorated with [udf][lancedb.udf]. + definition : FunctionDefinition + A callable decorated with [function][lancedb.function]. secrets : sequence of EnvVarSecret, optional One [EnvVarSecret][lancedb.secrets.EnvVarSecret] per credential the Function needs, each naming a Secret and the environment variable @@ -915,12 +986,12 @@ class DBConnection(EnforceOverrides): Examples -------- ```python - db.create_secret("openai-prod", os.environ["OPENAI_API_KEY"]) + db.create_secret("model-api-key", os.environ["MODEL_API_KEY"]) db.create_function( analyze_caption, secrets=[ EnvVarSecret( - secret_name="openai-prod", env_variable="OPENAI_API_KEY" + secret_name="model-api-key", env_variable="MODEL_API_KEY" ) ], ) @@ -932,19 +1003,24 @@ class DBConnection(EnforceOverrides): def create_function_async( self, - definition: UdfDefinition, + definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: - """Submit a scalar Python UDF for building and registration. + """Submit a scalar Python function for building and registration. The server-side job builds the OCI image, then registers the completed - artifact. Waiting on the job returns the immutable Function version. + artifact. The returned job has type ``query`` and the SQL query UUID as + its ID. Waiting on it returns the immutable Function version. LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( - "Function catalog operations are not supported for this connection type" + _append_doc_url( + "Function catalog operations are not supported " + "for this connection type", + "functions", + ) ) def get_function( @@ -956,7 +1032,11 @@ class DBConnection(EnforceOverrides): ) -> FunctionVersion: """Open one exact immutable Function version from the remote catalog.""" raise NotImplementedError( - "Function catalog operations are not supported for this connection type" + _append_doc_url( + "Function catalog operations are not supported " + "for this connection type", + "functions", + ) ) def list_functions( @@ -969,7 +1049,9 @@ class DBConnection(EnforceOverrides): """List every published immutable Function version in a namespace. Functions in child namespaces are not included. Results are ordered by - Function name then version. LanceDB Embedded connections raise + Function name then numeric version. Remote connections use + ``SHOW FUNCTIONS HISTORY`` to include every revision. + LanceDB Embedded connections raise ``NotImplementedError``. Examples @@ -985,7 +1067,11 @@ class DBConnection(EnforceOverrides): iteration. See [pagination state][lancedb.listing.AsyncListing]. """ raise NotImplementedError( - "Function catalog operations are not supported for this connection type" + _append_doc_url( + "Function catalog operations are not supported " + "for this connection type", + "functions", + ) ) def drop_function( @@ -995,16 +1081,24 @@ class DBConnection(EnforceOverrides): version: str, namespace_path: Optional[List[str]] = None, ) -> bool: - """Drop a Function name and the object it was bound to. + """Drop one published Function revision, preserving its siblings. - The requested version must exist in the currently named object. Returns - True when the name was removed and False when it was absent. The - object's content is deleted with it, which may finish after this - returns; use :meth:`drop_function_async` to wait for that. Local - connections raise NotImplementedError. + Returns True when the revision was removed and False for a repeated drop + or a missing name. A revision never published under an existing name is + an error. Dropping the last visible revision releases the name and + schedules physical cleanup in the background. When the remote server + reports dependent warnings, they are emitted as ``UserWarning`` before + this method returns. Use + :meth:`drop_function_async` to + access the query job, whose completion confirms catalog removal of the + revision. Local connections raise NotImplementedError. """ raise NotImplementedError( - "Function catalog operations are not supported for this connection type" + _append_doc_url( + "Function catalog operations are not supported " + "for this connection type", + "functions", + ) ) def drop_function_async( @@ -1014,16 +1108,21 @@ class DBConnection(EnforceOverrides): version: str, namespace_path: Optional[List[str]] = None, ) -> Tuple[bool, Job]: - """Drop a Function name and return its cleanup job. + """Drop one Function revision and return its SQL query job. - The name is unbound before this returns; the object's content may still - be being deleted. Call :meth:`Job.wait` to wait for that to finish. When - the server deletes inline, or when nothing was bound, the returned job - is already finished and has no id. LanceDB Embedded connections raise - NotImplementedError. + The boolean reports removal of the requested revision from the catalog; + sibling revisions and their grants remain available. The job has type + ``query`` and its ID is the SQL query UUID. Repeated waits confirm that + revision's removal. Only the last visible revision's drop releases the + name and schedules background object cleanup. LanceDB Embedded + connections raise NotImplementedError. """ raise NotImplementedError( - "Function catalog operations are not supported for this connection type" + _append_doc_url( + "Function catalog operations are not supported " + "for this connection type", + "functions", + ) ) def create_secret( @@ -1037,7 +1136,10 @@ class DBConnection(EnforceOverrides): connections raise ``NotImplementedError``. """ raise NotImplementedError( - "Secret operations are not supported for this connection type" + _append_doc_url( + "Secret operations are not supported for this connection type", + "secrets", + ) ) def alter_secret( @@ -1051,7 +1153,10 @@ class DBConnection(EnforceOverrides): before it. LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( - "Secret operations are not supported for this connection type" + _append_doc_url( + "Secret operations are not supported for this connection type", + "secrets", + ) ) def list_secrets( @@ -1072,7 +1177,10 @@ class DBConnection(EnforceOverrides): iteration. See [pagination state][lancedb.listing.AsyncListing]. """ raise NotImplementedError( - "Secret operations are not supported for this connection type" + _append_doc_url( + "Secret operations are not supported for this connection type", + "secrets", + ) ) def drop_secret( @@ -1086,7 +1194,10 @@ class DBConnection(EnforceOverrides): LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( - "Secret operations are not supported for this connection type" + _append_doc_url( + "Secret operations are not supported for this connection type", + "secrets", + ) ) def describe_secret( @@ -1098,7 +1209,10 @@ class DBConnection(EnforceOverrides): connections raise ``NotImplementedError``. """ raise NotImplementedError( - "Secret operations are not supported for this connection type" + _append_doc_url( + "Secret operations are not supported for this connection type", + "secrets", + ) ) def create_view( @@ -1123,7 +1237,10 @@ class DBConnection(EnforceOverrides): name: string """ raise NotImplementedError( - "View operations are not supported for this connection type" + _append_doc_url( + "View operations are not supported for this connection type", + "views", + ) ) def describe_view( @@ -1137,34 +1254,43 @@ class DBConnection(EnforceOverrides): ``NotImplementedError``. """ raise NotImplementedError( - "View operations are not supported for this connection type" + _append_doc_url( + "View operations are not supported for this connection type", + "views", + ) ) def drop_view( self, name: str, *, namespace_path: Optional[List[str]] = None ) -> None: - """Drop a view and wait for its definition to be deleted. + """Drop a view and wait for catalog removal. The tables it reads are untouched: a view holds no rows of its own. Use - :meth:`drop_view_async` to get the cleanup job instead of waiting on it. + :meth:`drop_view_async` to retain its SQL query job. Completion confirms + catalog removal; physical cleanup continues in the background. LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( - "View operations are not supported for this connection type" + _append_doc_url( + "View operations are not supported for this connection type", + "views", + ) ) def drop_view_async( self, name: str, *, namespace_path: Optional[List[str]] = None ) -> "Job[None]": - """Start dropping a view and return the job deleting its definition. + """Drop a view and return its SQL query job. - The name is free before this returns. Call :meth:`Job.wait` to wait for - the definition dataset to be deleted. When nothing was bound to the - name, the returned job is already finished and has no id. Local - connections raise ``NotImplementedError``. + The job has type ``query`` and its ID is the SQL query UUID. Call + :meth:`Job.wait` to confirm catalog removal. Physical cleanup continues + in the background. Local connections raise ``NotImplementedError``. """ raise NotImplementedError( - "View operations are not supported for this connection type" + _append_doc_url( + "View operations are not supported for this connection type", + "views", + ) ) def list_views( @@ -1185,7 +1311,103 @@ class DBConnection(EnforceOverrides): iteration. See [pagination state][lancedb.listing.AsyncListing]. """ raise NotImplementedError( - "View operations are not supported for this connection type" + _append_doc_url( + "View operations are not supported for this connection type", + "views", + ) + ) + + def create_property_graph( + self, + name: str, + nodes: Sequence[NodeTable], + edges: Sequence[EdgeTable] = (), + *, + namespace_path: Optional[List[str]] = None, + ) -> PropertyGraph: + """Create a property graph over tables in its namespace. + + Each [NodeTable][lancedb.graph.NodeTable] names the table holding one + label's nodes and its key column, and each + [EdgeTable][lancedb.graph.EdgeTable] the table holding one label's + edges and the node keys its source and destination columns reference + -- the shape of SQL/PGQ's ``CREATE PROPERTY GRAPH``. The graph stores + nothing else: a query reads its tables through SQL ``GRAPH_TABLE``, as + they are when it runs. + + The database checks the definition against the tables now, so one they + cannot satisfy is refused here rather than at the first query. A name + another property graph holds is an error. Local connections raise + ``NotImplementedError``. + + >>> import lancedb + >>> from lancedb.graph import EdgeTable, Endpoint, NodeTable + >>> db = lancedb.connect("db://my_database") # doctest: +SKIP + >>> graph = db.create_property_graph( + ... "social", + ... nodes=[NodeTable("person", key="person_id", label="Person")], + ... edges=[ + ... EdgeTable( + ... "knows", + ... label="KNOWS", + ... source=Endpoint("src_id", references=("person", "person_id")), + ... destination=Endpoint( + ... "dst_id", references=("person", "person_id") + ... ), + ... ) + ... ], + ... ) # doctest: +SKIP + >>> graph.describe().nodes[0].properties # doctest: +SKIP + ['person_id', 'name'] + """ + raise NotImplementedError( + "Property graph operations are not supported for this connection type" + ) + + def open_property_graph( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> PropertyGraph: + """Open the property graph named ``name``. + + The graph is described to check that it exists, so a name no property + graph holds raises [HttpError][lancedb.remote.errors.HttpError] with + ``status_code`` 404. Local connections raise ``NotImplementedError``. + """ + raise NotImplementedError( + "Property graph operations are not supported for this connection type" + ) + + def drop_property_graph( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> None: + """Drop a property graph and wait for its definition to be deleted. + + The tables it reads are untouched: a property graph holds no rows of + its own. Local connections raise ``NotImplementedError``. + """ + raise NotImplementedError( + "Property graph operations are not supported for this connection type" + ) + + def list_property_graphs( + self, + *, + namespace_path: Optional[List[str]] = None, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + ) -> Listing[str]: + """The names of the property graphs in one namespace. + + Names only; a definition comes from + [PropertyGraph.describe][lancedb.graph.PropertyGraph.describe]. Local + connections raise ``NotImplementedError``. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total; + ``page_token`` resumes from a saved token. Requests and errors occur during + iteration. See [pagination state][lancedb.listing.AsyncListing]. + """ + raise NotImplementedError( + "Property graph operations are not supported for this connection type" ) def open_job(self, job_id: str) -> Job: @@ -1199,7 +1421,30 @@ class DBConnection(EnforceOverrides): Raises `JobNotFoundError` when the server has no such job, the way `open_table` does for a missing table. """ - raise NotImplementedError("open_job is not supported for this connection type") + raise NotImplementedError( + _append_doc_url( + "open_job is not supported for this connection type", + "jobs", + ) + ) + + def list_gpu_classes(self) -> List[GpuClass]: + """List the operator-configured Function GPU classes. + + Each record names the class and reports its configured GPU model, + memory, per-worker GPU limit, and CPU, memory, and ephemeral-storage + limits. This describes configured hardware, not current free capacity. + + LanceDB Enterprise only; the principal needs System Usage permission. + Raises ``NotImplementedError`` when the server predates + ``GET /v1/gpu/classes``. + """ + raise NotImplementedError( + _append_doc_url( + "GPU class discovery is not supported for this connection type", + "gpu_classes", + ) + ) def list_jobs( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None @@ -1210,7 +1455,12 @@ class DBConnection(EnforceOverrides): ``page_token`` resumes from a saved token. Requests and errors occur during iteration. See [pagination state][lancedb.listing.AsyncListing]. """ - raise NotImplementedError("list_jobs is not supported for this connection type") + raise NotImplementedError( + _append_doc_url( + "list_jobs is not supported for this connection type", + "jobs", + ) + ) def cancel_job(self, job_id: str) -> bool: """Request cancellation of a server-side job by id. @@ -1220,7 +1470,10 @@ class DBConnection(EnforceOverrides): success. """ raise NotImplementedError( - "cancel_job is not supported for this connection type" + _append_doc_url( + "cancel_job is not supported for this connection type", + "jobs", + ) ) def pause_job(self, job_id: str) -> str: @@ -1230,7 +1483,12 @@ class DBConnection(EnforceOverrides): "pausing", "already_paused", or "committing" -- a job finalizing its results cannot be parked; retry shortly. """ - raise NotImplementedError("pause_job is not supported for this connection type") + raise NotImplementedError( + _append_doc_url( + "pause_job is not supported for this connection type", + "jobs", + ) + ) def resume_job(self, job_id: str) -> str: """Resume a paused server-side job by id. @@ -1240,7 +1498,10 @@ class DBConnection(EnforceOverrides): confirmed yet; retry shortly -- or "not_paused". """ raise NotImplementedError( - "resume_job is not supported for this connection type" + _append_doc_url( + "resume_job is not supported for this connection type", + "jobs", + ) ) def execute_query( @@ -1296,11 +1557,15 @@ class DBConnection(EnforceOverrides): LanceDB Embedded connections do not support SQL. """ - raise NotImplementedError("SQL is not supported for this connection type") + raise NotImplementedError( + _append_doc_url("SQL is not supported for this connection type", "sql") + ) def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription: """Describe a submitted SQL query by its connection-scoped id.""" - raise NotImplementedError("SQL is not supported for this connection type") + raise NotImplementedError( + _append_doc_url("SQL is not supported for this connection type", "sql") + ) class LanceDBConnection(DBConnection): @@ -1774,7 +2039,7 @@ class LanceDBConnection(DBConnection): LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it - disabled; LanceDB Distributed operations remain available. + disabled; LanceDB Enterprise operations remain available. See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. @@ -2022,7 +2287,7 @@ class LanceDBConnection(DBConnection): @override def create_function_async( self, - definition: UdfDefinition, + definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, namespace_path: Optional[List[str]] = None, @@ -2099,6 +2364,76 @@ class LanceDBConnection(DBConnection): ) return dropped, Job(job) + @override + def create_storage_integration( + self, + name: str, + storage_prefix: str, + *, + aws_role_arn: Optional[str] = None, + aws_access_key_id_secret: Optional[Union[str, SecretReference]] = None, + aws_secret_access_key_secret: Optional[Union[str, SecretReference]] = None, + aws_region: Optional[str] = None, + storage_provider: Literal["S3", "AZURE", "GCP", "HUGGINGFACE"] = "S3", + azure_storage_account: Optional[str] = None, + azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None, + azure_client_id_secret: Optional[Union[str, SecretReference]] = None, + azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, + gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, + huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + namespace_path: Optional[List[str]] = None, + ) -> StorageIntegrationInfo: + return LOOP.run( + self._conn.create_storage_integration( + name, + storage_prefix, + aws_role_arn=aws_role_arn, + aws_access_key_id_secret=aws_access_key_id_secret, + aws_secret_access_key_secret=aws_secret_access_key_secret, + aws_region=aws_region, + storage_provider=storage_provider, + azure_storage_account=azure_storage_account, + azure_tenant_id_secret=azure_tenant_id_secret, + azure_client_id_secret=azure_client_id_secret, + azure_client_secret_secret=azure_client_secret_secret, + gcp_credentials_json_secret=gcp_credentials_json_secret, + huggingface_token_secret=huggingface_token_secret, + namespace_path=namespace_path, + ) + ) + + @override + def describe_storage_integration( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> StorageIntegrationInfo: + return LOOP.run( + self._conn.describe_storage_integration(name, namespace_path=namespace_path) + ) + + @override + def list_storage_integrations( + self, + *, + namespace_path: Optional[List[str]] = None, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + ) -> Listing[str]: + return Listing( + self._conn.list_storage_integrations( + namespace_path=namespace_path, + page_token=page_token, + page_limit=page_limit, + ) + ) + + @override + def drop_storage_integration( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> None: + LOOP.run( + self._conn.drop_storage_integration(name, namespace_path=namespace_path) + ) + @override def create_secret( self, name: str, value: str, *, namespace_path: Optional[List[str]] = None @@ -2195,6 +2530,61 @@ class LanceDBConnection(DBConnection): ) ) + @override + def create_property_graph( + self, + name: str, + nodes: Sequence[NodeTable], + edges: Sequence[EdgeTable] = (), + *, + namespace_path: Optional[List[str]] = None, + ) -> PropertyGraph: + return PropertyGraph( + LOOP.run( + self._conn.create_property_graph( + name, nodes, edges, namespace_path=namespace_path + ) + ) + ) + + @override + def open_property_graph( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> PropertyGraph: + return PropertyGraph( + LOOP.run( + self._conn.open_property_graph(name, namespace_path=namespace_path) + ) + ) + + @override + def drop_property_graph( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> None: + LOOP.run(self._conn.drop_property_graph(name, namespace_path=namespace_path)) + + @override + def list_property_graphs( + self, + *, + namespace_path: Optional[List[str]] = None, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + ) -> Listing[str]: + """List property graphs. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total; + ``page_token`` resumes from a saved token. Requests and errors occur during + iteration. See [pagination state][lancedb.listing.AsyncListing]. + """ + return Listing( + self._conn.list_property_graphs( + namespace_path=namespace_path, + page_token=page_token, + page_limit=page_limit, + ) + ) + @override def list_jobs( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None @@ -2269,12 +2659,12 @@ class AsyncConnection(object): To obtain a connection you can use the [connect_async][lancedb.connect_async] function. - This could be a LanceDB Embedded connection (using lance) or a LanceDB Distributed - connection (e.g. for connecting to LanceDB Enterprise) + This could be a LanceDB Embedded connection (using Lance) or a connection + to LanceDB Enterprise. Embedded connections do not currently hold any open resources but they may do so in the future (for example, for shared cache or connections to catalog services) - Distributed connections represent an open connection to the server. The + Enterprise connections represent an open connection to the server. The [close][lancedb.db.AsyncConnection.close] method can be used to release any underlying resources eagerly. The connection can also be used as a context manager. @@ -2911,7 +3301,7 @@ class AsyncConnection(object): LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it - disabled; LanceDB Distributed operations remain available. + disabled; LanceDB Enterprise operations remain available. See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. """ @@ -2946,7 +3336,7 @@ class AsyncConnection(object): """Submit materialized-view creation and return its job. Wait for the returned job before opening or querying the view. In LanceDB - Distributed, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` + Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` identifies that query on this connection. """ source, native_options = await self._materialized_view_source( @@ -3000,7 +3390,7 @@ class AsyncConnection(object): ) -> None: """Drop a materialized view. - In LanceDB Distributed, drops wait for the SQL command to remove the + In LanceDB Enterprise, drops wait for the SQL command to remove the catalog binding. Physical cleanup continues in the background. """ @@ -3016,7 +3406,7 @@ class AsyncConnection(object): ) -> AsyncJob[None]: """Start dropping a materialized view and return its job. - In LanceDB Distributed, the job has type ``query`` and its ID identifies + In LanceDB Enterprise, the job has type ``query`` and its ID identifies the SQL query. Await :meth:`AsyncJob.wait` for catalog removal; physical cleanup continues in the background. """ @@ -3160,6 +3550,8 @@ class AsyncConnection(object): async def drop_all_tables(self, namespace_path: Optional[List[str]] = None): """Drop all tables from the database. + Lists the tables in the selected namespace and drops them one at a time. + Parameters ---------- namespace_path: List[str], optional @@ -3176,25 +3568,32 @@ class AsyncConnection(object): """ return AsyncJob(await self._inner.open_job(job_id)) + async def list_gpu_classes(self) -> List[GpuClass]: + """List configured Function GPU classes. See + [DBConnection.list_gpu_classes][lancedb.db.DBConnection.list_gpu_classes]. + """ + return await self._inner.list_gpu_classes() + async def create_function_async( self, - definition: UdfDefinition, + definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, namespace_path: Optional[List[str]] = None, ) -> AsyncJob[FunctionVersion]: - """Submit a scalar Python UDF for building and registration. + """Submit a scalar Python function for building and registration. The server-side job builds the OCI image, then registers the completed - artifact. Waiting on the job returns the immutable Function version. + artifact. The returned job has type ``query`` and the SQL query UUID as + its ID. Waiting on it returns the immutable Function version. ``secrets`` is a sequence of [EnvVarSecret][lancedb.secrets.EnvVarSecret], each naming a Secret and the environment variable its value arrives in. ``namespace_path`` is the namespace the Function is registered in; None or an empty list is the root. LanceDB Embedded connections raise ``NotImplementedError``. """ - if not isinstance(definition, UdfDefinition): - raise TypeError("create_function_async requires a @udf definition") + if not isinstance(definition, FunctionDefinition): + raise TypeError("create_function_async requires a @function definition") request = definition.bind_secrets(secrets) inner = await self._inner.create_function_async( request.to_canonical_json(), namespace_path @@ -3246,8 +3645,34 @@ class AsyncConnection(object): version: str, namespace_path: Optional[List[str]] = None, ) -> bool: - """Drop a Function name and the object it was bound to.""" - return await self._inner.drop_function(name, version, namespace_path) + """Drop one published Function revision, preserving its siblings. + + Returns True when the requested revision was removed and False for a + repeated drop or a missing name. A revision never published under an + existing name is an error. Only the last visible revision's removal + releases the name and schedules background object cleanup. When the + remote server reports a warning, it is emitted as ``UserWarning`` + before this method returns, subject to the standard ``warnings`` + filters. A warnings-as-errors setting can therefore raise after the + catalog removal; it does not roll back the drop. Older servers that + omit the warning field remain silent. + """ + dropped, drop_warnings = await self._drop_function_with_warnings( + name, version, namespace_path + ) + for warning in drop_warnings: + warnings.warn(warning, UserWarning, stacklevel=2) + return dropped + + async def _drop_function_with_warnings( + self, + name: str, + version: str, + namespace_path: Optional[List[str]] = None, + ) -> Tuple[bool, List[str]]: + return await self._inner._drop_function_with_warnings( + name, version, namespace_path + ) async def drop_function_async( self, @@ -3256,17 +3681,201 @@ class AsyncConnection(object): version: str, namespace_path: Optional[List[str]] = None, ) -> Tuple[bool, AsyncJob]: - """Drop a Function name and return its cleanup job. + """Drop one Function revision and return its SQL query job. - The name is unbound before this returns; the object's content may still - be being deleted. Await :meth:`AsyncJob.wait` to wait for that to - finish. + The boolean reports removal of the requested revision from the catalog; + sibling revisions and their grants remain available. The job has type + ``query`` and its ID is the SQL query UUID. Repeated waits confirm that + revision's removal. Only the last visible revision's drop releases the + name and schedules background object cleanup. """ dropped, job = await self._inner.drop_function_async( name, version, namespace_path ) return dropped, AsyncJob(job) + async def create_storage_integration( + self, + name: str, + storage_prefix: str, + *, + aws_role_arn: Optional[str] = None, + aws_access_key_id_secret: Optional[Union[str, SecretReference]] = None, + aws_secret_access_key_secret: Optional[Union[str, SecretReference]] = None, + aws_region: Optional[str] = None, + storage_provider: Literal["S3", "AZURE", "GCP", "HUGGINGFACE"] = "S3", + azure_storage_account: Optional[str] = None, + azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None, + azure_client_id_secret: Optional[Union[str, SecretReference]] = None, + azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, + gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, + huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + namespace_path: Optional[List[str]] = None, + ) -> StorageIntegrationInfo: + """Register cloud storage access using database-owned credential Secrets. + + ``namespace_path`` follows Secret naming rules. A SecretReference can name + another database; a string names a root Secret in this database. + For Azure, set ``storage_provider="AZURE"``, ``azure_storage_account``, + and Secret references for tenant ID, client ID and client secret. + For GCP, set ``storage_provider="GCP"`` and ``gcp_credentials_json_secret`` + to a Secret containing the application credentials JSON file content. + For Hugging Face, set ``storage_provider="HUGGINGFACE"`` and + optionally set ``huggingface_token_secret`` to a Secret containing the + token; omitting it selects anonymous access at the default rate limits. + Registration returns setup instructions without verifying storage access. + """ + azure_options = ( + azure_tenant_id_secret, + azure_client_id_secret, + azure_client_secret_secret, + ) + if storage_provider != "HUGGINGFACE" and huggingface_token_secret is not None: + raise ValueError( + "Hugging Face options require storage_provider HUGGINGFACE" + ) + if storage_provider != "GCP" and gcp_credentials_json_secret is not None: + raise ValueError("GCP credential options require storage_provider GCP") + if storage_provider == "HUGGINGFACE": + if any( + value is not None + for value in azure_options + + ( + azure_storage_account, + aws_role_arn, + aws_access_key_id_secret, + aws_secret_access_key_secret, + aws_region, + gcp_credentials_json_secret, + ) + ): + raise ValueError("Hugging Face cannot contain other cloud options") + elif storage_provider == "GCP": + if gcp_credentials_json_secret is None: + raise ValueError("GCP requires gcp_credentials_json_secret") + if azure_storage_account is not None or any( + value is not None + for value in azure_options + + ( + aws_role_arn, + aws_access_key_id_secret, + aws_secret_access_key_secret, + aws_region, + ) + ): + raise ValueError("GCP integrations cannot contain AWS or Azure options") + elif storage_provider == "AZURE": + if not azure_storage_account or any( + value is None for value in azure_options + ): + raise ValueError( + "Azure requires a storage account and " + "all three credential Secret references" + ) + if any( + value is not None + for value in ( + aws_role_arn, + aws_access_key_id_secret, + aws_secret_access_key_secret, + aws_region, + ) + ): + raise ValueError("Azure integrations cannot contain AWS options") + elif storage_provider == "S3": + if azure_storage_account is not None or any( + value is not None for value in azure_options + ): + raise ValueError("S3 integrations cannot contain Azure options") + role_mode = aws_role_arn is not None + key_mode = ( + aws_access_key_id_secret is not None + and aws_secret_access_key_secret is not None + ) + if role_mode == key_mode or ( + role_mode + and ( + aws_access_key_id_secret is not None + or aws_secret_access_key_secret is not None + ) + ): + raise ValueError( + "Specify either aws_role_arn or " + "both AWS credential Secret references" + ) + + else: + raise ValueError("storage_provider must be S3, AZURE, GCP or HUGGINGFACE") + + def reference(value): + if value is None: + return None + if isinstance(value, str): + value = SecretReference(value) + if not isinstance(value, SecretReference): + raise TypeError( + "Credential secrets must be names or SecretReference objects" + ) + return asdict(value) + + request = { + "storage_provider": storage_provider, + "storage_prefix": storage_prefix, + "aws_role_arn": aws_role_arn, + "aws_region": aws_region, + "azure_storage_account": azure_storage_account, + "azure_tenant_id_secret": reference(azure_tenant_id_secret), + "azure_client_id_secret": reference(azure_client_id_secret), + "azure_client_secret_secret": reference(azure_client_secret_secret), + "gcp_credentials_json_secret": reference(gcp_credentials_json_secret), + "huggingface_token_secret": reference(huggingface_token_secret), + "aws_access_key_id_secret": reference(aws_access_key_id_secret), + "aws_secret_access_key_secret": reference(aws_secret_access_key_secret), + } + info = await self._inner.create_storage_integration( + validate_secret_name(name), + json.dumps(request), + list(validate_namespace_path(namespace_path)), + ) + return StorageIntegrationInfo(**json.loads(info)) + + async def describe_storage_integration( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> StorageIntegrationInfo: + """Return configuration and Secret references without credential values.""" + return StorageIntegrationInfo( + **json.loads( + await self._inner.describe_storage_integration( + validate_secret_name(name), + list(validate_namespace_path(namespace_path)), + ) + ) + ) + + def list_storage_integrations( + self, + *, + namespace_path: Optional[List[str]] = None, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + ) -> AsyncListing[str]: + """Lazily list one namespace of this database's storage integrations.""" + return AsyncListing( + self._inner.list_storage_integrations( + namespace_path=list(validate_namespace_path(namespace_path)), + page_token=page_token, + page_limit=page_limit, + ) + ) + + async def drop_storage_integration( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> None: + """Drop a storage integration with ownership permission.""" + await self._inner.drop_storage_integration( + validate_secret_name(name), list(validate_namespace_path(namespace_path)) + ) + async def create_secret( self, name: str, value: str, *, namespace_path: Optional[List[str]] = None ) -> None: @@ -3361,10 +3970,11 @@ class AsyncConnection(object): async def drop_view( self, name: str, *, namespace_path: Optional[List[str]] = None ) -> None: - """Drop a view and wait for its definition to be deleted. + """Drop a view and wait for catalog removal. The tables it reads are untouched. Use :meth:`drop_view_async` to get - the cleanup job instead of waiting on it. + its SQL query job. Completion confirms catalog removal; physical cleanup + continues in the background. """ await self._inner.drop_view(name, list(namespace_path or [])) @@ -3374,10 +3984,11 @@ class AsyncConnection(object): *, namespace_path: Optional[List[str]] = None, ) -> AsyncJob[None]: - """Start dropping a view and return the job deleting its definition. + """Drop a view and return its SQL query job. - The name is free before this returns. Await :meth:`AsyncJob.wait` before - assuming the definition dataset is gone. + The job has type ``query`` and its ID is the SQL query UUID. Await + :meth:`AsyncJob.wait` to confirm catalog removal. Physical cleanup + continues in the background. """ if namespace_path is None: namespace_path = [] @@ -3406,6 +4017,67 @@ class AsyncConnection(object): ) ) + async def create_property_graph( + self, + name: str, + nodes: Sequence[NodeTable], + edges: Sequence[EdgeTable] = (), + *, + namespace_path: Optional[List[str]] = None, + ) -> AsyncPropertyGraph: + """Create a property graph over tables in its namespace. + + See + [DBConnection.create_property_graph][lancedb.DBConnection.create_property_graph]. + """ + definition = _definition_json(nodes, edges) + graph = AsyncPropertyGraph(self._inner, name, namespace_path) + await self._inner.create_property_graph(name, definition, graph.namespace_path) + return graph + + async def open_property_graph( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> AsyncPropertyGraph: + """Open the property graph named ``name``, describing it to check that + it exists. + + See + [DBConnection.open_property_graph][lancedb.DBConnection.open_property_graph]. + """ + graph = AsyncPropertyGraph(self._inner, name, namespace_path) + await graph.describe() + return graph + + async def drop_property_graph( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> None: + """Drop a property graph and wait for its definition to be deleted. + + The tables it reads are untouched. + """ + await self._inner.drop_property_graph(name, list(namespace_path or [])) + + def list_property_graphs( + self, + *, + namespace_path: Optional[List[str]] = None, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + ) -> AsyncListing[str]: + """The names of the property graphs in one namespace. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total; + ``page_token`` resumes from a saved token. Requests and errors occur during + iteration. See [pagination state][lancedb.listing.AsyncListing]. + """ + return AsyncListing( + self._inner.list_property_graphs( + namespace_path=namespace_path, + page_token=page_token, + page_limit=page_limit, + ) + ) + def list_jobs( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None ) -> AsyncListing[JobInfo]: diff --git a/python/python/lancedb/embeddings/__init__.py b/python/python/lancedb/embeddings/__init__.py index 20e8c331b..679407610 100644 --- a/python/python/lancedb/embeddings/__init__.py +++ b/python/python/lancedb/embeddings/__init__.py @@ -13,6 +13,7 @@ from .bedrock import BedRockText from .cohere import CohereEmbeddingFunction from .gemini_text import GeminiText from .instructor import InstructorEmbeddingFunction +from .oci_genai import OCIGenAIEmbeddings from .ollama import OllamaEmbeddings from .open_clip import OpenClipEmbeddings from .openai import OpenAIEmbeddings @@ -49,6 +50,7 @@ __all__ = [ "GteEmbeddings", "InstructorEmbeddingFunction", "JinaEmbeddings", + "OCIGenAIEmbeddings", "OllamaEmbeddings", "TransformersEmbeddingFunction", "ColbertEmbeddings", diff --git a/python/python/lancedb/embeddings/oci_genai.py b/python/python/lancedb/embeddings/oci_genai.py new file mode 100644 index 000000000..382c3500d --- /dev/null +++ b/python/python/lancedb/embeddings/oci_genai.py @@ -0,0 +1,320 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + + +import os +from functools import cached_property +from typing import Any, List, Literal, Optional, Union + +import numpy as np +from pydantic import ConfigDict + +from ..util import attempt_import_or_raise +from .base import TextEmbeddingFunction +from .registry import register +from .utils import TEXT + +# The Generative AI embed-text API accepts at most 96 inputs per request: +# https://docs.oracle.com/en-us/iaas/api/#/en/generative-ai-inference/latest/EmbedTextResult/EmbedText +EMBEDDING_BATCH_SIZE = 96 + +# A ``name`` that is a dedicated AI cluster endpoint OCID is routed with +# DedicatedServingMode instead of the on-demand model catalog. +_DEDICATED_ENDPOINT_PREFIX = "ocid1.generativeaiendpoint" +_DEFAULT_REGION = "us-chicago-1" + +_SERVICE_ERROR_HELP = """ + Common causes: + - Expired session token (auth_type="SECURITY_TOKEN"): run + `oci session authenticate --profile-name `. + - Missing IAM policy: the caller needs + `allow group to use generative-ai-family in compartment `. + - Model not offered in the region behind `region` / `service_endpoint`, or + a wrong `name` / `compartment_id`. List models with + `oci generative-ai model-collection list-models --compartment-id `. +""" + + +class OCIGenAIServiceError(ValueError): + """Raised when the Generative AI service rejects an ``embed_text`` request. + + ``status_code`` mirrors the HTTP status so LanceDB's retry helper treats + 401/403 responses as permanent instead of retrying them. + """ + + def __init__(self, message: str, status_code: Optional[int] = None): + super().__init__(message) + self.status_code = status_code + + +@register("oci-genai") +class OCIGenAIEmbeddings(TextEmbeddingFunction): + """ + An embedding function that uses the Oracle Cloud Infrastructure (OCI) + Generative AI service. + + https://docs.oracle.com/en-us/iaas/Content/generative-ai/embed-models.htm + + Requires the OCI Python SDK (``pip install oci``). No credentials are stored + on this object: requests are signed by the SDK using an API-key or + session-token profile from the OCI config file, or the instance / resource + principal of the host, so there are no sensitive keys to protect with + ``$var:``. + + Cohere embedding models are asymmetric: the source column is embedded with + ``input_type="SEARCH_DOCUMENT"`` and queries with ``"SEARCH_QUERY"``. + Inputs are sent in batches of at most 96 texts, the service limit. + + Parameters + ---------- + name : str, default "cohere.embed-v4.0" + Model ID of an on-demand embedding model: ``cohere.embed-v4.0`` + (1536 dims), ``cohere.embed-english-v3.0`` / + ``cohere.embed-multilingual-v3.0`` (1024 dims) or their ``-light-v3.0`` + variants (384 dims). A dedicated AI cluster endpoint OCID + (``ocid1.generativeaiendpoint...``) is also accepted. + compartment_id : str, optional + OCID of the compartment the requests are authorized in and billed to. + The service requires it; when not passed, the ``OCI_COMPARTMENT_ID`` + environment variable is used. + region : str, default "us-chicago-1" + OCI region used to derive the inference endpoint when + ``service_endpoint`` is not set. + service_endpoint : str, optional + Full inference endpoint, e.g. + ``https://inference.generativeai.us-chicago-1.oci.oraclecloud.com``. + Takes precedence over ``region``; needed for realms with a different + endpoint template. + auth_type : str, default "API_KEY" + One of ``"API_KEY"``, ``"SECURITY_TOKEN"``, ``"INSTANCE_PRINCIPAL"`` or + ``"RESOURCE_PRINCIPAL"``. The first two read profile ``auth_profile`` + from the OCI config file ``auth_file_location``; ``SECURITY_TOKEN`` + additionally uses the profile's ``security_token_file`` written by + ``oci session authenticate``. The principal types use the identity of + the host (Compute instance, OKE workload, Functions, ...) and ignore + the config file. + auth_profile : str, default "DEFAULT" + Profile name in the OCI config file. + auth_file_location : str, default "~/.oci/config" + Path of the OCI config file. + truncate : str, default "END" + How inputs longer than the model context are handled: ``"NONE"`` + (fail), ``"START"`` or ``"END"`` (drop tokens from that side). + source_input_type : str, default "SEARCH_DOCUMENT" + ``input_type`` sent when embedding the source column. + query_input_type : str, default "SEARCH_QUERY" + ``input_type`` sent when embedding queries. + output_dimensions : int, optional + Embedding size for models that support it (``cohere.embed-v4.0``: + 256, 512, 1024 or 1536). When set, ``ndims()`` returns it directly; + otherwise the size is discovered with one probe request and cached. + + Examples + -------- + import lancedb + from lancedb.embeddings import get_registry + from lancedb.pydantic import LanceModel, Vector + + model = get_registry().get("oci-genai").create( + name="cohere.embed-v4.0", + compartment_id="ocid1.compartment.oc1..", + auth_profile="DEFAULT", + ) + + class TextModel(LanceModel): + text: str = model.SourceField() + vector: Vector(model.ndims()) = model.VectorField() + + db = lancedb.connect("~/.lancedb") + tbl = db.create_table("docs", schema=TextModel, mode="overwrite") + tbl.add([{"text": "hello world"}, {"text": "goodbye world"}]) + rs = tbl.search("hello").limit(1).to_pandas() + + When restored from table metadata in a new process, an explicit + ``service_endpoint`` or non-default ``region`` must be approved with + [allow_endpoint][lancedb.embeddings.EmbeddingFunctionRegistry.allow_endpoint]. + The default region does not need approval. + """ + + name: str = "cohere.embed-v4.0" + compartment_id: Optional[str] = None + region: str = _DEFAULT_REGION + service_endpoint: Optional[str] = None + auth_type: Literal[ + "API_KEY", "SECURITY_TOKEN", "INSTANCE_PRINCIPAL", "RESOURCE_PRINCIPAL" + ] = "API_KEY" + auth_profile: str = "DEFAULT" + auth_file_location: str = "~/.oci/config" + truncate: Literal["NONE", "START", "END"] = "END" + source_input_type: str = "SEARCH_DOCUMENT" + query_input_type: str = "SEARCH_QUERY" + output_dimensions: Optional[int] = None + + model_config = ConfigDict(ignored_types=(cached_property,)) + + @staticmethod + def model_names() -> List[str]: + """On-demand text embedding models offered by the service.""" + return [ + "cohere.embed-v4.0", + "cohere.embed-english-v3.0", + "cohere.embed-multilingual-v3.0", + "cohere.embed-english-light-v3.0", + "cohere.embed-multilingual-light-v3.0", + ] + + def endpoints(self) -> List[str]: + # Metadata only selects the default endpoint by omitting both fields. + if self.service_endpoint or self.region != _DEFAULT_REGION: + return [self._resolve_service_endpoint()] + return [] + + def ndims(self) -> int: + return self._resolved_ndims + + @cached_property + def _resolved_ndims(self) -> int: + if self.output_dimensions is not None: + return self.output_dimensions + # embed-v4.0 is variable-width and the catalog changes, so probe the + # service once instead of hardcoding a model -> dimensions table. + return len(self._embed_batch(["lancedb"], self.query_input_type)[0]) + + def compute_query_embeddings( + self, query: str, *args, **kwargs + ) -> List[Union[List[float], None]]: + return self.compute_source_embeddings(query, input_type=self.query_input_type) + + def compute_source_embeddings( + self, texts: TEXT, *args, **kwargs + ) -> List[Union[List[float], None]]: + texts = self.sanitize_input(texts) + # assume the source input type unless `compute_query_embeddings` set one + kwargs["input_type"] = kwargs.get("input_type") or self.source_input_type + return self.generate_embeddings(texts, **kwargs) + + def generate_embeddings( + self, texts: Union[List[str], np.ndarray], *args, **kwargs + ) -> List[Union[List[float], None]]: + """ + Get the embeddings for the given texts + + Parameters + ---------- + texts: list[str] or np.ndarray (of str) + The texts to embed + + Returns + ------- + list[list[float] | None] + One embedding per input, in order. Empty inputs are not sent to + the service (it rejects them) and come back as ``None``. + """ + input_type = kwargs.get("input_type") or self.source_input_type + texts = list(texts) + valid = [(idx, text) for idx, text in enumerate(texts) if text] + results: List[Union[List[float], None]] = [None] * len(texts) + for start in range(0, len(valid), EMBEDDING_BATCH_SIZE): + batch = valid[start : start + EMBEDDING_BATCH_SIZE] + embeddings = self._embed_batch([text for _, text in batch], input_type) + for (idx, _), embedding in zip(batch, embeddings): + results[idx] = embedding + return results + + def _embed_batch(self, texts: List[str], input_type: str) -> List[List[float]]: + """Send one embed_text request (at most EMBEDDING_BATCH_SIZE inputs).""" + oci = attempt_import_or_raise("oci") + models = oci.generative_ai_inference.models + if self.name.startswith(_DEDICATED_ENDPOINT_PREFIX): + serving_mode = models.DedicatedServingMode(endpoint_id=self.name) + else: + serving_mode = models.OnDemandServingMode(model_id=self.name) + details = { + "inputs": texts, + "serving_mode": serving_mode, + "compartment_id": self._resolve_compartment_id(), + "truncate": self.truncate, + "input_type": input_type, + } + if self.output_dimensions is not None: + details["output_dimensions"] = self.output_dimensions + try: + response = self._client.embed_text(models.EmbedTextDetails(**details)) + except oci.exceptions.ServiceError as e: + raise OCIGenAIServiceError( + f"OCI Generative AI embed_text failed with HTTP {e.status} " + f"({e.code}): {e.message}\n{_SERVICE_ERROR_HELP}", + status_code=e.status, + ) from e + return response.data.embeddings + + def _resolve_compartment_id(self) -> str: + compartment_id = self.compartment_id or os.environ.get("OCI_COMPARTMENT_ID") + if not compartment_id: + raise ValueError( + "compartment_id is required by the OCI Generative AI service. " + "Pass `compartment_id=` to OCIGenAIEmbeddings or set the " + "OCI_COMPARTMENT_ID environment variable." + ) + return compartment_id + + def _resolve_service_endpoint(self) -> str: + if self.service_endpoint: + return self.service_endpoint + return f"https://inference.generativeai.{self.region}.oci.oraclecloud.com" + + def _build_auth(self, oci) -> tuple[dict, Any]: + """Return the ``(config, signer)`` pair for the configured ``auth_type``.""" + if self.auth_type in ("API_KEY", "SECURITY_TOKEN"): + config = oci.config.from_file( + file_location=self.auth_file_location, profile_name=self.auth_profile + ) + token_file = config.get("security_token_file") + if self.auth_type == "API_KEY": + if token_file: + raise ValueError( + f"Profile '{self.auth_profile}' in {self.auth_file_location} " + "is a session-token profile; use auth_type='SECURITY_TOKEN'." + ) + return config, None + if not token_file: + raise ValueError( + f"Profile '{self.auth_profile}' in {self.auth_file_location} " + "has no security_token_file; run `oci session authenticate` " + "or use auth_type='API_KEY'." + ) + with open(os.path.expanduser(token_file)) as f: + token = f.read().strip() + private_key = oci.signer.load_private_key_from_file( + os.path.expanduser(config["key_file"]), config.get("pass_phrase") + ) + return config, oci.auth.signers.SecurityTokenSigner(token, private_key) + if self.auth_type == "INSTANCE_PRINCIPAL": + return {}, oci.auth.signers.InstancePrincipalsSecurityTokenSigner() + if self.auth_type == "RESOURCE_PRINCIPAL": + return {}, oci.auth.signers.get_resource_principals_signer() + raise ValueError(f"Unsupported auth_type '{self.auth_type}'") + + @cached_property + def _client(self): + oci = attempt_import_or_raise("oci") + config, signer = self._build_auth(oci) + kwargs = { + "config": config, + "service_endpoint": self._resolve_service_endpoint(), + # LanceDB already retries with exponential backoff (`max_retries`), + # so the SDK's own retry loop is disabled to avoid compounding it. + "retry_strategy": oci.retry.NoneRetryStrategy(), + "timeout": (10, 240), + } + if signer is not None: + kwargs["signer"] = signer + return oci.generative_ai_inference.GenerativeAiInferenceClient(**kwargs) + + def __getstate__(self) -> dict[str, Any]: + # The SDK client holds an HTTP session and cannot be pickled. + state = super().__getstate__() + state["__dict__"] = { + k: v for k, v in state["__dict__"].items() if k != "_client" + } + return state diff --git a/python/python/lancedb/embeddings/openai.py b/python/python/lancedb/embeddings/openai.py index d4ecbdf3f..8592598cc 100644 --- a/python/python/lancedb/embeddings/openai.py +++ b/python/python/lancedb/embeddings/openai.py @@ -36,6 +36,7 @@ class OpenAIEmbeddings(TextEmbeddingFunction): embedding_function = openai.create( name="", base_url="http://localhost:11434", + dim=768, # the model's embedding dimension; required for unlisted names ) ``` @@ -77,8 +78,15 @@ class OpenAIEmbeddings(TextEmbeddingFunction): return self.dim or 3072 elif self.name == "text-embedding-3-small": return self.dim or 1536 + elif self.dim: + # A name not listed above, e.g. a model served behind an + # OpenAI-compatible `base_url`: `dim` is its embedding size + return self.dim else: - raise ValueError(f"Unknown model name {self.name}") + raise ValueError( + f"Unknown model name {self.name}: set `dim` to the model's " + "embedding dimension" + ) def generate_embeddings( self, texts: Union[List[str], "np.ndarray"] diff --git a/python/python/lancedb/embeddings/registry.py b/python/python/lancedb/embeddings/registry.py index a7093094d..bebff3cec 100644 --- a/python/python/lancedb/embeddings/registry.py +++ b/python/python/lancedb/embeddings/registry.py @@ -2,7 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import json -from typing import Dict, Optional, Set, Tuple, Type +from typing import Dict, Mapping, Optional, Set, Tuple, Type, Union from pydantic import TypeAdapter @@ -13,6 +13,51 @@ from .base import ( ) +def _embedding_column_pairs( + metadata: Optional[Mapping[Union[bytes, str], Union[bytes, str]]], +) -> list[Tuple[str, str]]: + """Return source/vector pairs without restoring embedding functions.""" + pairs = [] + seen = set() + + def add_pair(source_column: str, vector_column: str) -> None: + pair = (source_column, vector_column) + if pair not in seen: + seen.add(pair) + pairs.append(pair) + + if metadata is None: + return pairs + + serialized = metadata.get( + b"embedding_functions", metadata.get("embedding_functions") + ) + if serialized is not None: + if isinstance(serialized, bytes): + serialized = serialized.decode("utf-8") + for config in json.loads(serialized): + add_pair(config["source_column"], config["vector_column"]) + + serialized = metadata.get( + b"lancedb::column_definitions", metadata.get("lancedb::column_definitions") + ) + if serialized is not None: + if isinstance(serialized, bytes): + serialized = serialized.decode("utf-8") + for column in json.loads(serialized): + kind = column.get("kind") + if not isinstance(kind, dict) or "Embedding" not in kind: + continue + embedding = kind["Embedding"] + source_column = embedding["source_column"] + vector_column = embedding.get("dest_column") + if vector_column is None: + vector_column = f"{source_column}_embedding" + add_pair(source_column, vector_column) + + return pairs + + class EmbeddingFunctionRegistry: """ This is a singleton class used to register embedding functions diff --git a/python/python/lancedb/exceptions.py b/python/python/lancedb/exceptions.py index 67f15cabe..e5f7c9a47 100644 --- a/python/python/lancedb/exceptions.py +++ b/python/python/lancedb/exceptions.py @@ -3,6 +3,8 @@ """Custom exception handling""" +from typing import Optional + class MissingValueError(ValueError): """Exception raised when a required value is missing.""" @@ -25,10 +27,59 @@ class MissingColumnError(KeyError): ) -class JobFailedError(RuntimeError): - """Exception raised when an asynchronous job reaches the failed state.""" +class ColumnNotFoundError(ValueError): + """A requested table column does not exist. - pass + Remote HTTP and SQL errors inherit this type and carry request metadata. + Locally rejected queries have no request or job identifiers. + """ + + def __init__(self, message: str): + super().__init__(message) + self.request_id: Optional[str] = None + self.job_id: Optional[str] = None + self.job_request_id: Optional[str] = None + + +class ReferenceNotFoundError(ValueError): + """A requested branch or table reference does not exist.""" + + request_id: Optional[str] = None + job_id: Optional[str] = None + job_request_id: Optional[str] = None + + +class SchemaMismatchError(ValueError): + """Input data does not match the table's schema.""" + + request_id: Optional[str] = None + job_id: Optional[str] = None + job_request_id: Optional[str] = None + + +class JobFailedError(RuntimeError): + """Exception raised when an asynchronous job reaches the failed state. + + ``job_id`` identifies the failed job when available. ``sql_job_id`` preserves + the SQL execution identity reported by the server, which may differ from + the outer job's identity. ``request_id`` and ``job_request_id`` identify the + current request and isolated worker request. A typed SQL cause is available + through ``__cause__`` when the server reports one. + """ + + def __init__( + self, + message: str, + job_id: Optional[str] = None, + sql_job_id: Optional[str] = None, + request_id: Optional[str] = None, + job_request_id: Optional[str] = None, + ): + super().__init__(message) + self.job_id = job_id + self.sql_job_id = sql_job_id + self.request_id = request_id + self.job_request_id = job_request_id class JobCancelledError(RuntimeError): diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 2125542af..fe5a1a45a 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -16,7 +16,7 @@ import builtins import base64 import functools import hashlib -import importlib +import importlib.util import inspect import symtable import json @@ -35,6 +35,7 @@ from typing import ( Callable, Literal, Optional, + TYPE_CHECKING, Union, get_args, get_origin, @@ -61,6 +62,11 @@ from .secrets import EnvVarSecret _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) _UInt32 = conint(strict=True, ge=0, 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" +) def _validate_gpu_wire_marker(value: Any) -> bool: @@ -75,6 +81,33 @@ def _normalize_gpu_marker(value: bool) -> Optional[bool]: 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 + + +def _validate_batch_size(value: Any) -> Optional[int]: + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError("batch_size must be an integer") + if not 1 <= value <= 2**32 - 1: + raise ValueError("batch_size must be between 1 and 4294967295") + return value + + +def _validate_row_timeout(value: Any) -> Optional[float]: + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError("row_timeout_seconds must be a number") + value = float(value) + if not math.isfinite(value) or value <= 0: + raise ValueError("row_timeout_seconds must be positive and finite") + return value + + class _FrozenDict(dict): def _immutable(self, *args, **kwargs): raise TypeError("remote canonical values are immutable") @@ -180,6 +213,45 @@ class _OpenRemoteValue(_RemoteValue): return set((self.__pydantic_extra__ or {}).keys()) +class FunctionRetryPolicy(_RemoteValue): + """Bound retries of selected errors inside one Enterprise Function call. + + ``max_attempts`` includes the first call. Matchers are alternatives; + ``transient=True`` selects connection/timeouts, HTTP 429/503 and the + provider codes ``SlowDown`` and ``ServiceUnavailable``. Exception names + may be qualified, and subclasses and wrapped causes also match. + + Backoff doubles with full jitter, bounded by ``max_backoff_seconds``. + Retry-After above that bound ends retries. A failed batch is retried as + one call: under ``skip``, exhaustion nulls every row in that call. + Completed calls are never repeated. Only opt in when repeating partial + work is safe; this does not make external side effects exactly once. + + >>> policy = FunctionRetryPolicy(transient=True, max_attempts=3) + >>> policy.max_attempts + 3 + >>> disabled = FunctionRetryPolicy(max_attempts=1) + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + max_attempts: Annotated[int, Field(strict=True)] = 3 + initial_backoff_seconds: Annotated[float, Field(strict=True)] = 0.2 + max_backoff_seconds: Annotated[float, Field(strict=True)] = 30.0 + exception_types: tuple[str, ...] = () + message_pattern: Optional[str] = None + error_codes: tuple[str, ...] = () + transient: Annotated[bool, Field(strict=True)] = False + honor_retry_after: Annotated[bool, Field(strict=True)] = True + + @model_validator(mode="after") + def _validate_policy(self): + from ._lancedb import validate_function_retry_policy + + validate_function_retry_policy(self.model_dump_json()) + return self + + class FunctionArtifact(_RemoteValue): """Content-addressed Python artifact identity.""" @@ -286,11 +358,71 @@ class PythonEnvironmentSpec(_RemoteValue): system_packages: tuple[str, ...] = () +_HUGGING_FACE_MODEL_REPO = re.compile( + r"^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$" +) +_HUGGING_FACE_REVISION = re.compile(r"^[0-9a-f]{40}$") + + +class HuggingFaceModel(_RemoteValue): + """One immutable Hugging Face model snapshot required by a Function. + + ``revision`` is a full 40-character lowercase commit SHA, not a branch or + tag. A Function may declare each repository once; separate versions of the + same repository use separate Function versions. The service prepares the + snapshot before initialization, so the model can load without a revision + argument or a Hugging Face Hub request:: + + @function( + pip=["sentence-transformers==3.3.1"], + models=[HuggingFaceModel( + repo="sentence-transformers/all-MiniLM-L6-v2", + revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41", + )], + ) + class Embed: + def __init__(self): + from sentence_transformers import SentenceTransformer + + self.model = SentenceTransformer( + "sentence-transformers/all-MiniLM-L6-v2", device="cpu" + ) + + def __call__(self, text: str) -> list[float]: + return self.model.encode(text).tolist() + """ + + repo: str = Field( + pattern=r"^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$" + ) + revision: str + + @field_validator("repo") + @classmethod + def _validate_repo(cls, value: str) -> str: + if not _HUGGING_FACE_MODEL_REPO.fullmatch(value) or any( + part in {".", ".."} for part in value.split("/") + ): + raise ValueError("model repo must be a Hugging Face owner/name") + return value + + @field_validator("revision", mode="before") + @classmethod + def _validate_revision(cls, value: Any) -> str: + if not isinstance(value, str) or not _HUGGING_FACE_REVISION.fullmatch(value): + raise ValueError( + "model revision must be a full 40-character lowercase commit SHA" + ) + return value + + class PythonRuntimeSpec(_RemoteValue): """Remote runtime definition with environment values. 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: str @@ -298,6 +430,7 @@ class PythonRuntimeSpec(_RemoteValue): environment: Optional[PythonEnvironmentSpec] = None env: Optional[Mapping[str, str]] = None gpu: Optional[bool] = None + gpu_class: Optional[str] = None @model_validator(mode="before") @classmethod @@ -315,6 +448,13 @@ class PythonRuntimeSpec(_RemoteValue): return None return _validate_gpu_wire_marker(value) + @field_validator("gpu_class", mode="before") + @classmethod + def _validate_gpu_class(cls, value): + if value is None: + return None + return _validate_gpu_class_name(value) + @model_validator(mode="after") def _validate_runtime_kind(self): if self.kind == "python": @@ -324,6 +464,10 @@ class PythonRuntimeSpec(_RemoteValue): raise ValueError("python runtime requires environment") if self.gpu is not None: raise ValueError("python runtime with gpu requires kind='python_v2'") + if self.gpu_class is not None: + raise ValueError( + "python runtime with gpu_class requires kind='python_v2'" + ) elif self.kind == "python_v2": if self.python_version is None: raise ValueError("python_v2 runtime requires python_version") @@ -336,6 +480,7 @@ class PythonRuntimeSpec(_RemoteValue): object.__setattr__(self, "environment", None) object.__setattr__(self, "env", None) object.__setattr__(self, "gpu", None) + object.__setattr__(self, "gpu_class", None) return self @@ -345,6 +490,7 @@ class FunctionImage(_RemoteValue): manifest_digest: str descriptor: Mapping[str, Any] source: bool + models: tuple[HuggingFaceModel, ...] = () def _validate_object_version(value: str) -> str: @@ -363,6 +509,12 @@ _ObjectVersion = Annotated[ class FunctionVersion(_RemoteValue): """A pinned object revision, independent of its executable image digest. + Unknown top-level fields from newer servers are accepted for forward + decoding, but they are not exposed on this value and are omitted from + ``to_canonical_json()``. Known fields retain their complete values, while + unknown fields inside the open ``image.descriptor`` mapping remain + available. + ``name`` and ``namespace_path`` are the Function's parts, as a [SecretReference][lancedb.functions.SecretReference] carries a Secret's; they are what [get_function][lancedb.db.DBConnection.get_function] takes. @@ -370,9 +522,16 @@ class FunctionVersion(_RemoteValue): ``source_digest`` identifies the registered source artifact, independently of the built ``image``. Compare it with - ``udf_def.registration_request.artifact.digest`` to check whether a local - [UdfDefinition][lancedb.functions.UdfDefinition] has the same source. + ``definition.registration_request.artifact.digest`` to check whether a local + [FunctionDefinition][lancedb.functions.FunctionDefinition] has the same source. It is ``None`` when the server does not provide a source digest. + + ``gpu_class`` is the operator-defined GPU pool fixed into this Function + version, or ``None`` when registration used the deployment default. + + ``batch_size``, ``row_timeout_seconds``, and ``result_stability`` retain + the execution controls reported by the catalog. They are ``None`` for + versions registered before the corresponding declaration. """ name: str @@ -387,6 +546,20 @@ class FunctionVersion(_RemoteValue): created_at_millis: int metadata: Mapping[str, str] disabled: bool + gpu_class: Optional[str] = None + batch_size: Optional[int] = None + row_timeout_seconds: Optional[float] = None + result_stability: Optional[str] = None + + @field_validator("batch_size", mode="before") + @classmethod + def _validate_batch_size(cls, value): + return _validate_batch_size(value) + + @field_validator("row_timeout_seconds", mode="before") + @classmethod + def _validate_row_timeout(cls, value): + return _validate_row_timeout(value) def __call__(self, **arguments: Any) -> FunctionApplication: """Bind this exact version to named table columns. @@ -506,7 +679,7 @@ def _initialization_value(name: str, value: Any) -> Any: class FunctionRegistrationRequest(_RemoteValue): - """Stable remote registration envelope produced by :func:`udf`. + """Stable remote registration envelope produced by :func:`function`. Credential values deliberately have no field here. The only secret-shaped thing a client sends is ``secret_bindings``: the name of a Secret the @@ -517,7 +690,21 @@ class FunctionRegistrationRequest(_RemoteValue): artifact: FunctionArtifactRequest signature: FunctionSignature runtime: PythonRuntimeSpec + batch_size: Optional[int] = None + row_timeout_seconds: Optional[float] = None + retry_policy: Optional[FunctionRetryPolicy] = None secret_bindings: tuple[SecretBinding, ...] = () + models: tuple[HuggingFaceModel, ...] = () + + @field_validator("batch_size", mode="before") + @classmethod + def _validate_batch_size(cls, value): + return _validate_batch_size(value) + + @field_validator("row_timeout_seconds", mode="before") + @classmethod + def _validate_row_timeout(cls, value): + return _validate_row_timeout(value) class FunctionVersionRef(_OpenRemoteValue): @@ -661,7 +848,7 @@ class FunctionBinding(_RemoteValue): class RefreshColumnResult(_RemoteValue): """Terminal result of an expression-backed or Function-backed refresh Job. - LanceDB Embedded jobs produce this value in process. LanceDB Distributed + LanceDB Embedded jobs produce this value in process. LanceDB Enterprise decodes the same value from the durable server-job terminal payload. """ @@ -683,6 +870,8 @@ class RefreshColumnResult(_RemoteValue): _FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +# Digest-pinned only; the server checks the host and repository grammar. +_IMAGE_REFERENCE = re.compile(r"^[^/@\s]+/[^@\s]+@sha256:[0-9a-f]{64}$") _FUNCTION_BLOB_V2_TYPE = "blob_v2" _ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name" @@ -715,12 +904,14 @@ _GRAMMAR_PRIMITIVES = ( ) -def _canonical_arrow_type(data_type: pa.DataType) -> str: +def _canonical_arrow_type( + data_type: pa.DataType, *, collection_blobs: bool = False +) -> str: """The compact Function grammar, or canonical exact JSON for nested types.""" grammar = _grammar_arrow_type(data_type) if grammar is not None: return grammar - exact = _exact_arrow_type(data_type) + exact = _exact_arrow_type(data_type, collection_blobs=collection_blobs) return json.dumps(exact, ensure_ascii=False, sort_keys=True, separators=(",", ":")) @@ -832,11 +1023,12 @@ def _has_supported_blob_v2_layout(field: pa.Field) -> bool: ) -def _canonical_arrow_field(field: pa.Field) -> str: +def _canonical_arrow_field(field: pa.Field, *, collection_blobs: bool = False) -> str: + """``collection_blobs`` admits Blob v2 under a list, which only outputs support.""" _validate_exact_arrow_field(field) if _is_blob_v2_field(field): return _FUNCTION_BLOB_V2_TYPE - return _canonical_arrow_type(field.type) + return _canonical_arrow_type(field.type, collection_blobs=collection_blobs) def _blob_storage_type(field: pa.Field) -> pa.DataType: @@ -888,11 +1080,14 @@ def _data_type_has_blob_v2(data_type: pa.DataType) -> bool: def _exact_arrow_field( - field: pa.Field, *, inside_collection: bool = False + field: pa.Field, + *, + inside_collection: bool = False, + collection_blobs: bool = False, ) -> dict[str, Any]: _validate_exact_arrow_field(field) if _is_blob_v2_field(field): - if inside_collection: + if inside_collection and not collection_blobs: raise TypeError(_NESTED_BLOB_COLLECTION_ERROR) return { "name": field.name, @@ -905,13 +1100,20 @@ def _exact_arrow_field( value = { "name": field.name, "nullable": field.nullable, - "type": _exact_arrow_type(field.type, inside_collection=inside_collection), + "type": _exact_arrow_type( + field.type, + inside_collection=inside_collection, + collection_blobs=collection_blobs, + ), } return value def _exact_arrow_type( - data_type: pa.DataType, *, inside_collection: bool = False + data_type: pa.DataType, + *, + inside_collection: bool = False, + collection_blobs: bool = False, ) -> dict[str, Any]: for candidate, name in _GRAMMAR_PRIMITIVES: if data_type == candidate: @@ -927,7 +1129,11 @@ def _exact_arrow_type( return { "type": "struct", "fields": [ - _exact_arrow_field(field, inside_collection=inside_collection) + _exact_arrow_field( + field, + inside_collection=inside_collection, + collection_blobs=collection_blobs, + ) for field in fields ], } @@ -955,7 +1161,13 @@ def _exact_arrow_type( else "fixed_size_list" ), "fields": [ - _exact_arrow_field(data_type.value_field, inside_collection=True) + _exact_arrow_field( + data_type.value_field, + inside_collection=True, + # Lance stores Blob v2 under list and large_list only. + collection_blobs=collection_blobs + and not pa.types.is_fixed_size_list(data_type), + ) ], } if pa.types.is_fixed_size_list(data_type): @@ -1076,7 +1288,7 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp raise ValueError("Function output must be non-nullable") return FunctionOutput( kind="scalar", - arrow_type=_canonical_arrow_field(field), + arrow_type=_canonical_arrow_field(field, collection_blobs=True), nullable=False, ) @@ -1092,7 +1304,7 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp fields=tuple( FunctionResultField( name=field.name, - arrow_type=_canonical_arrow_field(field), + arrow_type=_canonical_arrow_field(field, collection_blobs=True), nullable=field.nullable, ) for field in fields @@ -1204,11 +1416,15 @@ def _infer_signature( return FunctionSignature(inputs=tuple(inputs), output=output) -def _is_udf_decorator(node: ast.expr) -> bool: +# Both spellings strip from packaged source; `udf` is the deprecated alias. +_DECORATOR_NAMES = frozenset({"function", "udf"}) + + +def _is_function_decorator(node: ast.expr) -> bool: if isinstance(node, ast.Call): node = node.func - return (isinstance(node, ast.Name) and node.id == "udf") or ( - isinstance(node, ast.Attribute) and node.attr == "udf" + return (isinstance(node, ast.Name) and node.id in _DECORATOR_NAMES) or ( + isinstance(node, ast.Attribute) and node.attr in _DECORATOR_NAMES ) @@ -1273,7 +1489,7 @@ def _module_references(module_source: str) -> set[str]: visit(child, found) found: set[str] = set() - module = symtable.symtable(module_source, "", "exec") + module = symtable.symtable(module_source, "", "exec") for symbol in module.get_symbols(): if ( symbol.is_referenced() @@ -1346,7 +1562,7 @@ def _definition_node( ) except (OSError, TypeError) as error: raise ValueError( - f"@udf requires inspectable Python source for {target.__qualname__!r}" + f"@function requires inspectable Python source for {target.__qualname__!r}" ) from error module = ast.parse(source) is_class = inspect.isclass(target) @@ -1361,15 +1577,16 @@ def _definition_node( ] if len(definitions) != 1 or isinstance(definitions[0], ast.AsyncFunctionDef): raise ValueError( - "@udf source must contain exactly one " + "@function source must contain exactly one " + ("class" if is_class else "synchronous function") ) definition = definitions[0] if entry: if any( - not _is_udf_decorator(decorator) for decorator in definition.decorator_list + not _is_function_decorator(decorator) + for decorator in definition.decorator_list ): - raise ValueError("@udf cannot package additional Python decorators") + raise ValueError("@function cannot package additional Python decorators") definition.decorator_list = [] return definition @@ -1380,7 +1597,7 @@ def _definition_namespace(target: Any) -> Mapping[str, Any]: module = sys.modules.get(target.__module__) if module is None: raise ValueError( - f"@udf cannot resolve the module of {target.__qualname__!r}" + f"@function cannot resolve the module of {target.__qualname__!r}" ) namespace = vars(module) environment = namespace.get("__builtins__", builtins) @@ -1395,7 +1612,7 @@ def _definition_namespace(target: Any) -> Mapping[str, Any]: # The artifact runs under the standard builtins; only the exact mapping is # provably equivalent (a subclass or copy can change lookups and hooks). if environment is not vars(builtins): - raise ValueError("@udf cannot package a non-standard builtins environment") + raise ValueError("@function cannot package a non-standard builtins environment") return namespace @@ -1409,7 +1626,7 @@ def _is_self_reference(target: Any, namespace: Mapping[str, Any], name: str) -> return True # The decorator's own result is the one wrapper known to behave like # `target`; any other binding may differ from the packaged definition. - return type(bound) is UdfDefinition and bound._function is target + return type(bound) is FunctionDefinition and bound._function is target def _packaged_by_source(value: Any) -> bool: @@ -1422,7 +1639,7 @@ def _packaged_by_source(value: Any) -> bool: qualname = value.__qualname__ if "<" in qualname or "." in qualname: raise ValueError( - f"@udf cannot package {qualname!r}: only module-level functions and " + f"@function cannot package {qualname!r}: only module-level functions and " "classes travel with a Function, not lambdas, closures, or nested " "definitions" ) @@ -1462,6 +1679,28 @@ def _module_locations(module: types.ModuleType) -> tuple[str, ...]: return tuple(os.path.realpath(path) for path in getattr(module, "__path__", ())) +def _module_locations_for_name(module_name: str) -> tuple[str, ...]: + """Where a top-level module would be imported from, without importing it + when it is not already loaded.""" + import os + + top = module_name.partition(".")[0] + module = sys.modules.get(top) + if module is not None: + return _module_locations(module) + try: + spec = importlib.util.find_spec(top) + except (AttributeError, ImportError, ValueError): + return () + if spec is None: + return () + if spec.submodule_search_locations: + return tuple(os.path.realpath(path) for path in spec.submodule_search_locations) + if spec.origin and spec.origin not in {"built-in", "frozen"}: + return (os.path.realpath(spec.origin),) + return () + + class _SourcePackager: """Builds the entry module of a Function artifact. @@ -1478,6 +1717,7 @@ class _SourcePackager: self._definitions: list[str] = [] self._packaged: set[int] = set() self._names: dict[str, Any] = {} + self._warned_imports: set[str] = set() def package(self, target: Any, signature: FunctionSignature) -> str: entry = self._definition(target, entry=True, signature=signature) @@ -1495,7 +1735,7 @@ class _SourcePackager: definition = _definition_node(target, entry=entry) if not inspect.isclass(target) and inspect.getclosurevars(target).nonlocals: raise ValueError( - "@udf cannot package functions that capture closure values" + "@function cannot package functions that capture closure values" ) namespace = _definition_namespace(target) reader_name = ( @@ -1508,8 +1748,9 @@ class _SourcePackager: dynamic = _namespace_acquisition(definition, references) if dynamic: raise ValueError( - f"@udf cannot package dynamic namespace access: {dynamic!r}" + f"@function cannot package dynamic namespace access: {dynamic!r}" ) + self._warn_unshipped_direct_imports(definition) self._packaged.add(id(target)) self._claim(target.__name__, ("definition", id(target))) if reader_name is not None: @@ -1519,9 +1760,9 @@ class _SourcePackager: if name == target.__name__: if not _is_self_reference(target, namespace, name): raise ValueError( - f"@udf cannot package {name!r}: the module binds that name " - "to another value, which the artifact's own definition " - "would shadow" + f"@function cannot package {name!r}: the module binds that " + "name to another value, which the artifact's own " + "definition would shadow" ) continue if name in namespace: @@ -1530,7 +1771,7 @@ class _SourcePackager: unresolved.append(name) if unresolved: raise ValueError( - f"@udf source contains unresolved global names: {unresolved!r}" + f"@function source contains unresolved global names: {unresolved!r}" ) return source @@ -1576,7 +1817,7 @@ class _SourcePackager: claimed = self._names.setdefault(name, meaning) if claimed != meaning: raise ValueError( - f"@udf cannot package {name!r}: packaged definitions bind that " + f"@function cannot package {name!r}: packaged definitions bind that " "name to different values" ) @@ -1584,8 +1825,8 @@ class _SourcePackager: if _packaged_by_source(value): if value.__name__ != name: raise ValueError( - f"@udf packages {value.__qualname__!r} by source, so it must be " - f"referenced by its own name, not {name!r}" + f"@function packages {value.__qualname__!r} by source, so it " + f"must be referenced by its own name, not {name!r}" ) if id(value) not in self._packaged: self._definitions.append(self._definition(value, entry=False)) @@ -1604,7 +1845,8 @@ class _SourcePackager: if isinstance(value, types.ModuleType): if value.__name__.split(".")[0] in _NAMESPACE_MODULES: raise ValueError( - f"@udf cannot package dynamic namespace access: {value.__name__!r}" + "@function cannot package dynamic namespace access: " + f"{value.__name__!r}" ) try: imported = importlib.import_module(value.__name__) @@ -1636,9 +1878,12 @@ class _SourcePackager: return f"{name} = {_literal_source(value)}" def _require_importable(self, module_name: str) -> None: - """Warn about an import the Function's environment likely cannot - satisfy: a module that lives in a local source tree, is not shipped - with ``code=``, and names no declared package. + """Warn about an import the Function's environment may not be able to + satisfy. + + An unresolved module warns only when the Function declares no package + dependencies. A local source module warns unless ``code=`` ships it or + a declared requirement matches its top-level name. A warning rather than an error: a distribution name need not match the module it installs, so a declared package can still provide the @@ -1650,25 +1895,58 @@ class _SourcePackager: or top in sys.stdlib_module_names or top in sys.builtin_module_names or _normalized_distribution(top) in self._requirements + or top in self._warned_imports ): return - module = sys.modules.get(top) - locations = () if module is None else _module_locations(module) - roots = _installed_roots() - if not locations or any(location.startswith(roots) for location in locations): + locations = _module_locations_for_name(top) + if not locations: + if not self._requirements: + self._warned_imports.add(top) + warnings.warn( + f"@function source imports {top!r}, which is unavailable in the " + "client environment and has no declared pip/conda dependencies. " + "Remote availability cannot be verified; declare the required " + "package or confirm that the base image provides it.", + UserWarning, + ) return + roots = _installed_roots() + if any(location.startswith(roots) for location in locations): + return + self._warned_imports.add(top) warnings.warn( - f"@udf source imports {module_name!r} from {locations[0]}, a local " + f"@function source imports {module_name!r} from {locations[0]}, a local " "module the Function's environment may not be able to import; ship " f"it with code=[{top}] or declare the package that provides it in " "pip/conda", UserWarning, ) + def _warn_unshipped_direct_imports( + self, definition: Union[ast.FunctionDef, ast.ClassDef] + ) -> None: + """Warn for body imports that resolve to local, undeclared source. + + Imports from site-packages are deliberately not guessed about: the + declared distribution name need not match the imported module, and the + client cannot inspect the remote base image. + """ + for node in ast.walk(definition): + if isinstance(node, ast.Import): + for alias in node.names: + self._require_importable(alias.name) + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + self._require_importable(node.module) + def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]: """The Python source files of the modules and packages in ``code=``, - keyed by their path on the Function's import path.""" + keyed by their path on the Function's import path. + + Package resources are not part of the source artifact. Warn about files + and excluded directories that the walk leaves behind instead of silently + producing a Function that will fail later on the worker. + """ import os from pathlib import Path @@ -1704,19 +1982,39 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]] ) root = Path(paths[0]) sources = [] + skipped = set() for directory, subdirectories, filenames in os.walk(root): # Only importable modules travel: data files, caches, and # directories that are not identifiers cannot be imported. - subdirectories[:] = sorted( - child - for child in subdirectories - if _SOURCE_PATH_COMPONENT.fullmatch(child) - and child != "__pycache__" - ) - for filename in filenames: + kept = [] + for child in sorted(subdirectories): + if child == "__pycache__": + continue + if _SOURCE_PATH_COMPONENT.fullmatch(child): + kept.append(child) + else: + relative = (Path(directory) / child).relative_to(root) + skipped.add(f"{name}/{relative.as_posix()}/") + subdirectories[:] = kept + for filename in sorted(filenames): stem, suffix = os.path.splitext(filename) + if suffix in {".pyc", ".pyo"}: + continue if suffix == ".py" and _SOURCE_PATH_COMPONENT.fullmatch(stem): sources.append(Path(directory) / filename) + else: + relative = (Path(directory) / filename).relative_to(root) + skipped.add(f"{name}/{relative.as_posix()}") + if skipped: + skipped_paths = ", ".join(sorted(skipped)) + warnings.warn( + f"code= ships Python .py modules only; package {name!r} " + f"will not include: {skipped_paths}. Install a package that " + "includes the required resources with pip= or conda=, and " + f"remove {name!r} from code= so the copied package cannot " + "shadow the installed distribution.", + UserWarning, + ) for path in sources: relative = path.relative_to(root).as_posix() files[f"{name}/{relative}"] = _source_text(path) @@ -1833,13 +2131,23 @@ def _class_call(cls: type) -> Callable[..., Any]: return call -class UdfDefinition: +class FunctionDefinition: """A Python callable prepared for remote Function registration. - Instances are created with :func:`udf`. Calling an instance executes the - original Python function, or constructs the original class, which keeps - local unit testing ordinary. Remote execution adapts the callable to the - internal Arrow batch ABI described by the registration artifact. + Instances are created with :func:`function`. Calling an instance is ordinary + local Python: a decorated function is called directly, while a decorated + class is constructed using its initialization fields and the returned + instance is called with each input. Reuse the instance and call its + ``close`` method when it defines one. This public call does not create a + remote application or build the declared remote runtime, and it does not + need the private implementation attribute. + + Remote execution adapts the callable to the internal Arrow batch ABI + described by the registration artifact. By default it invokes the callable + once per row. A callable whose parameters are all annotated as + ``pyarrow.Array`` receives whole Arrow arrays and returns a + ``pyarrow.Array`` instead. This authoring choice is independent of the + internal artifact adapter in the registration request. """ def __init__( @@ -1852,17 +2160,25 @@ class UdfDefinition: pip: tuple[str, ...], env: Mapping[str, str], python_version: Optional[str], + batch_size: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, gpu: bool = False, + gpu_class: Optional[str] = None, conda: tuple[str, ...] = (), conda_channels: tuple[str, ...] = (), apt: tuple[str, ...] = (), + image: Optional[str] = None, code: tuple[types.ModuleType, ...] = (), + models: tuple[HuggingFaceModel, ...] = (), ): is_class = inspect.isclass(function) if not is_class and ( not inspect.isfunction(function) or inspect.iscoroutinefunction(function) ): - raise TypeError("@udf requires a synchronous Python function or a class") + raise TypeError( + "@function requires a synchronous Python function or a class" + ) function_name = name or function.__name__ if not _FUNCTION_NAME.fullmatch(function_name): raise ValueError(f"invalid Function name: {function_name!r}") @@ -1870,6 +2186,11 @@ class UdfDefinition: raise ValueError("a Function environment is pip or conda, not both") if conda_channels and not conda: raise ValueError("conda_channels requires conda packages") + gpu_marker = _normalize_gpu_marker(gpu) + if gpu_class is not None: + _validate_gpu_class_name(gpu_class) + if gpu_marker is None: + raise ValueError("gpu_class requires gpu=True") packages = tuple(sorted(set(conda if conda else pip))) system_packages = tuple(sorted(set(apt))) if any( @@ -1877,16 +2198,33 @@ class UdfDefinition: for package in packages + system_packages ): raise ValueError("package requirements must be non-empty and trimmed") + if image is not None and not _IMAGE_REFERENCE.fullmatch(image): + raise ValueError( + f"Function image {image!r} must be host/repository@sha256:" + ) + if any(not isinstance(model, HuggingFaceModel) for model in models): + raise TypeError("models must contain HuggingFaceModel values") + repos = [model.repo for model in models] + duplicates = sorted({repo for repo in repos if repos.count(repo) > 1}) + if duplicates: + raise ValueError( + "a Function declares each Hugging Face repository once; " + f"duplicated: {duplicates!r}" + ) if conda: environment_spec = PythonEnvironmentSpec( kind="conda", packages=packages, channels=tuple(conda_channels), + image=image, system_packages=system_packages, ) else: environment_spec = PythonEnvironmentSpec( - kind="pip", packages=packages, system_packages=system_packages + kind="pip", + packages=packages, + image=image, + system_packages=system_packages, ) environment = dict(env) if any( @@ -1894,10 +2232,20 @@ class UdfDefinition: for key, value in environment.items() ): raise TypeError("Function env keys and values must be strings") + reserved = sorted( + set(environment).intersection( + {"HF_HOME", "HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"} + ) + ) + if models and reserved: + raise ValueError( + "model Functions reserve environment variables " + f"{reserved!r}; the worker sets them for the private snapshot" + ) if is_class: if "<" in function.__qualname__ or "." in function.__qualname__: raise ValueError( - "@udf classes must be defined at module level; nested classes " + "@function classes must be defined at module level; nested classes " "would capture their enclosing scope" ) signature = _infer_signature( @@ -1932,7 +2280,6 @@ class UdfDefinition: kind = _PYTHON_CALLABLE_ARTIFACT source = entry_source.encode("utf-8") digest = f"sha256:{hashlib.sha256(source).hexdigest()}" - gpu_marker = _normalize_gpu_marker(gpu) runtime = PythonRuntimeSpec( kind="python_v2" if gpu_marker is not None else "python", python_version=python_version @@ -1940,6 +2287,7 @@ class UdfDefinition: environment=environment_spec, env=environment, gpu=gpu_marker, + gpu_class=gpu_class, ) self._function = function self._request = FunctionRegistrationRequest( @@ -1959,6 +2307,10 @@ class UdfDefinition: ), signature=signature, runtime=runtime, + batch_size=batch_size, + row_timeout_seconds=row_timeout_seconds, + retry_policy=retry_policy, + models=models, ) # A class's own __dict__ holds its methods; copying it would shadow # this wrapper's attributes. @@ -2040,12 +2392,12 @@ class UdfDefinition: @overload -def udf(function: Callable[..., Any]) -> UdfDefinition: ... +def function(target: Callable[..., Any]) -> FunctionDefinition: ... @overload -def udf( - function: None = None, +def function( + target: None = None, *, name: Optional[str] = None, input_schema: Optional[pa.Schema] = None, @@ -2053,16 +2405,22 @@ def udf( pip: tuple[str, ...] | list[str] = (), env: Optional[Mapping[str, str]] = None, python_version: Optional[str] = None, + batch_size: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, gpu: bool = False, + gpu_class: Optional[str] = None, conda: tuple[str, ...] | list[str] = (), conda_channels: tuple[str, ...] | list[str] = (), apt: tuple[str, ...] | list[str] = (), + image: Optional[str] = None, code: Sequence[types.ModuleType] = (), -) -> Callable[[Callable[..., Any]], UdfDefinition]: ... + models: Sequence[HuggingFaceModel] = (), +) -> Callable[[Callable[..., Any]], FunctionDefinition]: ... -def udf( - function: Optional[Callable[..., Any]] = None, +def function( + target: Optional[Callable[..., Any]] = None, *, name: Optional[str] = None, input_schema: Optional[pa.Schema] = None, @@ -2070,11 +2428,17 @@ def udf( pip: tuple[str, ...] | list[str] = (), env: Optional[Mapping[str, str]] = None, python_version: Optional[str] = None, + batch_size: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, gpu: bool = False, + gpu_class: Optional[str] = None, conda: tuple[str, ...] | list[str] = (), conda_channels: tuple[str, ...] | list[str] = (), apt: tuple[str, ...] | list[str] = (), + image: Optional[str] = None, code: Sequence[types.ModuleType] = (), + models: Sequence[HuggingFaceModel] = (), ): """Prepare a Python function or class for remote Function registration. @@ -2130,9 +2494,17 @@ def udf( imported normally, so helpers shared by several Functions live in one place. - A reference to a module in a local source tree that is neither shipped - with ``code`` nor named by a declared package draws a warning at - registration, because the worker will most likely fail to import it. + A module imported by the packaged source -- including a direct ``import`` + inside a function or method body -- draws a warning at registration when + the client cannot resolve its top-level module and declares no package + dependencies, or when it resolves to local source outside ``code`` and + no declared requirement matches the imported module name. The warning + does not assert that the remote environment lacks the module: + ``pip``/``conda`` distribution names need not match the modules they + install, and the client cannot inspect the contents of a base or custom + image. Warnings follow normal Python warning filters and may be promoted + to errors. Declare every third-party import in ``pip`` or ``conda`` even + when it happens to be installed on the registration host. Closures, lambdas, nested definitions, mutable module-level objects, code that reaches the module namespace another way (``globals()``/``eval``, ``sys.modules``, ``builtins``), and a @@ -2144,7 +2516,10 @@ def udf( Parameters ---------- function : function or class, optional - The synchronous callable, or the class whose instances are called. + The synchronous callable, or the class whose instances are called. For + a function, annotate every parameter as ``pyarrow.Array`` to opt into + vectorized execution; a matching return annotation documents that the + callable returns an Arrow array. name : str, optional The remote Function name. Defaults to the callable name. Must start with an ASCII letter or underscore and contain only ASCII @@ -2169,6 +2544,10 @@ def udf( conda cannot provide, such as FFmpeg's for ``torchcodec``. Packages are unpacked without running their maintainer scripts. Works with ``pip`` or ``conda``; requires image execution. + image : str, optional + A digest-pinned registry image (``"host/repository@sha256:"``) + the remote environment is built on instead of the default base. Pip + requirements install only what the image lacks. env : mapping of str to str, optional Environment variables included in the Function definition. Not for credentials -- these are ordinary configuration, stored with the @@ -2176,17 +2555,49 @@ def udf( values that differ between bindings. python_version : str, optional Remote Python major/minor version. Defaults to the client version. + batch_size : int, optional + Maximum number of input rows supplied in one execution batch. Must be + between 1 and 4294967295. Remote execution may use smaller batches. + When omitted, the service chooses the batch size adaptively. + row_timeout_seconds : float, optional + Positive, finite deadline in seconds for each Python call: one row for + scalar Functions and one batch for vectorized Functions. This does not + govern class initialization. When omitted, the service applies its + default per-call budget. + 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_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. code : sequence of module, optional Top-level modules or packages whose importable ``.py`` files ship - with the Function and are importable by their own names. + with the Function and are importable by their own names. Package data + files are not copied. To use a package that includes required data + resources, install it with ``pip=`` or ``conda=`` and remove that + package from ``code=`` so the copied Python package cannot shadow the + installed distribution. ``@function`` warns when it skips files from a + package in ``code=``. + models : sequence of HuggingFaceModel, optional + Immutable Hugging Face repository snapshots prepared in the worker + node cache before user code starts. A Function may declare a + repository once. Different revisions of one repository use different + Function versions. Model Functions run offline with a private + ``HF_HOME``; bind ``HF_TOKEN`` through Secrets when the repository + requires authentication. Returns ------- - UdfDefinition + FunctionDefinition A callable definition accepted by :meth:`lancedb.db.DBConnection.create_function`, :meth:`lancedb.db.AsyncConnection.create_function_async` and @@ -2194,14 +2605,14 @@ def udf( Examples -------- - >>> from lancedb import udf - >>> @udf(pip=["numpy==2.2.0"]) + >>> from lancedb import function + >>> @function(pip=["numpy==2.2.0"]) ... def score(value: float) -> float: ... return value * 2 >>> score(1.5) 3.0 >>> import pyarrow as pa - >>> @udf( + >>> @function( ... input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), ... output_schema=pa.int64(), ... ) @@ -2209,25 +2620,73 @@ def udf( ... return value >>> batch_identity(pa.array([1, 2, 3])).to_pylist() [1, 2, 3] - >>> @udf(pip=["cupy-cuda12x"], gpu=True) + >>> @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") ... def gpu_score(value: int) -> int: ... return value * 2 >>> gpu_score.registration_request.runtime.gpu True - >>> @udf + >>> gpu_score.registration_request.runtime.gpu_class + 'a10g' + >>> @function ... class scale: ... def __init__(self, factor: float, offset: float = 0.0): ... self.factor, self.offset = factor, offset ... def __call__(self, value: float) -> float: ... return value * self.factor + self.offset - >>> scale(factor=2.0)(1.5) + ... def close(self): + ... self.factor = 0.0 + >>> scale_fn = scale(factor=2.0) + >>> scale_fn(1.5) 3.0 + >>> scale_fn(2.0) + 4.0 + >>> scale_fn.close() >>> [field.name for field in scale.registration_request.signature.initialization] ['factor', 'offset'] + >>> import lancedb + >>> @function( + ... input_schema=pa.schema([lancedb.blob("image", nullable=False)]), + ... output_schema=lancedb.blob("copy", nullable=False), + ... ) + ... def copy_blobs(image: pa.Array) -> pa.Array: + ... return image + + **Local execution.** A function definition is callable with its decorated + input signature and runs the original function in the current Python + environment. A class definition is called with its initialization + arguments and constructs one instance; call that instance for row inputs, + reuse it as needed, and call ``close`` if it defines that method. This path + does not create a registered + [FunctionVersion][lancedb.functions.FunctionVersion], build the declared + 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]. + + ```python + scaled = scale(factor=2.0) + try: + assert scaled(1.5) == 3.0 + assert scaled(2.0) == 4.0 + finally: + scaled.close() + ``` + + Blob v2 input is exposed as ``pyarrow.LargeBinaryArray`` in vectorized + mode (and as ``bytes`` in row mode). Return a ``LargeBinaryArray`` with the + declared nullability. Use :func:`lancedb.blob` in the explicit schemas; + plain ``pyarrow.large_binary()`` does not carry Blob v2 semantics. + + A Blob v2 field may sit at the top level or inside a struct in inputs and + outputs. Only outputs may nest it in a list or large list (for example + ``pa.list_(lancedb.blob("item"))``, returned as a list of ``bytes``); + fixed-size lists and maps are not supported. List-nested Blob v2 values + are queryable as Blob descriptors, but the row-id blob fetch APIs and + ``blob_mode="bytes"`` cannot fetch payloads inside lists. """ - def decorate(target: Any) -> UdfDefinition: - return UdfDefinition( + def decorate(target: Any) -> FunctionDefinition: + return FunctionDefinition( target, name=name, input_schema=input_schema, @@ -2235,16 +2694,22 @@ def udf( pip=tuple(pip), env={} if env is None else env, python_version=python_version, + batch_size=batch_size, + row_timeout_seconds=row_timeout_seconds, + retry_policy=retry_policy, gpu=gpu, + gpu_class=gpu_class, conda=tuple(conda), conda_channels=tuple(conda_channels), apt=tuple(apt), + image=image, code=tuple(code), + models=tuple(models), ) - if function is None: + if target is None: return decorate - return decorate(function) + return decorate(target) __all__ = [ @@ -2258,17 +2723,44 @@ __all__ = [ "FunctionOutput", "FunctionParameter", "FunctionRegistrationRequest", + "FunctionRetryPolicy", "FunctionResultField", "FunctionSignature", "FunctionImage", "FunctionVersion", "FunctionVersionRef", + "HuggingFaceModel", "InputBinding", "OutputMapping", "PythonEnvironmentSpec", "PythonAdapterSpec", "PythonRuntimeSpec", "RefreshColumnResult", - "UdfDefinition", - "udf", + "FunctionDefinition", ] + + +def udf(*args: Any, **kwargs: Any) -> Any: + """Deprecated alias of :func:`function`.""" + warnings.warn( + "lancedb.udf is deprecated; use lancedb.function", + DeprecationWarning, + stacklevel=2, + ) + return function(*args, **kwargs) + + +UDF_DEFINITION_DEPRECATION = ( + "lancedb.UdfDefinition is deprecated; use lancedb.FunctionDefinition" +) + + +def __getattr__(name: str) -> Any: + if name == "UdfDefinition": + warnings.warn(UDF_DEFINITION_DEPRECATION, DeprecationWarning, stacklevel=2) + return FunctionDefinition + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +if TYPE_CHECKING: + UdfDefinition = FunctionDefinition diff --git a/python/python/lancedb/graph.py b/python/python/lancedb/graph.py new file mode 100644 index 000000000..cbdcdb009 --- /dev/null +++ b/python/python/lancedb/graph.py @@ -0,0 +1,256 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Property graphs: graphs defined over tables a database already holds. + +A property graph stores no rows. Its definition says which tables of its +namespace hold nodes and which hold edges: each node table's key and label +(:class:`NodeTable`), and each edge table's label and the node keys its source +and destination columns reference (:class:`EdgeTable`) -- the shape of +SQL/PGQ's ``CREATE PROPERTY GRAPH``. A query reads the tables through SQL +``GRAPH_TABLE``, as they are when it runs. + +See ``DBConnection.create_property_graph``. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple + +from .background_loop import LOOP + +if TYPE_CHECKING: + from ._lancedb import Connection as LanceDbConnection + + +@dataclass(frozen=True) +class NodeTable: + """A table whose rows are the nodes of one label.""" + + table: str + """The table, in the graph's namespace.""" + key: str + """The column that identifies a node.""" + label: str + """The label its nodes carry.""" + properties: Optional[List[str]] = None + """The columns exposed as node properties; every column when ``None``. A + created graph reports the list it resolved to, the key among them.""" + + +@dataclass(frozen=True) +class Endpoint: + """One end of an edge: a column of the edge table and the node key it holds.""" + + column: str + """The edge table's column.""" + references: Tuple[str, str] + """The node table and its key column, as ``(table, column)``.""" + + +@dataclass(frozen=True) +class EdgeTable: + """A table whose rows are the edges of one label.""" + + table: str + """The table, in the graph's namespace.""" + label: str + """The label its edges carry.""" + source: Endpoint + """The column naming each edge's source node.""" + destination: Endpoint + """The column naming each edge's destination node.""" + properties: Optional[List[str]] = None + """The columns exposed as edge properties; every column when ``None``. A + created graph reports the list it resolved to, both endpoint columns among + them.""" + + +@dataclass(frozen=True) +class PropertyGraphDescription: + """What a database records about one property graph.""" + + name: str + """The graph's name within its namespace.""" + namespace_path: List[str] + """The namespace holding the graph; empty is the root namespace.""" + nodes: List[NodeTable] + """The node tables, each with the properties create resolved.""" + edges: List[EdgeTable] + """The edge tables, each with the properties create resolved.""" + + +def _definition_json(nodes: Sequence[NodeTable], edges: Sequence[EdgeTable]) -> str: + """The definition a create request carries, refusing elements of the wrong + type before any request is made.""" + nodes, edges = list(nodes), list(edges) + for element, expected in [ + *((node, NodeTable) for node in nodes), + *((edge, EdgeTable) for edge in edges), + ]: + if not isinstance(element, expected): + raise TypeError( + "A property graph's nodes are NodeTable and its edges EdgeTable, " + f"not {type(element).__name__}" + ) + return json.dumps( + { + "nodes": [_node_table_to_json(node) for node in nodes], + "edges": [_edge_table_to_json(edge) for edge in edges], + } + ) + + +def _description_from_json(text: str) -> PropertyGraphDescription: + described = json.loads(text) + return PropertyGraphDescription( + name=described["name"], + namespace_path=list(described.get("namespace", [])), + nodes=[_node_table_from_json(node) for node in described["nodes"]], + edges=[_edge_table_from_json(edge) for edge in described.get("edges", [])], + ) + + +def _properties_to_json( + encoded: Dict[str, Any], properties: Optional[List[str]] +) -> None: + # Absent means every column, which an empty list would not. + if properties is None: + return + if isinstance(properties, str): + raise TypeError("properties is a list of column names, not a string") + encoded["properties"] = list(properties) + + +def _node_table_to_json(node: NodeTable) -> Dict[str, Any]: + encoded: Dict[str, Any] = { + "table": node.table, + "key": node.key, + "label": node.label, + } + _properties_to_json(encoded, node.properties) + return encoded + + +def _edge_table_to_json(edge: EdgeTable) -> Dict[str, Any]: + encoded: Dict[str, Any] = { + "table": edge.table, + "label": edge.label, + "source": _endpoint_to_json(edge.source), + "destination": _endpoint_to_json(edge.destination), + } + _properties_to_json(encoded, edge.properties) + return encoded + + +def _endpoint_to_json(endpoint: Endpoint) -> Dict[str, Any]: + if not isinstance(endpoint, Endpoint): + raise TypeError( + "An edge's source and destination are Endpoint, " + f"not {type(endpoint).__name__}" + ) + table, column = endpoint.references + return { + "column": endpoint.column, + "references": {"table": table, "column": column}, + } + + +def _node_table_from_json(node: Dict[str, Any]) -> NodeTable: + return NodeTable( + table=node["table"], + key=node["key"], + label=node["label"], + properties=node.get("properties"), + ) + + +def _edge_table_from_json(edge: Dict[str, Any]) -> EdgeTable: + return EdgeTable( + table=edge["table"], + label=edge["label"], + source=_endpoint_from_json(edge["source"]), + destination=_endpoint_from_json(edge["destination"]), + properties=edge.get("properties"), + ) + + +def _endpoint_from_json(endpoint: Dict[str, Any]) -> Endpoint: + references = endpoint["references"] + return Endpoint( + column=endpoint["column"], + references=(references["table"], references["column"]), + ) + + +class AsyncPropertyGraph: + """A handle on one property graph: its name and namespace, and the + connection it is described through. + + Obtained from ``AsyncConnection.create_property_graph`` or + ``AsyncConnection.open_property_graph``. The graph is queried through SQL + ``GRAPH_TABLE``, not through this handle. + """ + + def __init__( + self, + inner: "LanceDbConnection", + name: str, + namespace_path: Optional[List[str]] = None, + ): + self._inner = inner + self._name = name + self._namespace_path = list(namespace_path or []) + + def __repr__(self) -> str: + return ( + f"AsyncPropertyGraph(name={self._name!r}, " + f"namespace_path={self._namespace_path!r})" + ) + + @property + def name(self) -> str: + """The graph's name within its namespace.""" + return self._name + + @property + def namespace_path(self) -> List[str]: + """The namespace holding the graph; empty is the root namespace.""" + return list(self._namespace_path) + + async def describe(self) -> PropertyGraphDescription: + """The graph's node and edge tables, each with the properties create + resolved.""" + return _description_from_json( + await self._inner.describe_property_graph(self._name, self._namespace_path) + ) + + +class PropertyGraph: + """Synchronous variant of + [AsyncPropertyGraph][lancedb.graph.AsyncPropertyGraph].""" + + def __init__(self, graph: AsyncPropertyGraph): + self._async = graph + + def __repr__(self) -> str: + return ( + f"PropertyGraph(name={self.name!r}, namespace_path={self.namespace_path!r})" + ) + + @property + def name(self) -> str: + """The graph's name within its namespace.""" + return self._async.name + + @property + def namespace_path(self) -> List[str]: + """The namespace holding the graph; empty is the root namespace.""" + return self._async.namespace_path + + def describe(self) -> PropertyGraphDescription: + """The graph's node and edge tables, each with the properties create + resolved.""" + return LOOP.run(self._async.describe()) diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py index 8c192a2f0..9f53f203b 100644 --- a/python/python/lancedb/index.py +++ b/python/python/lancedb/index.py @@ -85,7 +85,7 @@ class LabelList: """Describe a LabelList index configuration. `LabelList` is a scalar index that can be used on `List` columns to - support queries with `array_contains_all` and `array_contains_any` + support queries with `array_has_all` and `array_has_any` using an underlying bitmap index. For example, it works with `tags`, `categories`, `keywords`, etc. @@ -108,6 +108,28 @@ class Fm: pass +@dataclass +class NGram: + """Describe an NGram index configuration. + + An `NGram` index is a scalar index on a UTF-8 string column that + accelerates substring filters such as `contains(col, 'needle')`, along + with some `LIKE` and regular-expression predicates. It tokenizes values + into overlapping character n-grams (using Lance's default trigram + parameters) and narrows a scan to the rows that share the query's n-grams; + the exact predicate is then evaluated on those candidates, so the results + are the same with or without the index. + + Unlike the `Fm` index, which matches arbitrary substrings of the raw + bytes, `NGram` is trigram based, so a query shorter than the n-gram length + cannot be served by the index. + + For example, it works with `text`, `description`, `comment`, etc. + """ + + pass + + @dataclass class FTS: """Describe a FTS index configuration. @@ -145,7 +167,7 @@ class FTS: Lance tokenizer can panic on malformed triples; see https://github.com/lance-format/lance/issues/8812. - LanceDB Distributed uses the same ``FTS()`` configuration and requires a + LanceDB Enterprise uses the same ``FTS()`` configuration and requires a server that supports JSON FTS. Wait for ``table.wait_for_index(["doc_idx"])`` before searching a newly created index there with its default name. @@ -160,6 +182,10 @@ class FTS: >>> from lancedb.query import DocumentGranularity >>> config = FTS(document_granularity=DocumentGranularity.LIST_ELEMENT) + Create an index that splits code identifiers into searchable subwords: + + >>> config = FTS(analyzer="code", split_identifiers=True) + Attributes ---------- with_position : bool, default False @@ -210,17 +236,39 @@ class FTS: memory_limit : int, optional The total memory limit in MiB for the local FTS build stage. The limit is divided evenly among indexing workers. This build-only setting is - not persisted with the index and does not apply to LanceDB Distributed. + not persisted with the index and does not apply to LanceDB Enterprise. num_workers : int, optional The number of workers for a local FTS build. By default Lance uses roughly half of the available CPU cores. The effective value is limited by the available compute capacity. This build-only setting is - not persisted with the index and does not apply to LanceDB Distributed. + not persisted with the index and does not apply to LanceDB Enterprise. document_granularity : DocumentGranularity, default ROW ``ROW`` treats the selected text in one table row as one document. ``LIST_ELEMENT`` treats each element of the deepest list on the indexed field path as one document and returns its physical coordinates in ``_doc_index`` for matching queries. + analyzer : {"text", "code"}, optional + ``"code"`` selects the code analyzer. ``"text"`` selects a text-family + analyzer with the selected ``base_tokenizer``; it does not reset an + explicit compatible tokenizer to ``"simple"``. ``None`` infers the + analyzer from ``base_tokenizer``. ``"code"`` cannot be combined with a + ``base_tokenizer`` other than ``"simple"`` (the default) or ``"code"``. + ``"text"`` cannot be combined with ``"code"``. + split_identifiers : bool, optional + Split code identifiers such as ``camelCase`` and ``snake_case`` into + subwords. Setting this to True requires the code analyzer. The default + is False, so ``analyzer="code"`` alone keeps identifiers whole. + split_on_numerics : bool, optional + Split identifier subwords at letter and number boundaries, for example + ``utf8`` into ``utf`` and ``8``. The code analyzer default is True, but + this only takes effect when ``split_identifiers=True``. + preserve_original : bool, optional + Also index the complete identifier next to its subwords. The code + analyzer default is True, but this only takes effect when + ``split_identifiers=True``. + index_operators : bool, optional + Index code operators such as ``::``, ``->`` and ``!=``. The code + analyzer default is False. Notes ----- @@ -246,6 +294,11 @@ class FTS: memory_limit: Optional[int] = None num_workers: Optional[int] = None document_granularity: DocumentGranularity = DocumentGranularity.ROW + analyzer: Optional[Literal["text", "code"]] = None + split_identifiers: Optional[bool] = None + split_on_numerics: Optional[bool] = None + preserve_original: Optional[bool] = None + index_operators: Optional[bool] = None @dataclass @@ -930,4 +983,5 @@ __all__ = [ "Bitmap", "LabelList", "Fm", + "NGram", ] diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index e61a188f2..92b545ce7 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -5,6 +5,7 @@ import asyncio import json +import time from datetime import timedelta from typing import Any, Callable, Generic, Optional, TypeVar, cast @@ -13,7 +14,8 @@ import pyarrow as pa from lancedb.background_loop import LOOP from . import _lancedb -from ._lancedb import JobDescription, JobFailureInfo, JobInfo +from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url +from .remote.errors import HttpError, RetryError T = TypeVar("T") @@ -26,6 +28,162 @@ __all__ = [ ] +def _timeout_message( + job_id: Optional[str], timeout: timedelta, job_type: Optional[str] +) -> str: + seconds = f"{timeout.total_seconds():g}" + unit = "second" if seconds == "1" else "seconds" + if job_id is None: + return ( + f"operation still running after {seconds} {unit}; " + "it continues on the server" + ) + if job_type == "query": + return ( + f"query {job_id!r} still running after {seconds} {unit}; " + "it continues on the server; keep this handle to continue waiting" + ) + return ( + f"job {job_id!r} still running after {seconds} {unit}; " + "it continues on the server; " + f"reattach with db.open_job({job_id!r}).wait()" + ) + + +def _normalize_job_progress(progress): + """Normalize ``wait(progress=...)`` using the same convention as writes.""" + if progress is True: + from tqdm.auto import tqdm + + return tqdm(unit=" rows"), True + if progress is False or progress is None: + return None, False + return progress, False + + +_ETA_MAX_SAMPLE_INTERVAL_MILLIS = 10 * 60 * 1_000 + + +def _progress_eta(previous, current): + """Best-effort remaining time from two same-execution observations.""" + if not previous or current.get("state") not in ("running", "finished"): + return None + remaining = current.get("rows_remaining") + if current.get("state") == "finished": + return 0 if remaining == 0 else None + if current.get("paused") or current.get("phase") in ( + "queued", + "starting", + "paused", + ): + return None + epoch = current.get("execution_epoch") + if epoch is None or previous.get("execution_epoch") != epoch: + return None + sample_at = current.get("sample_at_millis") + previous_at = previous.get("sample_at_millis") + if not isinstance(sample_at, int) or not isinstance(previous_at, int): + return None + elapsed = sample_at - previous_at + if not 0 < elapsed <= _ETA_MAX_SAMPLE_INTERVAL_MILLIS: + return None + if time.time() * 1_000 - sample_at > _ETA_MAX_SAMPLE_INTERVAL_MILLIS: + return None + planned = current.get("rows_planned") + if not isinstance(planned, int) or not isinstance(remaining, int): + return None + if remaining == 0: + return 0 + if planned != previous.get("rows_planned"): + return None + if current.get("fragments_planned") != previous.get("fragments_planned"): + return None + accounted = current.get("rows_computed", 0) + current.get("rows_skipped", 0) + previous_accounted = previous.get("rows_computed", 0) + previous.get( + "rows_skipped", 0 + ) + advanced = accounted - previous_accounted + previous_remaining = previous.get("rows_remaining") + if advanced <= 0 or not isinstance(previous_remaining, int): + return None + if remaining > previous_remaining: + return None + return remaining * elapsed // advanced + + +def _with_progress_eta(previous, current): + snapshot = dict(current) + estimate = _progress_eta(previous, snapshot) + if estimate is not None: + snapshot["estimated_remaining_time_millis"] = estimate + return snapshot + + +def _job_progress_callback(progress, enrich): + """Adapt a callback or tqdm-like object to structured job snapshots.""" + if progress is None: + return None + if callable(progress): + return lambda snapshot: progress(enrich(snapshot)) + + # A caller-owned bar can outlive one wait call. Resume from its displayed + # position instead of adding the same completed rows on the next call. + last_rows = getattr(progress, "n", 0) or 0 + last_planned = getattr(progress, "total", None) + last_epoch = None + first_snapshot = True + + def update(snapshot): + nonlocal first_snapshot, last_epoch, last_planned, last_rows + snapshot = enrich(snapshot) + planned = snapshot.get("rows_planned") + remaining = snapshot.get("rows_remaining") + computed = snapshot.get("rows_computed") + if isinstance(planned, int): + epoch = snapshot.get("execution_epoch") + reset = (isinstance(last_planned, int) and planned < last_planned) or ( + isinstance(last_epoch, int) + and isinstance(epoch, int) + and epoch != last_epoch + ) + if reset: + last_rows = 0 + if hasattr(progress, "reset"): + progress.reset(total=planned) + elif hasattr(progress, "n"): + progress.n = 0 + progress.total = planned + last_planned = planned + if isinstance(epoch, int): + last_epoch = epoch + completed = None + if isinstance(planned, int) and isinstance(remaining, int): + completed = max(planned - remaining, 0) + elif computed is not None: + completed = computed + if completed is not None: + if isinstance(planned, int): + completed = min(completed, planned) + if first_snapshot and completed < last_rows: + # The server may have started a new execution while a + # caller-owned bar retained its old position. + last_rows = completed + if hasattr(progress, "n"): + progress.n = completed + if hasattr(progress, "refresh"): + progress.refresh() + if completed > last_rows: + delta = completed - last_rows + last_rows = completed + progress.update(delta) + first_snapshot = False + phase = snapshot.get("phase") or snapshot.get("state") + if phase is not None and hasattr(progress, "set_postfix_str"): + progress.set_postfix_str(phase) + + return update + + class AsyncJob(Generic[T]): """A handle to an operation that may still be running. @@ -41,6 +199,12 @@ class AsyncJob(Generic[T]): ): self._inner = inner self._result_decoder = result_decoder + self._last_progress_snapshot = 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]: @@ -65,21 +229,118 @@ class AsyncJob(Generic[T]): return "finished" return await self._inner.status() - async def wait(self, timeout: Optional[timedelta] = None) -> T: + async def progress(self) -> Optional[dict[str, Any]]: + """Fetch a structured progress snapshot. + + Registry jobs always report lifecycle fields. Queue metadata and + counters are included when supplied by the server. Older servers may + 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. + """ + if self._inner is None: + return None + await self._inner.status() + description = getattr(self._inner, "_description", None) + if description is None or description.progress is None: + return None + return self._enrich_progress(description.progress) + + async def wait( + self, + timeout: Optional[timedelta] = None, + progress: Any = False, + ) -> T: """Wait until the operation reaches a terminal state. Returns the endpoint's typed result, or ``None`` for a unit-result job. + ``progress=True`` renders a progress bar, ``progress=callable`` + receives each structured snapshot, and a tqdm-like object is updated in + place. Observations use the backend's existing wait poller and never + start a second job. The bar advances by remaining rows when available, + because completed computation can include repeated work after a plan + change. On each wait call, the first complete observation synchronizes + 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. + ``False`` preserves the original wait behavior. + Raises `JobFailedError` if the operation failed, `JobCancelledError` if it was cancelled, and `TimeoutError` if `timeout` elapses first. + Transient connection and read errors are retried with capped exponential + backoff within the same timeout (indefinitely when no timeout is given). + If the timeout expires while disconnected, raises `ConnectionError` + instead, with the job ID and instructions to resume waiting. The job + may still be running; timing out does not cancel it. + + The timeout error identifies the job and explains that it continues on + the server. Registry jobs include the ``db.open_job(id).wait()`` + reattach call; SQL query handles must be kept because their IDs cannot + be reopened through the registry jobs API. """ if self._inner is None: return cast(T, None) - if timeout is None: - result = await self._inner.wait() - else: - result = await asyncio.wait_for(self._inner.wait(), timeout.total_seconds()) + progress_obj, owns = _normalize_job_progress(progress) + progress_callback = _job_progress_callback(progress_obj, self._enrich_progress) + last_error = None + + async def wait_with_retries(): + nonlocal last_error + delay = 0.25 + while True: + try: + if last_error is not None: + # Confirm recovery before restarting the backend poller, + # so a later timeout isn't blamed on an earlier outage. + await self._inner.status() + last_error = None + delay = 0.25 + if progress_callback is None: + return await self._inner.wait() + return await self._inner.wait(progress=progress_callback) + except (HttpError, RetryError) as error: + cause = error.__cause__ if isinstance(error, RetryError) else error + if not isinstance(cause, HttpError) or not cause.is_transport_error: + raise + last_error = error + await asyncio.sleep(delay) + delay = min(delay * 2, 30.0) + + try: + try: + if timeout is None: + result = await wait_with_retries() + else: + result = await asyncio.wait_for( + wait_with_retries(), timeout.total_seconds() + ) + except asyncio.TimeoutError as error: + if last_error is None: + if timeout is None: + raise + raise TimeoutError( + _timeout_message(self.id, timeout, self.job_type) + ) from error + identity = ( + 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": + reconnect = ( + 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." + raise ConnectionError( + f"Lost connection while waiting and the timeout expired; " + f"{identity} may still be running. " + f"{reconnect}" + ) from last_error + finally: + if owns: + progress_obj.close() if self._result_decoder is not None: return self._result_decoder(result) return cast(T, result) @@ -188,7 +449,10 @@ class AsyncJob(Generic[T]): """ if self._inner is None: raise NotImplementedError( - "job event history is only available for server-side jobs" + _append_doc_url( + "job event history is only available for server-side jobs", + "jobs", + ) ) return await self._inner.events(limit=limit, filter=filter) @@ -262,7 +526,11 @@ class Job(Generic[T]): return "finished" return LOOP.run(self._inner.status()) - def wait(self, timeout: Optional[timedelta] = None) -> T: + def wait( + self, + timeout: Optional[timedelta] = None, + progress: Any = False, + ) -> T: """Block until the operation reaches a terminal state. Returns the endpoint's typed result, or ``None`` for a unit-result @@ -270,10 +538,26 @@ class Job(Generic[T]): Raises `JobFailedError` if the operation failed, `JobCancelledError` if it was cancelled, and `TimeoutError` if `timeout` elapses first. + Transient connection and read errors are retried within that timeout; + if it expires while disconnected, raises `ConnectionError` with + instructions to reconnect. Timing out does not cancel the job. + + The timeout error identifies the job and explains that it continues on + the server. Registry jobs include the ``db.open_job(id).wait()`` + reattach call; SQL query handles must be kept because their IDs cannot + be reopened through the registry jobs API. + + See :meth:`AsyncJob.wait`. """ if self._inner is None: return cast(T, None) - return LOOP.run(self._inner.wait(timeout)) + return LOOP.run(self._inner.wait(timeout, progress=progress)) + + def progress(self) -> Optional[dict[str, Any]]: + """Fetch a structured progress snapshot. See :meth:`AsyncJob.progress`.""" + if self._inner is None: + return None + return LOOP.run(self._inner.progress()) def cancel(self): """Request cancellation. Cancelling a finished operation is a no-op.""" @@ -343,7 +627,10 @@ class Job(Generic[T]): """ if self._inner is None: raise NotImplementedError( - "job event history is only available for server-side jobs" + _append_doc_url( + "job event history is only available for server-side jobs", + "jobs", + ) ) return LOOP.run(self._inner.events(limit=limit, filter=filter)) diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index 7b0b3b80a..7b8c8c6a4 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -6,7 +6,7 @@ maintained by refresh. See ``DBConnection.create_materialized_view``. LanceDB Embedded creation and refresh require the ``experimental-functions`` Cargo feature in a source build. Published packages disable it. Opening, reading, -listing and dropping existing views and LanceDB Distributed operations remain +listing and dropping existing views and LanceDB Enterprise operations remain available. """ @@ -17,6 +17,7 @@ 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 @@ -156,6 +157,34 @@ 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") + return {name: value for name, value in values.items() if value is not None} + + class AsyncMaterializedView: """A handle on a materialized view: its table plus its definition. @@ -185,38 +214,73 @@ class AsyncMaterializedView: return _definition_from_json(raw) async def refresh( - self, *, full: bool = False, source_version: Optional[int] = None + self, + *, + full: bool = False, + source_version: Optional[int] = None, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. - In LanceDB Distributed, ``full=True`` forces a rebuild; otherwise the + In LanceDB Enterprise, ``full=True`` forces a rebuild; otherwise the server chooses the refresh mode. LanceDB Embedded views always rebuild, and ``source_version`` selects a source version instead of the latest. - LanceDB Distributed SQL refreshes do not support source-version pinning. + LanceDB Enterprise SQL refreshes do not support source-version pinning. - LanceDB Distributed results leave ``mode``, ``rows_written``, and + ``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. + These options require an Enterprise backend that enforces isolation; + Embedded refreshes reject them. Other servers may reject the new options. + + LanceDB Enterprise results leave ``mode``, ``rows_written``, and ``source_version`` as ``None`` because the SQL job adapter does not expose these metrics. """ return await self._table._inner.refresh_materialized_view( - source_version=source_version, full=full + source_version=source_version, + full=full, + **_refresh_execution_options( + cpu_millis, memory_bytes, gpu_count, gpu_class + ), ) async def refresh_async( - self, *, full: bool = False, source_version: Optional[int] = None + self, + *, + full: bool = False, + source_version: Optional[int] = None, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> "AsyncJob[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. The job may already be complete in LanceDB Embedded. In LanceDB - Distributed, refreshes are submitted through the SQL service. Options and + Distributed, refreshes are submitted through the SQL service and the + returned ``id`` is the registry job ID, usable with ``open_job`` for + progress, events, and cancellation while the refresh runs. Options and result metrics follow [refresh][lancedb.materialized_view.AsyncMaterializedView.refresh]. + + Servers without early registry-handle support return a connection-scoped + query job instead. Its ID cannot be reopened with ``open_job``. """ from ._lancedb import RefreshMaterializedViewResult return _typed_job( await self._table._inner.refresh_materialized_view_async( - source_version=source_version, full=full + source_version=source_version, + full=full, + **_refresh_execution_options( + cpu_millis, memory_bytes, gpu_count, gpu_class + ), ), RefreshMaterializedViewResult.from_json, ) @@ -248,14 +312,36 @@ class MaterializedView: return LOOP.run(self._async.definition()) def refresh( - self, *, full: bool = False, source_version: Optional[int] = None + self, + *, + full: bool = False, + source_version: Optional[int] = None, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. See [AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh].""" - return LOOP.run(self._async.refresh(full=full, source_version=source_version)) + return LOOP.run( + self._async.refresh( + full=full, + source_version=source_version, + **_refresh_execution_options( + cpu_millis, memory_bytes, gpu_count, gpu_class + ), + ) + ) def refresh_async( - self, *, full: bool = False, source_version: Optional[int] = None + self, + *, + full: bool = False, + source_version: Optional[int] = None, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> "Job[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. @@ -264,6 +350,12 @@ class MaterializedView: """ return Job( LOOP.run( - self._async.refresh_async(full=full, source_version=source_version) + self._async.refresh_async( + full=full, + source_version=source_version, + **_refresh_execution_options( + cpu_millis, memory_bytes, gpu_count, gpu_class + ), + ) ) ) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index b70c96979..a6f584f8a 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -548,7 +548,7 @@ class Permutation: picklable classes implementing ``__call__``. Lambdas and closures over local variables don't pickle with the default protocol. - A factory is optional for normal LanceDB Embedded and Distributed connections: + A factory is optional for normal LanceDB Embedded and Enterprise connections: if not set, ``__getstate__`` captures the table's own picklable reopen state. Use a factory when that default state is not enough, for example when credentials should be loaded from the worker environment instead diff --git a/python/python/lancedb/pydantic.py b/python/python/lancedb/pydantic.py index d2b5cb22d..4d77ecd15 100644 --- a/python/python/lancedb/pydantic.py +++ b/python/python/lancedb/pydantic.py @@ -9,16 +9,19 @@ import inspect import sys import types from abc import ABC, abstractmethod -from datetime import date, datetime +from datetime import date, datetime, time, timedelta from enum import Enum from typing import ( TYPE_CHECKING, Any, List, + Literal, Type, Union, _GenericAlias, GenericAlias, + get_args, + get_origin, ) import pyarrow as pa @@ -247,6 +250,19 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType: elif py_type is datetime: tz = get_extras(field, "tz") return pa.timestamp("us", tz=tz) + elif py_type is time: + return pa.time64("us") + elif py_type is timedelta: + return pa.duration("us") + elif get_origin(py_type) is Literal: + # Store a Literal as the type of its values, e.g. Literal["a", "b"] as utf8. + value_types = {type(value) for value in get_args(py_type)} + if len(value_types) != 1: + raise TypeError( + "Converting Pydantic type to Arrow Type: unsupported type " + f"{py_type}. All values of a Literal must have the same type." + ) + return _pydantic_type_to_arrow_type(value_types.pop(), field) elif getattr(py_type, "__origin__", None) in (list, tuple): # A bare, unparameterised ``typing.List`` / ``typing.Tuple`` matches this # branch (its ``__origin__`` is ``list`` / ``tuple``) but has no @@ -304,8 +320,12 @@ def _pydantic_type_to_arrow_type(tp: Any, field: FieldInfo) -> pa.DataType: # Map Enum to the Arrow type of its value. # For string-valued enums, use dictionary encoding for efficiency. # For integer enums, use the native type. - # Fall back to utf8 for mixed-type or empty enums. value_types = {type(m.value) for m in tp} + if len(value_types) > 1: + raise TypeError( + f"Converting Pydantic Enum {tp.__name__} to Arrow Type: " + "all enum values must have the same type." + ) if len(value_types) == 1: value_type = value_types.pop() if value_type is str: @@ -435,7 +455,8 @@ def pydantic_to_schema(model: Type[pydantic.BaseModel]) -> pa.Schema: an Arrow list, so all its elements must have the same type, as in ``Tuple[int, int]`` or ``Tuple[float, ...]``; for a fixed set of fields with different types, such as ``Tuple[int, str]``, use a nested - ``LanceModel`` (an Arrow struct) instead. + ``LanceModel`` (an Arrow struct) instead. Enum values must also all + have the same type. Examples -------- @@ -556,21 +577,36 @@ def get_extras(field_info: FieldInfo, key: str) -> Any: def model_to_dict(model: pydantic.BaseModel) -> dict[str, Any]: - """Convert a Pydantic model to a dictionary.""" - return _enum_members_to_values(model.model_dump()) + """Convert a Pydantic model to a dictionary. + + Raises + ------ + ValueError + If a ``datetime.time`` value has a non-null ``tzinfo``. LanceDB stores + times as timezone-naive wall-clock values and cannot preserve the offset. + """ + return _model_value_to_arrow_compatible(model.model_dump()) -def _enum_members_to_values(value: Any) -> Any: +def _model_value_to_arrow_compatible(value: Any) -> Any: # model_dump() keeps Enum members, and Arrow cannot convert a member of a # plain Enum (one without a str or int mixin). Write its value instead, # which is what the Arrow type of the field is derived from. if isinstance(value, Enum): - return value.value + value = value.value + if isinstance(value, time): + if value.tzinfo is not None: + raise ValueError( + "LanceDB supports timezone-naive wall-clock datetime.time values " + "only; time values with tzinfo cannot be written losslessly. Remove " + "the timezone offset or store it in a separate field." + ) + return value if isinstance(value, dict): - return {k: _enum_members_to_values(v) for k, v in value.items()} + return {k: _model_value_to_arrow_compatible(v) for k, v in value.items()} if isinstance(value, (list, tuple)) and value: # Skip lists of plain scalars, such as vectors, without walking them. if isinstance(value[0], (int, float, str, bytes)): return value - return [_enum_members_to_values(v) for v in value] + return [_model_value_to_arrow_compatible(v) for v in value] return value diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index c9ca258e7..4a3fea2e2 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -81,6 +81,85 @@ if TYPE_CHECKING: from typing_extensions import Self T = TypeVar("T", bound="LanceModel") + + +def _top_level_alias_key(alias: Any) -> str | None: + if isinstance(alias, str): + return alias + if isinstance(alias, pydantic.AliasPath) and alias.path: + key = alias.path[0] + return key if isinstance(key, str) else None + return None + + +def _top_level_alias_keys(alias: Any) -> set[str]: + options = alias.choices if isinstance(alias, pydantic.AliasChoices) else (alias,) + return { + key for option in options if (key := _top_level_alias_key(option)) is not None + } + + +def _single_component_alias(alias: Any) -> str | None: + # AliasChoices validates against the first matching source, so only use + # its first option as a field-name fallback. + option = alias.choices[0] if isinstance(alias, pydantic.AliasChoices) else alias + if isinstance(option, pydantic.AliasPath) and len(option.path) != 1: + # A nested path needs a structured payload; do not infer one here. + return None + return _top_level_alias_key(option) + + +def _rows_to_models(model: type[T], rows: List[dict]) -> List[T]: + """Build ``model`` instances from result rows. + + A table created from a LanceModel stores each field under its name, while + pydantic validates an aliased field by its alias. Pass a row's value under + the alias when the row has the field name but none of the aliases, so a + model with aliases can read the tables it wrote; rows keyed by any alias + still work. + """ + if model.model_config.get("validate_by_alias", True) is False: + # Name-only validation: pydantic reads field names and ignores aliases. + return [model(**row) for row in rows] + aliases = { + name: field.validation_alias or field.alias + for name, field in model.model_fields.items() + } + # populate_by_name is the pre-2.11 spelling; an explicit new flag wins. + accepts_by_name = model.model_config.get( + "validate_by_name", + model.model_config.get("populate_by_name", False), + ) + # Every top-level key some field reads, including the first step of an + # AliasPath and each choice of an AliasChoices. + alias_keys = {} + for name, alias in aliases.items(): + keys = _top_level_alias_keys(alias) + if not keys or accepts_by_name: + keys.add(name) + alias_keys[name] = keys + readers = {} + for name, keys in alias_keys.items(): + for key in keys: + readers.setdefault(key, set()).add(name) + renames = { + name: target + for name, alias in aliases.items() + if (target := _single_component_alias(alias)) is not None + # Do not move a source that another field reads. + and target != name + and not (readers.get(name, set()) - {name}) + # Do not add a source that another field accepts. Introducing a shared + # alias key could change that field's Pydantic selection. + and not (readers.get(target, set()) - {name}) + } + for row in rows: + for name, target in renames.items(): + if name in row and not any(key in row for key in alias_keys[name]): + row[target] = row.pop(name) + return [model(**row) for row in rows] + + AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"] _SYNC_VECTOR_QUERY_TYPES = (list, tuple, np.ndarray, pa.Array, pa.ChunkedArray) @@ -125,7 +204,7 @@ def _supports_local_blob_fetch( def _blob_bytes_without_snapshot_error() -> NotImplementedError: return NotImplementedError( "blob_mode='bytes' cannot safely materialize blob columns without a " - "stable table snapshot. LanceDB Distributed and namespace QueryTable pushdown " + "stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown " "run the query on a server, so the blob fetch could read another table " "version. Use blob_mode='descriptions'." ) @@ -157,6 +236,7 @@ def _query_is_plain_scan(query: Query) -> bool: query.vector is None and query.full_text_query is None and query.take_offsets is None + and query.take_row_ids is None and not query.postfilter and not query.order_by ) @@ -833,6 +913,12 @@ class Query(pydantic.BaseModel): ef : Optional[int] The size of the nearest neighbor list maintained during HNSW search + This will only be set on vector search. + approx_mode : Optional[str] + The speed / accuracy tradeoff to use for approximate vector search + + One of "fast", "normal" or "accurate". + This will only be set on vector search. full_text_query : Optional[Union[str, dict]] The full text search query @@ -924,6 +1010,9 @@ class Query(pydantic.BaseModel): # This is populated when a take query is converted to this serializable form. take_offsets: Optional[List[int]] = None + # Row IDs whose requested order and duplicate occurrences must be restored. + take_row_ids: Optional[List[int]] = None + # if true, will only search the indexed data fast_search: Optional[bool] = None @@ -935,6 +1024,9 @@ class Query(pydantic.BaseModel): # size of the nearest neighbor list maintained during HNSW search ef: Optional[int] = None + # speed / accuracy tradeoff for approximate vector search + approx_mode: Optional[str] = None + # Bypass the vector index and use a brute force search bypass_vector_index: Optional[bool] = None @@ -946,6 +1038,7 @@ class Query(pydantic.BaseModel): query.limit = req.limit query.offset = req.offset query.take_offsets = req.take_offsets + query.take_row_ids = req.take_row_ids query.filter = req.filter query.full_text_query = req.full_text_search query.columns = req.select @@ -965,6 +1058,7 @@ class Query(pydantic.BaseModel): query.lower_bound = req.lower_bound query.upper_bound = req.upper_bound query.ef = req.ef + query.approx_mode = req.approx_mode query.refine_factor = req.refine_factor query.bypass_vector_index = req.bypass_vector_index query.postfilter = req.postfilter @@ -1133,6 +1227,7 @@ class LanceQueryBuilder(ABC): self._vector = None self._text = None self._ef = None + self._approx_mode = None self._bypass_vector_index = None self._order_by = None @@ -1184,7 +1279,7 @@ class LanceQueryBuilder(ABC): mode and for legacy blob columns. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - LanceDB Distributed blob queries support only ``"descriptions"`` until a + LanceDB Enterprise blob queries support only ``"descriptions"`` until a stable table snapshot can bind the query and blob fetches. **kwargs @@ -1240,6 +1335,9 @@ class LanceQueryBuilder(ABC): and also the "_distance" column which is the distance between the query vector and the returned vectors. + This collects all results in memory. To process a large result a batch + at a time, use [to_batches][lancedb.query.LanceQueryBuilder.to_batches]. + Parameters ---------- timeout: Optional[timedelta] @@ -1271,6 +1369,11 @@ class LanceQueryBuilder(ABC): ``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide automatic row ids. + A remote table decodes batches as they arrive when the server streams + query results. If the response stops partway, reading raises + [ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError] + after the batches already returned, which are valid but incomplete. + Parameters ---------- batch_size: int @@ -1278,6 +1381,8 @@ class LanceQueryBuilder(ABC): timeout: Optional[timedelta] The maximum time to wait for the query to complete. If None, wait indefinitely. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. blob_mode: str, default "lazy" ``"lazy"`` keeps blob descriptors and auto row ids for manual fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2 @@ -1340,7 +1445,7 @@ class LanceQueryBuilder(ABC): ------- List[LanceModel] """ - return [model(**row) for row in self.to_arrow(timeout=timeout).to_pylist()] + return _rows_to_models(model, self.to_arrow(timeout=timeout).to_pylist()) def to_polars(self, *, timeout: Optional[timedelta] = None) -> "pl.DataFrame": """ @@ -1965,6 +2070,11 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): def search_effort(self, search_effort: Optional[float]) -> LanceVectorQueryBuilder: """Set the initial IVF search effort to a finite value in [0, 1]. + Efforts 0.1 and 0.25 target empirical mean partition-routing recall of + 80% and 90% for L2, cosine and dot through k=100000. The probe budget + adapts to the metric and k. Hamming and larger k remain uncalibrated; + 100000 is not an API limit. Remote queries also require server support. + None (the default) uses Auto, internally 0.5. Zero starts at the caller minimum; one searches all partitions within the caller maximum. Later probing may continue when too few candidates are found. Any explicit @@ -2057,6 +2167,35 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): self._ef = ef return self + def approx_mode( + self, approx_mode: Literal["fast", "normal", "accurate"] + ) -> LanceVectorQueryBuilder: + """Set the speed / accuracy tradeoff to use for approximate search. + + This currently affects RQ-quantized indexes, such as IVF_RQ, and + prefiltered search on HNSW indexes, where "fast" enables the ACORN + traversal. Other index types ignore this setting. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("memory://") + >>> table = db.create_table("approx_vectors", [{"vector": [0.1, 0.2]}]) + >>> query = table.search([0.1, 0.2]).approx_mode("fast") + + Parameters + ---------- + approx_mode: "fast" or "normal" or "accurate" + The tradeoff to use. By default "normal" is used. + + Returns + ------- + LanceVectorQueryBuilder + The LanceQueryBuilder object. + """ + self._approx_mode = approx_mode + return self + def refine_factor(self, refine_factor: int) -> LanceVectorQueryBuilder: """Set the refine factor to use, increasing the number of vectors sampled. @@ -2151,6 +2290,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): offset=self._offset, fast_search=self._fast_search, ef=self._ef, + approx_mode=self._approx_mode, bypass_vector_index=self._bypass_vector_index, order_by=self._order_by, ) @@ -2173,6 +2313,8 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): timeout: timedelta, default None The maximum time to wait for the query to complete. If None, wait indefinitely. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. blob_mode: str, default "lazy" Controls blob conversion as described in :meth:`LanceQueryBuilder.to_batches`. @@ -2709,7 +2851,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): ) if not with_row_ids and "_rowid" in empty.column_names: empty = empty.drop(["_rowid"]) - return empty + # Match the columns a non-empty result has for this reranker. Call the + # base method so an override that assumes rows never sees the empty + # table (#3030). + return Reranker._keep_relevance_score(reranker, empty) original_distances = None original_scores = None @@ -2891,6 +3036,11 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): def search_effort(self, search_effort: Optional[float]) -> LanceHybridQueryBuilder: """Set the initial IVF search effort to a finite value in [0, 1]. + Efforts 0.1 and 0.25 target empirical mean partition-routing recall of + 80% and 90% for L2, cosine and dot through k=100000. The probe budget + adapts to the metric and k. Hamming and larger k remain uncalibrated; + 100000 is not an API limit. Remote queries also require server support. + None (the default) uses Auto, internally 0.5. Zero starts at the caller minimum; one searches all partitions within the caller maximum. Later probing may continue when too few candidates are found. Any explicit @@ -2978,6 +3128,43 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): self._ef = ef return self + def approx_mode( + self, approx_mode: Literal["fast", "normal", "accurate"] + ) -> LanceHybridQueryBuilder: + """ + Set the speed / accuracy tradeoff to use for approximate search. + + This currently affects RQ-quantized indexes, such as IVF_RQ, and + prefiltered search on HNSW indexes, where "fast" enables the ACORN + traversal. Other index types ignore this setting. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("memory://") + >>> table = db.create_table( + ... "approx_hybrid", [{"vector": [0.1, 0.2], "text": "dog"}] + ... ) + >>> query = ( + ... table.search(query_type="hybrid") + ... .vector([0.1, 0.2]) + ... .text("dog") + ... .approx_mode("accurate") + ... ) + + Parameters + ---------- + approx_mode: "fast" or "normal" or "accurate" + The tradeoff to use. By default "normal" is used. + + Returns + ------- + LanceHybridQueryBuilder + The LanceHybridQueryBuilder object. + """ + self._approx_mode = approx_mode + return self + def metric(self, metric: Literal["l2", "cosine", "dot"]) -> LanceHybridQueryBuilder: """Set the distance metric to use. @@ -3222,6 +3409,8 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): self._vector_query.refine_factor(self._refine_factor) if self._ef: self._vector_query.ef(self._ef) + if self._approx_mode: + self._vector_query.approx_mode(self._approx_mode) if self._bypass_vector_index: self._vector_query.bypass_vector_index() if self._lower_bound is not None or self._upper_bound is not None: @@ -3393,6 +3582,11 @@ class AsyncQueryBase(object): """ Execute the query and return the results as an Apache Arrow RecordBatchReader. + A remote table decodes batches as they arrive when the server streams + query results. If the response stops partway, reading raises + [ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError] + after the batches already returned, which are valid but incomplete. + Parameters ---------- @@ -3405,6 +3599,8 @@ class AsyncQueryBase(object): The maximum time to wait for the query to complete. If not specified, no timeout is applied. If the query does not complete within the specified time, an error will be raised. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. blob_mode: str, default "lazy" ``"lazy"`` keeps blob descriptors and auto row ids for manual fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2 @@ -3521,7 +3717,7 @@ class AsyncQueryBase(object): ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. ``"bytes"`` returns payload bytes and raises for legacy blob columns and blobs inside lists. - LanceDB Distributed and namespace query pushdown refuse ``"bytes"``. + LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``. """ blob_sources = await self._validated_blob_sources(blob_mode) batch_iter = await self.to_batches(timeout=timeout) @@ -3600,7 +3796,7 @@ class AsyncQueryBase(object): mode and for legacy blob columns. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - LanceDB Distributed blob queries support only ``"descriptions"`` until a + LanceDB Enterprise blob queries support only ``"descriptions"`` until a stable table snapshot can bind the query and blob fetches. **kwargs @@ -3770,9 +3966,9 @@ class AsyncQueryBase(object): ------- list[LanceModel] """ - return [ - model(**row) for row in (await self.to_arrow(timeout=timeout)).to_pylist() - ] + return _rows_to_models( + model, (await self.to_arrow(timeout=timeout)).to_pylist() + ) async def explain_plan(self, verbose: Optional[bool] = False): """Return the execution plan for this query. @@ -4249,7 +4445,7 @@ class AsyncVectorQueryBase: you the desired recall. LanceDB retains this as `nprobes` through LanceDB Embedded and LanceDB - Distributed request construction. Lance sets both probe bounds to this + Enterprise request construction. Lance sets both probe bounds to this value. Explicit minimum or maximum settings can override their respective bounds. """ @@ -4259,6 +4455,11 @@ class AsyncVectorQueryBase: def search_effort(self, search_effort: Optional[float]) -> Self: """Set the initial IVF search effort to a finite value in [0, 1]. + Efforts 0.1 and 0.25 target empirical mean partition-routing recall of + 80% and 90% for L2, cosine and dot through k=100000. The probe budget + adapts to the metric and k. Hamming and larger k remain uncalibrated; + 100000 is not an API limit. Remote queries also require server support. + None preserves Auto (internally 0.5) and fixed nprobes. Any explicit effort, including 0.5, overrides nprobes in either call order; explicit minimum and maximum bounds remain effective. Zero starts at the caller @@ -4348,6 +4549,33 @@ class AsyncVectorQueryBase: self._inner.ef(ef) return self + def approx_mode(self, approx_mode: Literal["fast", "normal", "accurate"]) -> Self: + """ + Set the speed / accuracy tradeoff to use for approximate search + + This currently affects RQ-quantized indexes, such as IVF_RQ, and prefiltered + search on HNSW indexes, where "fast" enables the ACORN traversal. Other index + types ignore this setting. + + "fast" favors lower latency and may reduce recall, "normal" (the default) uses + the index's default balance, and "accurate" favors higher recall and may + increase latency. + + Examples + -------- + >>> import asyncio + >>> import lancedb + >>> async def build_query(): + ... db = await lancedb.connect_async("memory://") + ... table = await db.create_table( + ... "approx_async", [{"vector": [0.1, 0.2]}] + ... ) + ... return table.vector_search([0.1, 0.2]).approx_mode("accurate") + >>> query = asyncio.run(build_query()) + """ + self._inner.approx_mode(approx_mode) + return self + def refine_factor(self, refine_factor: int) -> Self: """ A multiplier to control how many additional rows are taken during the refine @@ -4905,6 +5133,8 @@ class BaseQueryBuilder(object): The maximum time to wait for the query to complete. If not specified, no timeout is applied. If the query does not complete within the specified time, an error will be raised. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. blob_mode: str, default "lazy" Controls blob conversion as described in :meth:`AsyncQueryBase.to_batches`. diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index d97e6526b..2cc6bf056 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -15,6 +15,7 @@ from typing import ( Dict, Iterable, List, + Literal, Optional, Sequence, Tuple, @@ -37,16 +38,18 @@ import pyarrow as pa from ..common import DATA from lancedb.listing import Listing, NamespaceListing, TableListing from ..db import DBConnection, LOOP -from ..functions import FunctionVersion, UdfDefinition +from ..functions import FunctionVersion, FunctionDefinition +from ..graph import EdgeTable, NodeTable, PropertyGraph from ..job import AsyncJob, Job from ..sql import Query as SqlQuery from ..sql import QueryDescription, QueryParameters from ..materialized_view import MaterializedView, MaterializedViewSource, SelectArg from ..secrets import EnvVarSecret, SecretInfo +from ..storage_integration import SecretReference, StorageIntegrationInfo from ..view import ViewDescription if TYPE_CHECKING: - from .._lancedb import JobInfo, Session + from .._lancedb import GpuClass, JobInfo, Session from ..embeddings import EmbeddingFunctionConfig from lance_namespace import ( LanceNamespace, @@ -101,7 +104,7 @@ def _tls_config_to_dict(config: Optional[TlsConfig]) -> Optional[dict[str, Any]] def _client_config_to_dict(config: ClientConfig) -> dict[str, Any]: if config.header_provider is not None: raise ValueError( - "Cannot serialize a LanceDB Distributed connection with a header_provider. " + "Cannot serialize a LanceDB Enterprise connection with a header_provider. " "Use static api_key/extra_headers or provide a worker-side " "connection factory instead." ) @@ -246,16 +249,16 @@ class RemoteDBConnection(DBConnection): @property def session(self) -> Optional["Session"]: - """LanceDB Distributed connections do not expose a local cache session.""" + """LanceDB Enterprise connections do not expose a local cache session.""" raise NotImplementedError( - "session is not supported by LanceDB Distributed connections" + "session is not supported by LanceDB Enterprise connections" ) @property def read_consistency_interval(self) -> Optional[timedelta]: - """LanceDB Distributed connections do not expose a read consistency interval.""" + """LanceDB Enterprise connections do not expose a read consistency interval.""" raise NotImplementedError( - "read_consistency_interval is not supported by LanceDB Distributed " + "read_consistency_interval is not supported by LanceDB Enterprise " "connections" ) @@ -664,11 +667,11 @@ class RemoteDBConnection(DBConnection): The embedding functions to store in the table schema and use to generate vectors when creating the table or adding data. storage_options: dict, optional - Not supported in LanceDB Distributed. Raises NotImplementedError. + Not supported in LanceDB Enterprise. Raises NotImplementedError. data_storage_version: str, optional - Not supported in LanceDB Distributed. Raises NotImplementedError. + Not supported in LanceDB Enterprise. Raises NotImplementedError. enable_v2_manifest_paths: bool, optional - Not supported in LanceDB Distributed. Raises NotImplementedError. + Not supported in LanceDB Enterprise. Raises NotImplementedError. Returns ------- @@ -742,7 +745,7 @@ class RemoteDBConnection(DBConnection): if value is not None: raise NotImplementedError( f"{option} is not supported for table creation in " - "LanceDB Distributed" + "LanceDB Enterprise" ) if exist_ok: if mode == "create": @@ -909,8 +912,7 @@ class RemoteDBConnection(DBConnection): def drop_all_tables(self, namespace_path: Optional[List[str]] = None): """Drop all tables from the database. - The remote API does not currently support this operation. Use - ``list_tables()`` and ``drop_table()`` to drop tables individually. + Lists the tables in the selected namespace and drops them one at a time. """ LOOP.run(self._conn.drop_all_tables(namespace_path=namespace_path)) @@ -956,10 +958,17 @@ class RemoteDBConnection(DBConnection): """ return Job(LOOP.run(self._conn.open_job(job_id))) + @override + def list_gpu_classes(self) -> List[GpuClass]: + """List configured Function GPU classes. See + [DBConnection.list_gpu_classes][lancedb.db.DBConnection.list_gpu_classes]. + """ + return LOOP.run(self._conn.list_gpu_classes()) + @override def create_function_async( self, - definition: UdfDefinition, + definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, namespace_path: Optional[List[str]] = None, @@ -1015,11 +1024,14 @@ class RemoteDBConnection(DBConnection): version: str, namespace_path: Optional[List[str]] = None, ) -> bool: - return LOOP.run( - self._conn.drop_function( + dropped, drop_warnings = LOOP.run( + self._conn._drop_function_with_warnings( name, version=version, namespace_path=namespace_path ) ) + for warning in drop_warnings: + warnings.warn(warning, UserWarning, stacklevel=2) + return dropped @override def drop_function_async( @@ -1036,6 +1048,76 @@ class RemoteDBConnection(DBConnection): ) return dropped, Job(job) + @override + def create_storage_integration( + self, + name: str, + storage_prefix: str, + *, + aws_role_arn: Optional[str] = None, + aws_access_key_id_secret: Optional[Union[str, SecretReference]] = None, + aws_secret_access_key_secret: Optional[Union[str, SecretReference]] = None, + aws_region: Optional[str] = None, + storage_provider: Literal["S3", "AZURE", "GCP", "HUGGINGFACE"] = "S3", + azure_storage_account: Optional[str] = None, + azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None, + azure_client_id_secret: Optional[Union[str, SecretReference]] = None, + azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, + gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, + huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + namespace_path: Optional[List[str]] = None, + ) -> StorageIntegrationInfo: + return LOOP.run( + self._conn.create_storage_integration( + name, + storage_prefix, + aws_role_arn=aws_role_arn, + aws_access_key_id_secret=aws_access_key_id_secret, + aws_secret_access_key_secret=aws_secret_access_key_secret, + aws_region=aws_region, + storage_provider=storage_provider, + azure_storage_account=azure_storage_account, + azure_tenant_id_secret=azure_tenant_id_secret, + azure_client_id_secret=azure_client_id_secret, + azure_client_secret_secret=azure_client_secret_secret, + gcp_credentials_json_secret=gcp_credentials_json_secret, + huggingface_token_secret=huggingface_token_secret, + namespace_path=namespace_path, + ) + ) + + @override + def describe_storage_integration( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> StorageIntegrationInfo: + return LOOP.run( + self._conn.describe_storage_integration(name, namespace_path=namespace_path) + ) + + @override + def list_storage_integrations( + self, + *, + namespace_path: Optional[List[str]] = None, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + ) -> Listing[str]: + return Listing( + self._conn.list_storage_integrations( + namespace_path=namespace_path, + page_token=page_token, + page_limit=page_limit, + ) + ) + + @override + def drop_storage_integration( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> None: + LOOP.run( + self._conn.drop_storage_integration(name, namespace_path=namespace_path) + ) + @override def create_secret( self, name: str, value: str, *, namespace_path: Optional[List[str]] = None @@ -1131,6 +1213,61 @@ class RemoteDBConnection(DBConnection): ) ) + @override + def create_property_graph( + self, + name: str, + nodes: Sequence[NodeTable], + edges: Sequence[EdgeTable] = (), + *, + namespace_path: Optional[List[str]] = None, + ) -> PropertyGraph: + return PropertyGraph( + LOOP.run( + self._conn.create_property_graph( + name, nodes, edges, namespace_path=namespace_path + ) + ) + ) + + @override + def open_property_graph( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> PropertyGraph: + return PropertyGraph( + LOOP.run( + self._conn.open_property_graph(name, namespace_path=namespace_path) + ) + ) + + @override + def drop_property_graph( + self, name: str, *, namespace_path: Optional[List[str]] = None + ) -> None: + LOOP.run(self._conn.drop_property_graph(name, namespace_path=namespace_path)) + + @override + def list_property_graphs( + self, + *, + namespace_path: Optional[List[str]] = None, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + ) -> Listing[str]: + """List property graphs. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total; + ``page_token`` resumes from a saved token. Requests and errors occur during + iteration. See [pagination state][lancedb.listing.AsyncListing]. + """ + return Listing( + self._conn.list_property_graphs( + namespace_path=namespace_path, + page_token=page_token, + page_limit=page_limit, + ) + ) + @override def list_jobs( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None @@ -1179,7 +1316,7 @@ class RemoteDBConnection(DBConnection): default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, ) -> SqlQuery: - """Start executing SQL through this LanceDB Distributed connection. + """Start executing SQL through this LanceDB Enterprise connection. Unqualified tables use this connection's database and the ``["public"]`` namespace by default. Fully qualified table names may diff --git a/python/python/lancedb/remote/errors.py b/python/python/lancedb/remote/errors.py index 5aa13a9c7..ee92ddf53 100644 --- a/python/python/lancedb/remote/errors.py +++ b/python/python/lancedb/remote/errors.py @@ -4,6 +4,14 @@ from typing import Optional +from lance_namespace.errors import TableNotFoundError as _NamespaceTableNotFoundError + +from lancedb.exceptions import ( + ColumnNotFoundError as _ColumnNotFoundError, + ReferenceNotFoundError as _ReferenceNotFoundError, + SchemaMismatchError as _SchemaMismatchError, +) + class LanceDBClientError(RuntimeError): """An error that occurred in the LanceDB client. @@ -44,6 +52,313 @@ class HttpError(LanceDBClientError): status_code: int The HTTP status code of the response. May be None if the request failed before the response was received. + error_code: str + A machine-readable error code reported by the server, if available. + resource_kind: str + The kind of resource reported by the server, if available. + resource_name: str + The name of the resource reported by the server, if available. + namespace_path: tuple[str, ...] + The parent namespace path of the resource, if available. + is_transport_error: bool + Whether the request failed while connecting, sending, or reading, rather + than because of an HTTP status or an invalid response payload. + job_id: str or None + SQL job reported by the server, when available. + job_request_id: str or None + Original request executed by the isolated SQL worker, when available. + """ + + def __new__( + cls, + message: str, + request_id: str, + status_code: Optional[int] = None, + error_code: Optional[str] = None, + resource_kind: Optional[str] = None, + resource_name: Optional[str] = None, + namespace_path: Optional[tuple[str, ...]] = None, + is_transport_error: bool = False, + job_id: Optional[str] = None, + job_request_id: Optional[str] = None, + ): + if cls is HttpError: + mapped_cls = _http_error_class(error_code, resource_kind, status_code) + if mapped_cls is not None: + cls = mapped_cls + return RuntimeError.__new__(cls) + + def __init__( + self, + message: str, + request_id: str, + status_code: Optional[int] = None, + error_code: Optional[str] = None, + resource_kind: Optional[str] = None, + resource_name: Optional[str] = None, + namespace_path: Optional[tuple[str, ...]] = None, + is_transport_error: bool = False, + job_id: Optional[str] = None, + job_request_id: Optional[str] = None, + ): + super().__init__(message, request_id, status_code) + self.is_transport_error = is_transport_error + self.job_id = job_id + self.job_request_id = job_request_id + self.error_code = error_code + self.resource_kind = resource_kind + self.resource_name = resource_name + self.namespace_path = ( + tuple(namespace_path) if namespace_path is not None else None + ) + + def __reduce__(self) -> tuple[type, tuple]: + return ( + self.__class__, + ( + str(self), + self.request_id, + self.status_code, + self.error_code, + self.resource_kind, + self.resource_name, + self.namespace_path, + self.is_transport_error, + self.job_id, + self.job_request_id, + ), + ) + + +def _http_error_class( + error_code: Optional[str], resource_kind: Optional[str], status_code: Optional[int] +) -> Optional[type[HttpError]]: + if status_code == 400 and error_code is not None: + input_class = { + "column_not_found": ColumnNotFoundError, + "schema_mismatch": SchemaMismatchError, + }.get(error_code) + if input_class is not None: + return input_class + if status_code == 404 and error_code is not None: + input_class = { + "table_not_found": TableNotFoundError, + "reference_not_found": ReferenceNotFoundError, + }.get(error_code) + if input_class is not None: + return input_class + if error_code == "already_exists": + return AlreadyExistsError + if status_code == 409: + return ConflictError + if error_code != "not_found" or resource_kind is None: + return None + return { + "secret": SecretNotFoundError, + "function": FunctionNotFoundError, + "namespace": NamespaceNotFoundError, + }.get(resource_kind) + + +class ColumnNotFoundError(HttpError, _ColumnNotFoundError): + """A remote HTTP request named a missing table column.""" + + +class ReferenceNotFoundError(HttpError, _ReferenceNotFoundError): + """A remote HTTP request named a missing branch or table reference.""" + + +class SchemaMismatchError(HttpError, _SchemaMismatchError): + """Input to a remote HTTP request does not match the table schema.""" + + +class SqlError(LanceDBClientError): + """A SQL response with its gRPC status and correlation fields. + + ``grpc_code`` is the numeric gRPC code. ``error_code`` is an optional + machine-readable classification supplied by the server; message text is + never used to choose a subclass. ``job_id`` and ``job_request_id`` are absent + unless the server reports an isolated SQL job. ``request_id`` identifies the + current request. Older servers still produce SqlError without a category. + + Examples + -------- + >>> error = SqlError("Column 'missing' was not found", "req-1", 3, + ... "column_not_found", "job-1", "worker-1") + >>> isinstance(error, SqlColumnNotFoundError) + True + >>> error.job_request_id + 'worker-1' + """ + + def __new__( + cls, + message: str, + request_id: str, + grpc_code: int, + error_code: Optional[str] = None, + job_id: Optional[str] = None, + job_request_id: Optional[str] = None, + ): + if cls is SqlError and error_code is not None: + cls = { + (3, "column_not_found"): SqlColumnNotFoundError, + (3, "schema_mismatch"): SqlSchemaMismatchError, + (5, "table_not_found"): SqlTableNotFoundError, + (5, "reference_not_found"): SqlReferenceNotFoundError, + }.get((grpc_code, error_code), cls) + return RuntimeError.__new__(cls) + + def __init__( + self, + message: str, + request_id: str, + grpc_code: int, + error_code: Optional[str] = None, + job_id: Optional[str] = None, + job_request_id: Optional[str] = None, + ): + super().__init__(message, request_id) + self.grpc_code = grpc_code + self.error_code = error_code + self.job_id = job_id + self.job_request_id = job_request_id + + def __reduce__(self): + return ( + self.__class__, + ( + str(self), + self.request_id, + self.grpc_code, + self.error_code, + self.job_id, + self.job_request_id, + ), + ) + + +class SqlColumnNotFoundError(SqlError, _ColumnNotFoundError): + """A SQL request named a missing column.""" + + +class SqlReferenceNotFoundError(SqlError, _ReferenceNotFoundError): + """A SQL request named a missing branch or table reference.""" + + +class SqlSchemaMismatchError(SqlError, _SchemaMismatchError): + """SQL input does not match the table schema.""" + + +class SqlTableNotFoundError(SqlError, ValueError, _NamespaceTableNotFoundError): + """A SQL request named a missing table.""" + + +class SecretNotFoundError(HttpError): + """A remote secret was not found.""" + + +class FunctionNotFoundError(HttpError): + """A remote function was not found.""" + + +class NamespaceNotFoundError(HttpError): + """A remote namespace was not found.""" + + +class AlreadyExistsError(HttpError): + """A remote resource already exists.""" + + +class ConflictError(HttpError): + """A remote operation conflicts with the current state of a resource. + + For example, deleting a branch whose files are still needed by another + branch raises this error. The server's reason is included in the message. + + Examples + -------- + >>> error = HttpError("main depends on the branch's files", "req-1", 409) + >>> isinstance(error, ConflictError) + True + >>> error.status_code + 409 + """ + + +class ResponseInterruptedError(HttpError): + """A streamed query response stopped before the server finished sending it. + + The batches already returned are valid, but the result is incomplete. The + query is not retried automatically, because a new attempt would return those + rows a second time. To read the same data in a new attempt, check out + ``table_version`` first. + + Attributes + ---------- + batches: int + The number of batches returned before the interruption. + rows: int + The number of rows in those batches. + table_version: int or None + The table version the response reflected, if the server reported it. + + Examples + -------- + >>> error = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7) + >>> isinstance(error, HttpError) + True + >>> (error.rows, error.table_version) + (2048, 7) + """ + + # HttpError.__new__ takes HttpError's arguments, to choose a subclass. + def __new__(cls, *args, **kwargs): + return RuntimeError.__new__(cls) + + def __init__( + self, + message: str, + request_id: str, + batches: int, + rows: int, + table_version: Optional[int] = None, + is_transport_error: bool = False, + ): + super().__init__(message, request_id, is_transport_error=is_transport_error) + self.batches = batches + self.rows = rows + self.table_version = table_version + + def __reduce__(self) -> tuple[type, tuple]: + return ( + self.__class__, + ( + str(self), + self.request_id, + self.batches, + self.rows, + self.table_version, + self.is_transport_error, + ), + ) + + +class TableNotFoundError(HttpError, ValueError, _NamespaceTableNotFoundError): + """A remote table was not found. + + This is also a ``lance_namespace.errors.TableNotFoundError`` and a + ``ValueError``, so existing missing-table handlers continue to work. + Like [HttpError][lancedb.remote.errors.HttpError], it carries the + ``request_id`` and ``status_code`` of the failed request. + + Examples + -------- + >>> error = TableNotFoundError("Table 'missing' was not found", "req-123", 404) + >>> isinstance(error, ValueError) + True + >>> error.request_id + 'req-123' """ pass diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 7454b3e73..8f1f741fb 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1,6 +1,9 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +from __future__ import annotations + +from collections.abc import Mapping from datetime import timedelta import deprecation import logging @@ -45,7 +48,11 @@ from lancedb.index import ( LabelList, ) from lancedb.job import Job -from lancedb.functions import FunctionApplication, RefreshColumnResult +from lancedb.functions import ( + FunctionApplication, + FunctionRetryPolicy, + RefreshColumnResult, +) from lancedb.remote.db import LOOP from lancedb.table import IndexConfigType, _maybe_add_fts_error_note import pyarrow as pa @@ -126,7 +133,7 @@ class RemoteTable(Table): def _serialized_connection_state(self) -> str: if self._connection_state is None: raise RuntimeError( - "Cannot reopen this LanceDB Distributed table because it does not " + "Cannot reopen this LanceDB Enterprise table because it does not " "carry serialized connection state" ) if callable(self._connection_state): @@ -206,7 +213,8 @@ class RemoteTable(Table): LOOP.run(self._table.replace_field_metadata(field_name, new_metadata)) def __repr__(self) -> str: - return f"RemoteTable({self.db_name}.{self.name})" + identifier = "$".join([*self._namespace_path, self.name]) + return f"RemoteTable({self.db_name}.{identifier})" @property def schema(self) -> pa.Schema: @@ -273,23 +281,23 @@ class RemoteTable(Table): return LOOP.run(self._table.list_versions()) def to_arrow(self, *, blob_mode: BlobMode = "lazy") -> pa.Table: - """to_arrow() is not supported in LanceDB Distributed.""" + """to_arrow() is not supported in LanceDB Enterprise.""" validate_blob_mode(blob_mode) raise NotImplementedError( - "to_arrow() is not supported in LanceDB Distributed. " + "to_arrow() is not supported in LanceDB Enterprise. " "Use table.search().to_arrow() instead." ) def to_pandas(self, blob_mode: BlobMode = "lazy", **kwargs): - """to_pandas() is not supported in LanceDB Distributed.""" + """to_pandas() is not supported in LanceDB Enterprise.""" validate_blob_mode(blob_mode) raise NotImplementedError( - "to_pandas() is not supported in LanceDB Distributed. " + "to_pandas() is not supported in LanceDB Enterprise. " "Use table.search().to_pandas() instead." ) def to_lance(self, **kwargs) -> "lance.LanceDataset": - """Direct Lance dataset access is not supported in LanceDB Distributed. + """Direct Lance dataset access is not supported in LanceDB Enterprise. Use ``table.search().to_arrow()`` to read query results through the server. """ @@ -298,7 +306,7 @@ class RemoteTable(Table): def to_polars(self, batch_size=None) -> "pl.LazyFrame": """Use ``table.search().to_polars()`` to read query results.""" raise NotImplementedError( - "to_polars() is not supported in LanceDB Distributed. " + "to_polars() is not supported in LanceDB Enterprise. " "Use table.search().to_polars() instead." ) @@ -331,7 +339,7 @@ class RemoteTable(Table): """Tokenize a query using the tokenizer configured on an FTS index. Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are - rebuilt in the client process from index metadata. In LanceDB Distributed, + rebuilt in the client process from index metadata. In LanceDB Enterprise, this means the same tokenizer model files must also exist locally (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the server uses. A mismatch cannot be detected: the returned tokens may @@ -638,7 +646,7 @@ class RemoteTable(Table): if accelerator is not None: logging.warning( - "GPU accelerator is not supported in LanceDB Distributed " + "GPU accelerator is not supported in LanceDB Enterprise " "and will be ignored." ) @@ -743,7 +751,7 @@ class RemoteTable(Table): capped at the number of CPU cores. Lower this if bulk ingestion is using too much memory. allow_external_blob_outside_bases: bool, default False - Not supported in LanceDB Distributed. Setting this raises. + Not supported in LanceDB Enterprise. Setting this raises. Returns ------- @@ -992,6 +1000,11 @@ class RemoteTable(Table): This can be used to update zero to all rows depending on how many rows match the where clause. + Embeddings are not computed by this method. Updating an embedding source + column requires providing all associated vector columns in the same call; + otherwise a ValueError is raised. Use `merge_insert` to recompute embeddings + automatically. + Parameters ---------- where: str or [Expr][lancedb.expr.Expr], optional @@ -1048,20 +1061,20 @@ class RemoteTable(Table): delete_unverified: bool = False, ): """ - cleanup_old_versions() is a no-op in LanceDB Distributed. + cleanup_old_versions() is a no-op in LanceDB Enterprise. """ warnings.warn( - "cleanup_old_versions() is a no-op in LanceDB Distributed.", + "cleanup_old_versions() is a no-op in LanceDB Enterprise.", stacklevel=2, ) pass def compact_files(self, *args, **kwargs): """ - compact_files() is a no-op in LanceDB Distributed. + compact_files() is a no-op in LanceDB Enterprise. """ warnings.warn( - "compact_files() is a no-op in LanceDB Distributed.", + "compact_files() is a no-op in LanceDB Enterprise.", stacklevel=2, ) pass @@ -1074,12 +1087,24 @@ class RemoteTable(Table): retrain: bool = False, compaction_options: Optional[CompactionOptions] = None, ): - """optimize() is not supported in LanceDB Distributed.""" + """Compact the table's data files via a durable, asynchronous + Enterprise job. Pruning old versions and index optimization are not + yet supported remotely, so this call skips them and returns + successfully with zeroed pruning statistics once the compaction job + has been submitted; it does not wait for that job to finish. The + per-job options ``target_rows_per_fragment``, ``max_source_rows``, + ``io_buffer_size``, and ``batch_size`` are supported on compatible + servers. Omitted fields inherit table tuning, then deployment/built-in + defaults. Other non-default settings raise ``NotImplementedError`` + before submission. Errors from older servers are propagated without + retrying with the settings removed. + """ return LOOP.run( self._table.optimize( cleanup_older_than=cleanup_older_than, delete_unverified=delete_unverified, retrain=retrain, + compaction_options=compaction_options, ) ) @@ -1088,11 +1113,15 @@ class RemoteTable(Table): def add_columns( self, - transforms: Dict[str, str | FunctionApplication] + transforms: Mapping[str, str | FunctionApplication] | FunctionApplication | pa.Field | List[pa.Field] | pa.Schema + | DATA + | pa.RecordBatch + | pa.RecordBatchReader + | pl.DataFrame | None = None, *, computed: Dict[str, str] | None = None, @@ -1108,11 +1137,77 @@ class RemoteTable(Table): ) ) - def refresh_column(self, column: str): - return LOOP.run(self._table.refresh_column(column)) + def refresh_column( + self, + column: str, + *, + where: Optional[str] = None, + batch_size: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, + ): + return LOOP.run( + self._table.refresh_column( + column, + where=where, + batch_size=batch_size, + gpu_class=gpu_class, + gpu_count=gpu_count, + retry_policy=retry_policy, + error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, + ) + ) - def refresh_column_async(self, column: str) -> Job[RefreshColumnResult]: - return Job(LOOP.run(self._table.refresh_column_async(column))) + def refresh_column_async( + self, + column: str, + *, + where: Optional[str] = None, + batch_size: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, + ) -> Job[RefreshColumnResult]: + return Job( + LOOP.run( + self._table.refresh_column_async( + column, + where=where, + batch_size=batch_size, + gpu_class=gpu_class, + gpu_count=gpu_count, + retry_policy=retry_policy, + error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, + ) + ) + ) def function_errors( self, @@ -1153,6 +1248,18 @@ class RemoteTable(Table): """Read the installed RTEWriteSpec, or ``None``.""" return LOOP.run(self._table.get_rte_spec()) + def get_table_overrides(self) -> dict[str, Any]: + """Read Enterprise table overrides for this 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.""" + return LOOP.run(self._table.update_table_overrides(**overrides)) + + def reset_table_overrides(self) -> dict[str, Any]: + """Clear Enterprise table overrides for this table.""" + return LOOP.run(self._table.reset_table_overrides()) + # WAL-PK-FUSION: delete both hooks. def _hybrid_pk_fusion_learned(self) -> bool: # `self._table` is the async table, which owns the Rust handle. @@ -1184,7 +1291,7 @@ class RemoteTable(Table): ) def close_rte_writers(self) -> None: - """No-op in LanceDB Distributed (no local shard writers).""" + """No-op in LanceDB Enterprise (no local shard writers).""" return LOOP.run(self._table.close_rte_writers()) @_deprecated_keyword("index_name", "name") @@ -1213,7 +1320,7 @@ class RemoteTable(Table): This is a hint to the database that the given columns will be accessed in the future and the database should prefetch the data if possible. - Currently only supported in LanceDB Distributed. + 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. @@ -1242,7 +1349,7 @@ class RemoteTable(Table): def uri(self) -> str: """The table URI (storage location). - In LanceDB Distributed, this fetches the location from the server via describe. + In LanceDB Enterprise, this fetches the location from the server via describe. """ return LOOP.run(self._table.uri()) diff --git a/python/python/lancedb/rerankers/base.py b/python/python/lancedb/rerankers/base.py index e1bc7f0dd..966f23eeb 100644 --- a/python/python/lancedb/rerankers/base.py +++ b/python/python/lancedb/rerankers/base.py @@ -189,6 +189,8 @@ class Reranker(ABC): vector_results = ( [vector_results] if not isinstance(vector_results, list) else vector_results ) + if not vector_results: + raise ValueError("vector_results must not be empty") # Make sure all elements are of the same type if not all(isinstance(v, type(vector_results[0])) for v in vector_results): diff --git a/python/python/lancedb/rerankers/linear_combination.py b/python/python/lancedb/rerankers/linear_combination.py index 74f23ea61..682aac9e2 100644 --- a/python/python/lancedb/rerankers/linear_combination.py +++ b/python/python/lancedb/rerankers/linear_combination.py @@ -3,7 +3,6 @@ from collections import defaultdict -from numpy import nan import pyarrow as pa from .base import Reranker @@ -66,7 +65,7 @@ class LinearCombinationReranker(Reranker): elif self.score == "all": results = results.append_column( "_distance", - pa.array([nan] * len(fts_results), type=pa.float32()), + pa.nulls(len(fts_results), type=pa.float32()), ) return results @@ -87,7 +86,7 @@ class LinearCombinationReranker(Reranker): elif self.score == "all": results = results.append_column( "_score", - pa.array([nan] * len(vector_results), type=pa.float32()), + pa.nulls(len(vector_results), type=pa.float32()), ) return results results = defaultdict() diff --git a/python/python/lancedb/secrets.py b/python/python/lancedb/secrets.py index 75ac9e340..ebafadbc5 100644 --- a/python/python/lancedb/secrets.py +++ b/python/python/lancedb/secrets.py @@ -72,7 +72,7 @@ class EnvVarSecret: Pass these in the ``secrets`` sequence of [DBConnection.create_function][lancedb.db.DBConnection.create_function]. The - Function's source is unchanged by binding: it reads ``OPENAI_API_KEY`` the + Function's source is unchanged by binding: it reads ``MODEL_API_KEY`` the way it always did, and the binding is what puts a value there. This is a local value. Constructing it contacts no server, so it always @@ -101,10 +101,10 @@ class EnvVarSecret: -------- >>> from lancedb import EnvVarSecret >>> binding = EnvVarSecret( - ... secret_name="openai-prod", env_variable="OPENAI_API_KEY" + ... secret_name="model-api-key", env_variable="MODEL_API_KEY" ... ) >>> binding.secret_name, binding.env_variable - ('openai-prod', 'OPENAI_API_KEY') + ('model-api-key', 'MODEL_API_KEY') """ __slots__ = ("_secret_name", "_env_variable", "_secret_namespace_path") diff --git a/python/python/lancedb/sql.py b/python/python/lancedb/sql.py index d011e25a5..7498cddcc 100644 --- a/python/python/lancedb/sql.py +++ b/python/python/lancedb/sql.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Handles to SQL queries running on a LanceDB Distributed database.""" +"""Handles to SQL queries running on a LanceDB Enterprise database.""" from typing import Any, Mapping, Optional, Sequence, Union from uuid import UUID diff --git a/python/python/lancedb/storage_integration.py b/python/python/lancedb/storage_integration.py new file mode 100644 index 000000000..a9dda088b --- /dev/null +++ b/python/python/lancedb/storage_integration.py @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Database-owned storage integrations and references to credential Secrets.""" + +from dataclasses import dataclass +from typing import Any, Dict, Literal, Optional + + +@dataclass(frozen=True) +class SecretReference: + """A credential Secret, optionally qualified by database and namespace.""" + + name: str + database: Optional[str] = None + namespace_path: tuple[str, ...] = () + + +@dataclass(frozen=True) +class StorageIntegrationInfo: + """Registered cloud configuration and setup instructions. + + ``configuration_instructions`` is a single sentence of setup guidance for + display; its wording may change. Use the structured identity and policy fields + instead of parsing that text. Creating this object does not verify AWS access + or configure a storage operation to use it. Static-key authentication stores + only Secret references. No field contains AWS credentials. + """ + + name: str + database: str + namespace_path: list[str] + storage_provider: Literal["S3", "AZURE", "GCP", "HUGGINGFACE"] + storage_prefix: str + aws_region: Optional[str] + aws_account_id: str + aws_iam_principal_arn: str + aws_external_id: str + created_at_millis: int + access_verified: bool + trust_policy: Optional[Dict[str, Any]] + permissions_policy: Optional[Dict[str, Any]] + configuration_instructions: str + aws_role_arn: Optional[str] = None + aws_access_key_id_secret: Optional[SecretReference] = None + aws_secret_access_key_secret: Optional[SecretReference] = None + azure_storage_account: Optional[str] = None + azure_tenant_id_secret: Optional[SecretReference] = None + azure_client_id_secret: Optional[SecretReference] = None + azure_client_secret_secret: Optional[SecretReference] = None + gcp_credentials_json_secret: Optional[SecretReference] = None + huggingface_token_secret: Optional[SecretReference] = None + + def __post_init__(self): + for field in ( + "aws_access_key_id_secret", + "aws_secret_access_key_secret", + "azure_tenant_id_secret", + "azure_client_id_secret", + "azure_client_secret_secret", + "gcp_credentials_json_secret", + "huggingface_token_secret", + ): + value = getattr(self, field) + if isinstance(value, dict): + object.__setattr__(self, field, SecretReference(**value)) diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index db71840c6..810911e28 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -13,7 +13,7 @@ Provides StreamingDataset, a PyTorch IterableDataset that guarantees: distributed topology changes between runs. Transform failures on bad rows (e.g. nulls or NaNs from incomplete data) can -be tolerated with ``on_transform_error="skip"``; see the parameter +be tolerated with ``on_transform_error="skip"`` or ``"fill"``; see the parameter documentation on StreamingDataset for how this interacts with the guarantees above. """ @@ -30,7 +30,7 @@ import warnings from collections import deque from concurrent.futures import ThreadPoolExecutor from copy import deepcopy -from multiprocessing import RawArray +from multiprocessing import RawArray, get_context from typing import Any, Callable, cast, Iterator, Literal, NamedTuple, Optional, Union import pyarrow as pa @@ -57,6 +57,7 @@ _EPOCH_PRIME = 100003 DEFAULT_READ_BATCH_SIZE = 64 DEFAULT_PREFETCH_BATCHES = 4 +_UNSET = object() class _WorkerSample(NamedTuple): @@ -350,6 +351,10 @@ class StreamingDataset(IterableDataset): - ``"skip"``: the failing rows are dropped and iteration continues. - ``"warn"``: like ``"skip"``, but a warning is logged for each failing batch. + - ``"fill"``: replace each failing row with ``fill_value`` or the + result of ``repair(exc, row_batch)``. Exactly one of these must be + provided. Filled rows retain their original positions, so split + lengths, elastic determinism, and checkpoint offsets are preserved. - a callable ``handler(exc) -> bool``: called with the exception; return ``True`` to skip the failing rows or ``False`` to re-raise. Useful to skip only expected error types (compatible with @@ -357,9 +362,9 @@ class StreamingDataset(IterableDataset): When a batch fails, the transform is re-invoked on each single-row slice of the batch so that only the rows that actually fail are - dropped. Transforms should therefore be deterministic and accept - batches of any size (including one row). Skipped rows are counted in - ``rows_skipped``. + skipped or filled. Transforms should therefore be deterministic and + accept batches of any size (including one row). Skipped and filled + rows are counted in ``rows_skipped`` and ``rows_filled`` respectively. Skipping weakens the elastic-determinism guarantee at the end of the epoch: splits that lose more rows than others run dry earlier, and @@ -372,8 +377,9 @@ class StreamingDataset(IterableDataset): but synchronous distributed training (e.g. ranks that call ``all_reduce`` every step) can hang or deadlock if one rank's iterator is exhausted while others are still stepping; callers doing - synchronous multi-rank training with ``on_transform_error != "raise"`` - are responsible for their own cross-rank stopping mechanism (e.g. + synchronous multi-rank training with ``on_transform_error="skip"`` or + ``"warn"`` (or a skipping callable) are responsible for their own + cross-rank stopping mechanism (e.g. broadcasting a stop signal on ``StopIteration``). The final few global steps can also differ across topologies (bounded by the skew in bad-row counts across splits). The sequence of samples yielded @@ -385,6 +391,18 @@ class StreamingDataset(IterableDataset): Prefer the ``filter`` parameter when bad rows can be expressed as a SQL predicate (e.g. ``"col IS NOT NULL"``) — filtering happens before splits are built, so every guarantee is fully preserved. + fill_value: + Constant output row used with ``on_transform_error="fill"``. A copy + is made for each failed row so mutable placeholders are independent. + For example, ``fill_value={"vector": [0.0, 0.0]}``. Pass exactly one + of ``fill_value`` or ``repair`` in fill mode. + repair: + Optional function ``repair(exc, row_batch) -> row`` used with + ``on_transform_error="fill"``. ``row_batch`` is a one-row + ``pyarrow.RecordBatch``. The returned value replaces that row's + transformed output. Replacements should have the same structure as + successful transform outputs. The repair must be deterministic for + reproducible checkpoints and elastic steps. transform_queue_depth: Number of transform-result batches to buffer per split in the post-transform queue before backpressure is applied to the transform @@ -438,6 +456,8 @@ class StreamingDataset(IterableDataset): pad_id: Optional[int] = None, blocks_per_epoch: Optional[Union[int, Literal["auto"]]] = None, on_transform_error: Union[str, Callable[[Exception], bool]] = "raise", + fill_value: Any = _UNSET, + repair: Optional[Callable[[Exception, pa.RecordBatch], Any]] = None, transform_queue_depth: Optional[int] = None, connection_factory: Optional[Callable[[str], Any]] = None, worker_info_override=None, @@ -513,13 +533,20 @@ class StreamingDataset(IterableDataset): ) elif blocks_per_epoch is not None: raise ValueError("blocks_per_epoch requires pack_sequences") - if on_transform_error not in ("raise", "skip", "warn") and not callable( + if on_transform_error not in ("raise", "skip", "warn", "fill") and not callable( on_transform_error ): raise ValueError( - "on_transform_error must be 'raise', 'skip', 'warn', or a " + "on_transform_error must be 'raise', 'skip', 'warn', 'fill', or a " f"callable, got {on_transform_error!r}" ) + if on_transform_error == "fill": + if (fill_value is _UNSET) == (repair is None): + raise ValueError( + "fill mode requires exactly one of fill_value or repair" + ) + elif fill_value is not _UNSET or repair is not None: + raise ValueError("fill_value and repair require on_transform_error='fill'") if transform_queue_depth is not None and transform_queue_depth <= 0: raise ValueError("transform_queue_depth must be greater than 0") @@ -542,6 +569,8 @@ class StreamingDataset(IterableDataset): self._pad_id = pad_id self._blocks_per_epoch = blocks_per_epoch self._on_transform_error = on_transform_error + self._fill_value = None if fill_value is _UNSET else fill_value + self._repair = repair self._transform_queue_depth = transform_queue_depth self._connection_factory = connection_factory self._worker_info_override = worker_info_override @@ -568,6 +597,9 @@ class StreamingDataset(IterableDataset): # bytes_loaded, fetch_time_us, transform_time_us, # rows_skipped] self._worker_stats: RawArray = RawArray(ctypes.c_int64, 8) + # A locked shared counter keeps fills from separate DataLoader workers + # from overwriting one another's totals. + self._filled_count = get_context("spawn").Value(ctypes.c_int64, 0) # A standard multi-process DataLoader cannot report which prefetched # batches were actually returned to its consumer. Workers set this @@ -951,12 +983,12 @@ class StreamingDataset(IterableDataset): on_error = self._on_transform_error - def _should_skip(exc: Exception) -> bool: + def _should_continue(exc: Exception) -> bool: if on_error == "raise": return False if callable(on_error): return bool(on_error(exc)) - return True # "skip" or "warn" + return True # "skip", "warn", or "fill" def _check_row_count(rows: list, num_rows: int) -> None: if len(rows) != num_rows: @@ -968,16 +1000,27 @@ class StreamingDataset(IterableDataset): ) def _transform_isolated(abs_start, batch, batch_exc): - """Re-run the transform on single-row slices, dropping failures.""" + """Re-run the transform on single-row slices to isolate failures.""" out = [] skipped = 0 + filled = 0 first_exc = None for j in range(batch.num_rows): + row_batch = batch.slice(j, 1) try: - rows = list(final_transform(batch.slice(j, 1))) + rows = list(final_transform(row_batch)) except Exception as exc: - if not _should_skip(exc): + if not _should_continue(exc): raise + if on_error == "fill": + row = ( + self._repair(exc, row_batch) + if self._repair is not None + else deepcopy(self._fill_value) + ) + out.append((abs_start + j, row)) + filled += 1 + continue skipped += 1 if first_exc is None: first_exc = exc @@ -985,6 +1028,9 @@ class StreamingDataset(IterableDataset): _check_row_count(rows, 1) out.append((abs_start + j, rows[0])) self._rows_skipped += skipped + if filled: + with self._filled_count.get_lock(): + self._filled_count.value += filled if skipped and on_error == "warn": logger.warning( "Skipped %d of %d rows whose transform failed (first error: %r)", @@ -999,7 +1045,7 @@ class StreamingDataset(IterableDataset): try: rows = list(final_transform(batch)) except Exception as exc: - if not _should_skip(exc): + if not _should_continue(exc): raise return _transform_isolated(abs_start, batch, exc) _check_row_count(rows, batch.num_rows) @@ -1370,6 +1416,15 @@ class StreamingDataset(IterableDataset): return self._rows_skipped return int(self._worker_stats[7]) + @property + def rows_filled(self) -> int: + """Number of failed transform rows replaced by fill mode. + + Accumulates across iterations of the same dataset instance and is + never reset automatically. + """ + return int(self._filled_count.value) + @property def consumed_rows(self) -> int: """Number of rows already yielded to the caller across all splits. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index b68f15912..75975a2c3 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -9,6 +9,7 @@ import json import deprecation import warnings from abc import ABC, abstractmethod +from collections.abc import Mapping from dataclasses import dataclass from datetime import datetime, timedelta from functools import cached_property @@ -34,6 +35,7 @@ from urllib.parse import urlparse from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable from . import __version__ +from ._lancedb import _parse_field_path from ._blob import ( BlobFile, _normalize_blob_descriptor, @@ -62,6 +64,7 @@ import numpy as np from .common import DATA, VEC, VECTOR_COLUMN_NAME from .embeddings import EmbeddingFunctionConfig, EmbeddingFunctionRegistry +from .embeddings.registry import _embedding_column_pairs from .index import ( BTree, IvfFlat, @@ -71,6 +74,7 @@ from .index import ( IvfRq, LabelList, Fm, + NGram, HnswPq, HnswSq, HnswFlat, @@ -78,6 +82,7 @@ from .index import ( ) from .expr import Expr from .functions import ( + FunctionRetryPolicy, FunctionApplication, RefreshColumnResult as RefreshColumnJobResult, ) @@ -124,6 +129,16 @@ def _should_push_down_query_table( return namespace_client is not None and "QueryTable" in pushdown_operations +def _requires_local_namespace_execution(query: Query) -> bool: + # The namespace QueryTable request does not support these query options. + return ( + query.take_offsets is not None + or query.take_row_ids is not None + or query.search_effort is not None + or query.approx_mode is not None + ) + + _CUDA_UNAVAILABLE_MESSAGE = ( "CUDA acceleration is unavailable in this Python environment. Install a " "CUDA-enabled PyTorch build and verify that the CUDA device is accessible, or " @@ -284,6 +299,7 @@ IndexConfigType = Union[ Bitmap, LabelList, Fm, + NGram, FTS, ] @@ -291,7 +307,12 @@ IndexConfigType = Union[ class CompactionOptions(TypedDict, total=False): """Options that control file compaction during table optimization. - Unspecified options use Lance's defaults. + Unspecified options use Lance's defaults for local tables. Remote tables + forward ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``, + and ``batch_size`` as per-job SQL options; other non-default settings are + unsupported. Omitted remote options inherit table tuning, then deployment/built-in + defaults. The server must support these SQL options. These settings do not + change table policy. Compaction planning is row based. Lowering ``target_rows_per_fragment`` based on the expected row size can bound later compaction passes once @@ -337,7 +358,10 @@ class CompactionOptions(TypedDict, total=False): """Number of rows per input scan batch.""" io_buffer_size: Optional[int] - """Maximum number of bytes queued in the input scan I/O buffer.""" + """Input scan I/O read-ahead budget in bytes. + + Zero disables byte-based I/O backpressure. + """ defer_index_remap: bool """Whether to defer index remapping during compaction (default: False).""" @@ -556,7 +580,7 @@ def _into_pyarrow_reader( and data.__class__.__name__ == "LazyFrame" ): return data.collect().to_arrow().to_reader() - elif isinstance(data, Iterable): + elif isinstance(data, Iterable) and not isinstance(data, str): return _iterator_to_reader(data, schema) else: raise TypeError( @@ -1575,7 +1599,7 @@ class Table(ABC): def to_lance(self, **kwargs) -> lance.LanceDataset: """Return a LanceDB Embedded table as a lance.LanceDataset. - LanceDB Distributed tables cannot be opened as Lance datasets by the + LanceDB Enterprise tables cannot be opened as Lance datasets by the client. Use ``table.search().to_arrow()`` to read them through the server. @@ -1588,7 +1612,7 @@ class Table(ABC): def to_polars(self, batch_size=None) -> "pl.LazyFrame": """Return the table as a Polars LazyFrame. - In LanceDB Distributed, use ``table.search().to_polars()`` to convert query + In LanceDB Enterprise, use ``table.search().to_polars()`` to convert query results to a Polars DataFrame. Parameters @@ -1883,16 +1907,38 @@ 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, FTS. + BTree, Bitmap, LabelList, Fm, NGram, FTS. replace : bool, default True Whether to replace an existing index on this column. wait_timeout : timedelta, optional - Timeout to wait for async indexing to complete. + LanceDB Enterprise only: how long to wait for the index build to finish. + If not set, the call returns once the build is scheduled. name : str, optional Custom name for the index. train : bool, default True Whether to train the index with existing data. + Notes + ----- + On LanceDB Embedded tables the index is built before this method + returns. On LanceDB Enterprise tables it returns once the build is + scheduled. Until the build finishes, a vector index may be missing + from [list_indices][lancedb.table.Table.list_indices], a scalar or FTS + index may be listed with 0 indexed rows, and queries won't use the + index. To block until the index is ready, pass ``wait_timeout``, call + [wait_for_index][lancedb.table.Table.wait_for_index], or use + [create_index_async][lancedb.table.Table.create_index_async] and wait + on its job when the server returned a job ID. + + ``wait_timeout`` waits for the submitted build when the server returns + a job ID. On older servers that don't return one, it falls back to + polling the index by name. ``wait_for_index`` always waits by name. + When replacing an existing index, those name-based waits may return + before the new build finishes because the old index can still match. + ``create_index_async`` can track a specific build only when the server + returned a job ID; otherwise it returns an already-complete job and + callers must use ``wait_for_index`` for that build. + Examples -------- New API (recommended): @@ -1926,11 +1972,38 @@ class Table(ABC): Takes the same arguments as :meth:`create_index`. The job may already be complete when returned; callers must not assume the index exists until :meth:`Job.wait` returns. + + In LanceDB Enterprise, the returned job tracks this submission only if + the server returns a job ID. If it does not, the job is already + complete and does not wait for the background build; use + ``wait_for_index`` and account for the replacement caveat described in + [create_index][lancedb.table.Table.create_index]. """ raise NotImplementedError( "create_index_async is not supported for this table type" ) + def get_table_overrides(self) -> dict[str, Any]: + """Read Enterprise table overrides for this table. + + Table overrides configure Enterprise-managed background behavior such as + automatic compaction, cleanup, and reindex execution. This method is + supported only on remote Enterprise tables. + """ + raise NotImplementedError + + 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. + """ + raise NotImplementedError + + def reset_table_overrides(self) -> dict[str, Any]: + """Clear Enterprise table overrides for this table.""" + raise NotImplementedError + def drop_index(self, name: str) -> None: """ Drop an index from the table. @@ -2493,9 +2566,8 @@ class Table(ABC): Row ids are not stable and are relative to the current version of the table. They can change due to compaction and updates. - No guarantees are made regarding the order in which results are returned. If - you desire an output order that matches the order of the given ids, you will - need to add the row id column to the output and align it yourself. + Results follow the requested row-id order. Repeated IDs produce repeated + rows; missing or deleted IDs are omitted. This also applies to remote tables. Unlike offsets, row ids are not 0-indexed and no assumptions should be made about the possible range of row ids. In order to use this method you must @@ -2548,7 +2620,7 @@ class Table(ABC): Blobs inside lists cannot be fetched by row id yet. - LanceDB Distributed limits each request to 1024 row IDs and 64 MiB of blob + LanceDB Enterprise limits each request to 1024 row IDs and 64 MiB of blob bytes. The client splits requests automatically and reads an individual larger blob through the Range route. This method still materializes all bytes in memory; for large values use :meth:`fetch_blob_files`. @@ -2575,7 +2647,7 @@ class Table(ABC): results are returned. Row IDs can be obtained from a query with ``with_row_id(True)``. - LanceDB Distributed reads the requested ranges through version-pinned blob + LanceDB Enterprise reads the requested ranges through version-pinned blob handles using HTTP byte-range requests. """ @@ -2592,7 +2664,7 @@ class Table(ABC): a ``list[int]``, an integer Arrow array or chunked array, or a query ``pyarrow.Table`` carrying row identity via ``_rowid`` or a ``_lance_row_id`` field on the blob descriptor. Null blob values return - ``None``. LanceDB Distributed requires server version 0.5.0 or newer. + ``None``. LanceDB Enterprise requires server version 0.5.0 or newer. ``_rowid`` values stay valid after compaction when the table has stable row ids. @@ -2744,6 +2816,11 @@ class Table(ABC): Either `values` or `values_sql` must be provided. You cannot provide both. + Embeddings are not computed by this method. Updating an embedding source + column requires providing all associated vector columns in the same call; + otherwise a ValueError is raised. Use `merge_insert` to recompute embeddings + automatically. + Parameters ---------- where: str or [Expr][lancedb.expr.Expr], optional @@ -2829,7 +2906,7 @@ class Table(ABC): Notes ----- - This function is not available in LanceDB Distributed, which manages + This function is not available in LanceDB Enterprise, which manages cleanup for you automatically. """ @@ -2851,7 +2928,7 @@ class Table(ABC): Notes ----- - This function is not available in LanceDB Distributed, which manages + This function is not available in LanceDB Enterprise, which manages compaction for you automatically. """ @@ -2867,6 +2944,21 @@ class Table(ABC): """ Optimize the on-disk data and indices for better performance. + .. note:: + + On a LanceDB Enterprise (remote) table, only compaction is + currently supported. Pruning old versions and index optimization + are silently skipped there instead of being attempted, so this + call returns successfully, with zeroed pruning statistics, once + the compaction job has been submitted; it does not wait for that + job to finish. Remote compaction supports per-job + ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``, + and ``batch_size``. Omitted fields inherit table tuning, then + deployment/built-in defaults. Other non-default compaction settings raise + ``NotImplementedError`` before submission. The server must support + these SQL options; older-server errors are propagated without + dropping the requested settings. + Modeled after ``VACUUM`` in PostgreSQL. Optimization covers three operations: @@ -2922,6 +3014,12 @@ class Table(ABC): """ List all indices that have been created with [Table.create_index][lancedb.table.Table.create_index] + + On LanceDB Enterprise tables, an index whose build hasn't finished may + be missing (vector indices) or listed with 0 indexed rows (scalar and + FTS indices), and ``num_unindexed_rows`` may be ``None``. Use + [wait_for_index][lancedb.table.Table.wait_for_index] to wait until an + index is ready. """ @abstractmethod @@ -2938,7 +3036,7 @@ class Table(ABC): Specify exactly one of ``column`` or ``index_name``. Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are - rebuilt in the client process from index metadata. In LanceDB Distributed, + rebuilt in the client process from index metadata. In LanceDB Enterprise, this means the same tokenizer model files must also exist locally (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the server uses. A mismatch cannot be detected: the returned tokens may @@ -2965,11 +3063,15 @@ class Table(ABC): @abstractmethod def add_columns( self, - transforms: Dict[str, str | FunctionApplication] + transforms: Mapping[str, str | FunctionApplication] | FunctionApplication | pa.Field | List[pa.Field] | pa.Schema + | DATA + | pa.RecordBatch + | pa.RecordBatchReader + | pl.DataFrame | None = None, *, computed: Dict[str, str] | None = None, @@ -2981,8 +3083,9 @@ class Table(ABC): Parameters ---------- - transforms: Dict[str, str | FunctionApplication], FunctionApplication, - pa.Field, List[pa.Field], pa.Schema + transforms: Mapping[str, str | FunctionApplication], FunctionApplication, + pa.Field, List[pa.Field], pa.Schema, pandas.DataFrame, + polars.DataFrame, pa.Table, pa.RecordBatch, pa.RecordBatchReader A map of column name to a SQL expression to use to calculate the value of the new column. These expressions will be evaluated for each row in the table, and can reference existing columns. @@ -2995,11 +3098,21 @@ class Table(ABC): named-struct application expands its ordered result fields as one atomic binding; aliases come from ``rename(columns=...)``. Function columns are supported only in LanceDB - Distributed. + Enterprise. + + On local tables, a pandas or Polars DataFrame, PyArrow Table, + RecordBatch, or RecordBatchReader supplies precomputed new-column + values. Supply exactly one row per current live table row, in storage + scan order; pandas indexes are ignored. The input contains only new + columns. Readers are consumed once, and their batch boundaries need + not match table fragments. Keep the table unchanged between computing + these values and calling add_columns. Data inputs cannot be combined + with computed columns. Remote tables do not support data inputs. + computed: Dict[str, str], optional LanceDB Embedded declaration and refresh require a source build with the ``experimental-functions`` Cargo feature, which published packages - do not enable. LanceDB Distributed operations remain available. + do not enable. LanceDB Enterprise operations remain available. A mapping from output column names to SQL expressions derives each output field from its expression. A direct projection of a Blob v2 @@ -3018,7 +3131,7 @@ class Table(ABC): While a declaration reads a column, that column cannot be renamed, retyped or dropped. - In LanceDB Distributed the expression is planned by the + In LanceDB Enterprise the expression is planned by the server, and the refresh runs as a server job -- see [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Cannot be combined with ``transforms``. @@ -3051,10 +3164,31 @@ class Table(ABC): x doubled 0 1 2 1 2 4 + + >>> import pyarrow as pa + >>> result = table.add_columns(pa.table({"score": [0.25, 0.75]}).to_reader()) + >>> table.to_arrow()["score"].to_pylist() + [0.25, 0.75] """ @abstractmethod - def refresh_column(self, column: str) -> "RefreshColumnResult": + def refresh_column( + self, + column: str, + *, + where: Optional[str] = None, + batch_size: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, + ) -> "RefreshColumnResult": """ Fill the rows of a computed column that hold no value yet. @@ -3066,14 +3200,54 @@ class Table(ABC): by the next one, and rows whose inputs changed since they were computed are recomputed; everything else is left as it is. - LanceDB Embedded only. In LanceDB Distributed, a refresh runs as a - server job, through + Supported for local tables only. For remote tables, a refresh runs as + a server job, through [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Parameters ---------- column: str The name of the computed column to fill. + where: str, optional + SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN + ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB + Enterprise only; local refreshes reject this option. + batch_size: int, optional + Maximum rows per Function call on the remote server. Must be + greater than zero. None uses the server default. Has no effect on + local expression-backed columns. + gpu_class: str, optional + GPU class for Function workers. Must be a lowercase name of 1-63 + letters, digits, or hyphens, without a leading or trailing hyphen. + None keeps the Function's registered class or the deployment + default. LanceDB Enterprise only. + gpu_count: int, optional + Positive aggregate GPU budget for Function workers. None leaves + the server's configured budget unchanged. LanceDB Enterprise + only. + retry_policy: FunctionRetryPolicy, optional + Override retries of failed user-code calls. Only use when repeating + partial work is safe. Set max_attempts=1 to disable retries. + Enterprise Functions only; local refreshes reject this option. + error_policy: {"fail", "skip"}, optional + Action after failure or retry exhaustion. Skip records the error + and attempt count, subject to the server's failure limits. + max_failed_fraction: float, optional + Under a skip policy, fail the job once more than this share of + rows (0 to 1) has failed. LanceDB Enterprise only. + max_failed_rows: int, optional + Under a skip policy, fail the job once more than this many rows + have failed. LanceDB Enterprise only. + row_timeout_seconds: float, optional + Deadline for one Function call. LanceDB Enterprise only. + init_timeout_seconds: float, optional + Deadline for Function initialization. LanceDB Enterprise only. + num_workers: int, optional + Worker count for an expression column; registered Function + columns reject it. LanceDB Enterprise only. + max_executor_processes_per_worker: int, optional + Cap on executor processes per Function worker. LanceDB + Enterprise only. Returns ------- @@ -3083,20 +3257,81 @@ class Table(ABC): """ @abstractmethod - def refresh_column_async(self, column: str) -> Job[RefreshColumnJobResult]: + def refresh_column_async( + self, + column: str, + *, + where: Optional[str] = None, + batch_size: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, + ) -> Job[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job instead of blocking until it completes. - LanceDB Embedded refresh requires a source build with - ``experimental-functions``. - LanceDB Distributed jobs do not require this feature. + Local refresh requires a source build with ``experimental-functions``. + Remote jobs do not require this feature. The job may already be complete when returned; callers must not assume the column is filled until :meth:`Job.wait` returns. Invalid input -- an unknown column, or one that is not computed -- raises here rather - than failing the job. In LanceDB Embedded the job runs in-process; in - LanceDB Distributed it is the server's backfill job. + than failing the job. For local tables, the job runs in-process; for + remote tables, it is the server's backfill job. + + Parameters + ---------- + column: str + The name of the computed column to fill. + where: str, optional + SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN + ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB + Enterprise only; local refreshes reject this option. + batch_size: int, optional + Maximum rows per Function call on the remote server. Must be + greater than zero. None uses the server default. Lower this for + slow Functions to stay within the executor's per-call deadline. + Has no effect on local expression-backed columns. + gpu_class: str, optional + GPU class for Function workers. Must be a lowercase name of 1-63 + letters, digits, or hyphens, without a leading or trailing hyphen. + None keeps the Function's registered class or the deployment + default. LanceDB Enterprise only. + gpu_count: int, optional + Positive aggregate GPU budget for Function workers. None leaves + the server's configured budget unchanged. LanceDB Enterprise + only. + retry_policy: FunctionRetryPolicy, optional + Override retries of failed user-code calls. Only use when repeating + partial work is safe. Set max_attempts=1 to disable retries. + Enterprise Functions only; local refreshes reject this option. + error_policy: {"fail", "skip"}, optional + Action after failure or retry exhaustion. Skip records the error + and attempt count, subject to the server's failure limits. + max_failed_fraction: float, optional + Under a skip policy, fail the job once more than this share of + rows (0 to 1) has failed. LanceDB Enterprise only. + max_failed_rows: int, optional + Under a skip policy, fail the job once more than this many rows + have failed. LanceDB Enterprise only. + row_timeout_seconds: float, optional + Deadline for one Function call. LanceDB Enterprise only. + init_timeout_seconds: float, optional + Deadline for Function initialization. LanceDB Enterprise only. + num_workers: int, optional + Worker count for an expression column; registered Function + columns reject it. LanceDB Enterprise only. + max_executor_processes_per_worker: int, optional + Cap on executor processes per Function worker. LanceDB + Enterprise only. Returns ------- @@ -3132,7 +3367,7 @@ class Table(ABC): 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 Distributed only; reading errors + detail was capped. LanceDB Enterprise only; reading errors needs read access to the table, since a message carries the value that failed. @@ -3151,6 +3386,52 @@ class Table(ABC): ``records``, ``fragments`` and ``truncated``, the last saying whether the listing stopped at its limit. + Each record identifies its row with ``fragment_id``, ``row_offset``, + the physical ``row_address`` (``(fragment_id << 32) | + row_offset``), and, when the table uses stable row IDs, the stable + ``row_id`` read from the refresh's pinned table version. Prefer + ``row_id`` for retries: compaction and rewrite can change the + physical fields, while a stable row ID survives them. + + To retry the recorded rows with stable row IDs: + + .. code-block:: python + + errors = table.function_errors(column="embedding") + row_ids = sorted( + record.row_id + for record in errors.records + if record.row_id is not None + ) + if row_ids: + row_id_list = ", ".join(str(row_id) for row_id in row_ids) + database.execute_query( + f"REFRESH COLUMN embedding ON {table.name} " + f"WHERE _rowid IN ({row_id_list})" + ) + + For a table without stable row IDs, collect the non-null physical + addresses before the table is compacted or rewritten and run the + SQL refresh: + + .. code-block:: python + + errors = table.function_errors(column="embedding") + addresses = sorted( + record.row_address + for record in errors.records + if record.row_address is not None + ) + if addresses: + address_list = ", ".join(str(address) for address in addresses) + database.execute_query( + f"REFRESH COLUMN embedding ON {table.name} " + f"WHERE _rowaddr IN ({address_list})" + ) + + Records whose per-row detail was capped have no address and appear + only in ``fragments``; they cannot be selected individually here. + Examples -------- >>> errors = table.function_errors(column="embedding") # doctest: +SKIP @@ -3188,6 +3469,9 @@ class Table(ABC): or "nullable". The legacy key "name" is also accepted for renaming. Unknown keys raise ValueError before any alterations are applied. + Local tables reject renaming source or vector columns used by an + embedding function with ValueError, preserving the embedding binding. + Returns ------- AlterColumnsResult @@ -3256,6 +3540,9 @@ class Table(ABC): """ Drop columns from the table. + Local tables reject dropping source or vector columns used by an + embedding function with ValueError, preserving the embedding binding. + Parameters ---------- columns : Iterable[str] @@ -3984,7 +4271,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, FTS. + BTree, Bitmap, LabelList, Fm, NGram, FTS. replace : bool, default True Whether to replace an existing index on this column. wait_timeout : timedelta, optional @@ -4142,6 +4429,12 @@ class LanceTable(Table): The job may already be complete when returned; callers must not assume the index exists until :meth:`Job.wait` returns. + + In LanceDB Enterprise, the returned job tracks this submission only if + the server returns a job ID. If it does not, the job is already + complete and does not wait for the background build; use + ``wait_for_index`` and account for the replacement caveat described in + [create_index][lancedb.table.Table.create_index]. """ return Job( LOOP.run( @@ -4195,7 +4488,7 @@ class LanceTable(Table): This is a hint to the database that the given columns will be accessed in the future and the database should prefetch the data if possible. - Currently only supported in LanceDB Distributed. + 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. @@ -4831,6 +5124,11 @@ class LanceTable(Table): This can be used to update zero to all rows depending on how many rows match the where clause. + Embeddings are not computed by this method. Updating an embedding source + column requires providing all associated vector columns in the same call; + otherwise a ValueError is raised. Use `merge_insert` to recompute embeddings + automatically. + Parameters ---------- where: str or [Expr][lancedb.expr.Expr], optional @@ -4892,8 +5190,7 @@ class LanceTable(Table): ) and not self._route_pushdown_to_rust and self.current_branch() is None - and query.take_offsets is None - and query.search_effort is None + and not _requires_local_namespace_execution(query) ): from lancedb.namespace import _execute_server_side_query @@ -5086,7 +5383,7 @@ class LanceTable(Table): Specify exactly one of ``column`` or ``index_name``. Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are - rebuilt in the client process from index metadata. In LanceDB Distributed, + rebuilt in the client process from index metadata. In LanceDB Enterprise, this means the same tokenizer model files must also exist locally (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the server uses. A mismatch cannot be detected: the returned tokens may @@ -5115,11 +5412,15 @@ class LanceTable(Table): def add_columns( self, - transforms: Dict[str, str | FunctionApplication] + transforms: Mapping[str, str | FunctionApplication] | FunctionApplication | pa.Field | List[pa.Field] | pa.Schema + | DATA + | pa.RecordBatch + | pa.RecordBatchReader + | pl.DataFrame | None = None, *, computed: Dict[str, str] | None = None, @@ -5135,18 +5436,84 @@ class LanceTable(Table): ) ) - def refresh_column(self, column: str) -> "RefreshColumnResult": + def refresh_column( + self, + column: str, + *, + where: Optional[str] = None, + batch_size: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, + ) -> "RefreshColumnResult": """Fill a computed column's unfilled rows and recompute those whose inputs changed. See [`AsyncTable.refresh_column`][lancedb.AsyncTable.refresh_column].""" - return LOOP.run(self._table.refresh_column(column)) + return LOOP.run( + self._table.refresh_column( + column, + where=where, + batch_size=batch_size, + gpu_class=gpu_class, + gpu_count=gpu_count, + retry_policy=retry_policy, + error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, + ) + ) - def refresh_column_async(self, column: str) -> Job[RefreshColumnJobResult]: + def refresh_column_async( + self, + column: str, + *, + where: Optional[str] = None, + batch_size: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, + ) -> Job[RefreshColumnJobResult]: """Fill a computed column's unfilled rows and recompute those whose inputs changed, returning a handle to the refresh job. See [`Table.refresh_column_async`][lancedb.table.Table.refresh_column_async]. """ - return Job(LOOP.run(self._table.refresh_column_async(column))) + return Job( + LOOP.run( + self._table.refresh_column_async( + column, + where=where, + batch_size=batch_size, + gpu_class=gpu_class, + gpu_count=gpu_count, + retry_policy=retry_policy, + error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, + ) + ) + ) def function_errors( self, @@ -5193,6 +5560,36 @@ class LanceTable(Table): [`AsyncTable.get_rte_spec`][lancedb.AsyncTable.get_rte_spec].""" return LOOP.run(self._table.get_rte_spec()) + def get_table_overrides(self) -> dict[str, Any]: + """Read Enterprise table overrides for this table. + + Table overrides configure Enterprise-managed background behavior such as + automatic compaction, cleanup, and reindex execution. This method is + supported only on remote Enterprise tables. + """ + 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. + + Only fields supplied in ``overrides`` are changed; unrelated overrides + from the current read snapshot are preserved. + + Examples + -------- + >>> table.update_table_overrides( # doctest: +SKIP + ... job_types={ + ... "compaction": {"enabled": True}, + ... "cleanup": {"enabled": False}, + ... } + ... ) + """ + return LOOP.run(self._table.update_table_overrides(**overrides)) + + def reset_table_overrides(self) -> dict[str, Any]: + """Clear Enterprise table overrides for this table.""" + return LOOP.run(self._table.reset_table_overrides()) + def checkpoint_rte(self) -> None: """Synchronous version of [`AsyncTable.checkpoint_rte`][lancedb.AsyncTable.checkpoint_rte].""" @@ -5942,6 +6339,37 @@ class AsyncTable: """ return await self._inner.get_rte_spec() + async def get_table_overrides(self) -> dict[str, Any]: + """Read Enterprise table overrides for this table. + + Table overrides configure Enterprise-managed background behavior such as + automatic compaction, cleanup, and reindex execution. This method is + supported only on remote Enterprise tables. + """ + return json.loads(await self._inner.get_table_overrides()) + + 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. + + Examples + -------- + >>> await table.update_table_overrides( # doctest: +SKIP + ... job_types={ + ... "compaction": {"enabled": True}, + ... "cleanup": {"enabled": False}, + ... } + ... ) + """ + encoded = json.dumps(overrides) + return json.loads(await self._inner.update_table_overrides(encoded)) + + async def reset_table_overrides(self) -> dict[str, Any]: + """Clear Enterprise table overrides for this table.""" + return json.loads(await self._inner.reset_table_overrides()) + # WAL-PK-FUSION: delete both hooks. def _hybrid_pk_fusion_learned(self) -> bool: """See [`Table._hybrid_pk_fusion_learned`][lancedb.table.Table].""" @@ -6083,7 +6511,7 @@ class AsyncTable: async def to_lance(self, **kwargs) -> lance.LanceDataset: """Return the Lance dataset backing a LanceDB Embedded table. - LanceDB Distributed tables cannot be opened as Lance datasets by the + LanceDB Enterprise tables cannot be opened as Lance datasets by the client. Use [to_arrow][lancedb.table.AsyncTable.to_arrow] or [query][lancedb.table.AsyncTable.query] to read them through the server. @@ -6105,7 +6533,7 @@ class AsyncTable: """ if not self._inner._is_native(): raise NotImplementedError( - "to_lance() is not supported in LanceDB Distributed; " + "to_lance() is not supported in LanceDB Enterprise; " "query the server instead" ) @@ -6138,7 +6566,7 @@ class AsyncTable: Parameters ---------- blob_mode: str, default "lazy" - Controls how Lance blob columns are returned. LanceDB Distributed supports + Controls how Lance blob columns are returned. LanceDB Enterprise supports "descriptions"; "bytes" and "lazy" are not yet supported. **kwargs Forwarded to PyArrow / Lance pandas conversion. @@ -6215,6 +6643,7 @@ class AsyncTable: Bitmap, LabelList, Fm, + NGram, FTS, ] ] = None, @@ -6246,12 +6675,34 @@ class AsyncTable: like to create. You can also specify index-specific parameters when creating an index object. wait_timeout: timedelta, optional - The timeout to wait if indexing is asynchronous. + LanceDB Enterprise only: how long to wait for the index build to finish. + If not set, the call returns once the build is scheduled. name: str, optional The name of the index. If not provided, a default name will be generated. train: bool, default True Whether to train the index with existing data. Vector indices always train with existing data. + + Notes + ----- + On LanceDB Embedded tables the index is built before this method + returns. On LanceDB Enterprise tables it returns once the build is + scheduled. Until the build finishes, a vector index may be missing + from [list_indices][lancedb.table.AsyncTable.list_indices], a scalar or + FTS index may be listed with 0 indexed rows, and queries won't use the + index. To block until the index is ready, pass ``wait_timeout``, call + [wait_for_index][lancedb.table.AsyncTable.wait_for_index], or use + [create_index_async][lancedb.table.AsyncTable.create_index_async] and + wait on its job when the server returned a job ID. + + ``wait_timeout`` waits for the submitted build when the server returns + a job ID. On older servers that don't return one, it falls back to + polling the index by name. ``wait_for_index`` always waits by name. + When replacing an existing index, those name-based waits may return + before the new build finishes because the old index can still match. + ``create_index_async`` can track a specific build only when the server + returned a job ID; otherwise it returns an already-complete job and + callers must use ``wait_for_index`` for that build. """ if config is not None: if not isinstance( @@ -6268,12 +6719,13 @@ class AsyncTable: Bitmap, LabelList, Fm, + NGram, FTS, ), ): raise TypeError( "config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq," - " BTree, Bitmap, LabelList, Fm, or FTS, but got " + " BTree, Bitmap, LabelList, Fm, NGram, or FTS, but got " + str(type(config)) ) try: @@ -6311,6 +6763,7 @@ class AsyncTable: Bitmap, LabelList, Fm, + NGram, FTS, ] ] = None, @@ -6323,6 +6776,12 @@ class AsyncTable: Takes the same arguments as :meth:`create_index`. The job may already be complete when returned; callers must not assume the index exists until :meth:`AsyncJob.wait` resolves. + + In LanceDB Enterprise, the returned job tracks this submission only if + the server returns a job ID. If it does not, the job is already + complete and does not wait for the background build; use + ``wait_for_index`` and account for the replacement caveat described in + [create_index][lancedb.table.AsyncTable.create_index]. """ job = await self._inner.create_index_async( column, @@ -6382,7 +6841,7 @@ class AsyncTable: This is a hint to the database that the given columns will be accessed in the future and the database should prefetch the data if possible. - Currently only supported in LanceDB Distributed. + 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. @@ -6426,7 +6885,7 @@ class AsyncTable: """ Get the table URI (storage location). - In LanceDB Distributed, this fetches the location from the server via describe. + In LanceDB Enterprise, this fetches the location from the server via describe. In LanceDB Embedded, this returns the dataset URI. Returns @@ -6918,10 +7377,24 @@ class AsyncTable: | AsyncQuery | AsyncTakeQuery ): - if query.take_offsets is not None: - take_query = self.take_offsets(query.take_offsets) - if query.columns: - take_query = take_query.select(query.columns) + if query.take_offsets is not None or query.take_row_ids is not None: + if query.take_offsets is not None and query.take_row_ids is not None: + raise ValueError("Only one of take_offsets and take_row_ids may be set") + 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) + ) + if query.columns is not None: + columns = query.columns + # Native requests serialize dynamic projections as (name, SQL) pairs. + if ( + isinstance(columns, list) + and columns + and isinstance(columns[0], tuple) + ): + columns = dict(columns) + take_query = take_query.select(columns) if query.use_rte is not None: take_query = take_query.use_rte(query.use_rte) if query.with_row_id: @@ -6970,6 +7443,8 @@ class AsyncTable: async_query = async_query.column(query.vector_column) if query.ef: async_query = async_query.ef(query.ef) + if query.approx_mode: + async_query = async_query.approx_mode(query.approx_mode) if query.bypass_vector_index: async_query = async_query.bypass_vector_index() @@ -6995,8 +7470,7 @@ class AsyncTable: self._namespace_client, self._pushdown_operations ) and not self._route_pushdown_to_rust - and query.take_offsets is None - and query.search_effort is None + and not _requires_local_namespace_execution(query) ): from lancedb.namespace import _execute_server_side_query @@ -7137,6 +7611,11 @@ class AsyncTable: If a filter is provided with `where` then only rows matching the filter will be updated. Otherwise all rows will be updated. + Embeddings are not computed by this method. Updating an embedding source + column requires providing all associated vector columns in the same call; + otherwise a ValueError is raised. Use `merge_insert` to recompute embeddings + automatically. + Parameters ---------- updates: dict, optional @@ -7186,16 +7665,38 @@ class AsyncTable: if updates is not None: updates_sql = {k: value_to_sql(v) for k, v in updates.items()} + # Only the column mappings are needed here. Restoring embedding functions + # could load models even for updates that provide their own vectors. + schema = await self.schema() + column_pairs = _embedding_column_pairs(schema.metadata) + if column_pairs: + # Metadata names are literal top-level fields; targets may be quoted. + updated_columns = {tuple(_parse_field_path(name)) for name in updates_sql} + for source_column, vector_column in column_pairs: + source_updated = (source_column,) in updated_columns + vector_updated = (vector_column,) in updated_columns + if source_updated and not vector_updated: + raise ValueError( + f"Updating embedding source column {source_column!r} requires " + f"updating vector column {vector_column!r} in the same call. " + "Provide both columns or use merge_insert " + "to recompute embeddings." + ) + predicate = where.to_sql() if isinstance(where, Expr) else where return await self._inner.update(updates_sql, predicate) async def add_columns( self, - transforms: dict[str, str | FunctionApplication] + transforms: Mapping[str, str | FunctionApplication] | FunctionApplication | pa.Field | List[pa.Field] | pa.Schema + | DATA + | pa.RecordBatch + | pa.RecordBatchReader + | pl.DataFrame | None = None, *, computed: dict[str, str] | None = None, @@ -7207,7 +7708,9 @@ class AsyncTable: Parameters ---------- - transforms: Dict[str, str | FunctionApplication] or FunctionApplication + transforms: Mapping[str, str | FunctionApplication], FunctionApplication, + pa.Field, List[pa.Field], pa.Schema, pandas.DataFrame, + polars.DataFrame, pa.Table, pa.RecordBatch, pa.RecordBatchReader A map of column name to a SQL expression to use to calculate the value of the new column. These expressions will be evaluated for each row in the table, and can reference existing columns. @@ -7219,11 +7722,21 @@ class AsyncTable: named-struct application expands its ordered result fields as one atomic binding; aliases come from ``rename(columns=...)``. Function columns are supported only in LanceDB - Distributed. + Enterprise. + + On local tables, a pandas or Polars DataFrame, PyArrow Table, + RecordBatch, or RecordBatchReader supplies precomputed new-column + values. Supply exactly one row per current live table row, in storage + scan order; pandas indexes are ignored. The input contains only new + columns. Readers are consumed once, and their batch boundaries need + not match table fragments. Keep the table unchanged between computing + these values and calling add_columns. Data inputs cannot be combined + with computed columns. Remote tables do not support data inputs. + computed: Dict[str, str], optional LanceDB Embedded declaration and refresh require a source build with the ``experimental-functions`` Cargo feature, which published packages - do not enable. LanceDB Distributed operations remain available. + do not enable. LanceDB Enterprise operations remain available. A mapping from output column names to SQL expressions derives each output field from its expression. A direct projection of a Blob v2 @@ -7241,13 +7754,13 @@ class AsyncTable: While a declaration reads a column, that column cannot be renamed, retyped or dropped. - In LanceDB Distributed the expression is planned by + In LanceDB Enterprise the expression is planned by the server. Cannot be combined with ``transforms``. auto_refresh_enabled: bool, optional Enable automatic refresh for each computed output declared by this call. Defaults to True. LanceDB Embedded stores the setting; automatic - scheduling requires LanceDB Distributed. + scheduling requires LanceDB Enterprise. auto_refresh_interval_seconds: int, optional Positive minimum seconds after a successful refresh before another automatic refresh is eligible. When omitted, the server determines when @@ -7288,7 +7801,7 @@ class AsyncTable: function_output_name = None if isinstance(transforms, FunctionApplication): function_application = transforms - elif isinstance(transforms, dict) and any( + elif isinstance(transforms, Mapping) and any( isinstance(value, FunctionApplication) for value in transforms.values() ): if len(transforms) != 1 or not all( @@ -7320,7 +7833,10 @@ class AsyncTable: ): transforms = pa.schema(transforms) if computed: - if transforms: + if transforms is not None and ( + not isinstance(transforms, (Mapping, list, pa.Schema)) + or bool(transforms) + ): raise ValueError( "add_columns cannot take both transforms and computed columns" ) @@ -7337,10 +7853,29 @@ class AsyncTable: raise ValueError("add_columns requires transforms or computed columns") if isinstance(transforms, pa.Schema): return await self._inner.add_columns_with_schema(transforms) - else: + if isinstance(transforms, Mapping): return await self._inner.add_columns(list(transforms.items())) + return await self._inner.add_columns_from_reader( + _into_pyarrow_reader(transforms) + ) - async def refresh_column(self, column: str) -> RefreshColumnResult: + async def refresh_column( + self, + column: str, + *, + where: Optional[str] = None, + batch_size: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, + ) -> RefreshColumnResult: """ Fill the rows of a computed column that hold no value yet. @@ -7352,21 +7887,77 @@ class AsyncTable: by the next one, and rows whose inputs changed since they were computed are recomputed; everything else is left as it is. - LanceDB Embedded only. In LanceDB Distributed, a refresh runs as a - server job, through + Supported for local tables only. For remote tables, a refresh runs as + a server job, through [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Parameters ---------- column: str The name of the computed column to fill. + where: str, optional + SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN + ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB + Enterprise only; local refreshes reject this option. + batch_size: int, optional + Maximum rows per Function call on the remote server. Must be + greater than zero. None uses the server default. Has no effect on + local expression-backed columns. + gpu_class: str, optional + GPU class for Function workers. Must be a lowercase name of 1-63 + letters, digits, or hyphens, without a leading or trailing hyphen. + None keeps the Function's registered class or the deployment + default. LanceDB Enterprise only. + gpu_count: int, optional + Positive aggregate GPU budget for Function workers. None leaves + the server's configured budget unchanged. LanceDB Enterprise + only. + retry_policy: FunctionRetryPolicy, optional + Override retries of failed user-code calls. Only use when repeating + partial work is safe. Set max_attempts=1 to disable retries. + Enterprise Functions only; local refreshes reject this option. + error_policy: {"fail", "skip"}, optional + Action after failure or retry exhaustion. Skip records the error + and attempt count, subject to the server's failure limits. + max_failed_fraction: float, optional + Under a skip policy, fail the job once more than this share of + rows (0 to 1) has failed. LanceDB Enterprise only. + max_failed_rows: int, optional + Under a skip policy, fail the job once more than this many rows + have failed. LanceDB Enterprise only. + row_timeout_seconds: float, optional + Deadline for one Function call. LanceDB Enterprise only. + init_timeout_seconds: float, optional + Deadline for Function initialization. LanceDB Enterprise only. + num_workers: int, optional + Worker count for an expression column; registered Function + columns reject it. LanceDB Enterprise only. + max_executor_processes_per_worker: int, optional + Cap on executor processes per Function worker. LanceDB + Enterprise only. Returns ------- RefreshColumnResult The number of rows filled and the new version of the table. """ - return await self._inner.refresh_column(column) + return await self._inner.refresh_column( + column, + where=where, + batch_size=batch_size, + gpu_class=gpu_class, + gpu_count=gpu_count, + retry_policy=None + if retry_policy is None + else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(), + error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, + ) async def function_errors( self, @@ -7380,7 +7971,7 @@ class AsyncTable: 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 Distributed only; reading errors + detail was capped. LanceDB Enterprise only; reading errors needs read access to the table, since a message carries the value that failed. @@ -7399,6 +7990,52 @@ class AsyncTable: ``records``, ``fragments`` and ``truncated``, the last saying whether the listing stopped at its limit. + Each record identifies its row with ``fragment_id``, ``row_offset``, + the physical ``row_address`` (``(fragment_id << 32) | + row_offset``), and, when the table uses stable row IDs, the stable + ``row_id`` read from the refresh's pinned table version. Prefer + ``row_id`` for retries: compaction and rewrite can change the + physical fields, while a stable row ID survives them. + + To retry the recorded rows with stable row IDs: + + .. code-block:: python + + errors = await table.function_errors(column="embedding") + row_ids = sorted( + record.row_id + for record in errors.records + if record.row_id is not None + ) + if row_ids: + row_id_list = ", ".join(str(row_id) for row_id in row_ids) + await database.execute_query( + f"REFRESH COLUMN embedding ON {table.name} " + f"WHERE _rowid IN ({row_id_list})" + ) + + For a table without stable row IDs, collect the non-null physical + addresses before the table is compacted or rewritten and run the + SQL refresh: + + .. code-block:: python + + errors = await table.function_errors(column="embedding") + addresses = sorted( + record.row_address + for record in errors.records + if record.row_address is not None + ) + if addresses: + address_list = ", ".join(str(address) for address in addresses) + await database.execute_query( + f"REFRESH COLUMN embedding ON {table.name} " + f"WHERE _rowaddr IN ({address_list})" + ) + + Records whose per-row detail was capped have no address and appear + only in ``fragments``; they cannot be selected individually here. + Examples -------- >>> errors = await table.function_errors(column="embedding") # doctest: +SKIP @@ -7412,22 +8049,80 @@ class AsyncTable: ) async def refresh_column_async( - self, column: str + self, + column: str, + *, + where: Optional[str] = None, + batch_size: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ) -> AsyncJob[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job instead of blocking until it completes. - LanceDB Embedded refresh requires a source build with - ``experimental-functions``. - LanceDB Distributed jobs do not require this feature. + Local refresh requires a source build with ``experimental-functions``. + Remote jobs do not require this feature. The job may already be complete when returned; callers must not assume the column is filled until :meth:`AsyncJob.wait` resolves. Invalid input -- an unknown column, or one that is not computed -- raises here - rather than failing the job. In LanceDB Embedded the job runs - in-process; in LanceDB Distributed it is the server's - backfill job. + rather than failing the job. For local tables, the job runs in-process; + for remote tables, it is the server's backfill job. + + Parameters + ---------- + column: str + The name of the computed column to fill. + where: str, optional + SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN + ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB + Enterprise only; local refreshes reject this option. + batch_size: int, optional + Maximum rows per Function call on the remote server. Must be + greater than zero. None uses the server default. Lower this for + slow Functions to stay within the executor's per-call deadline. + Has no effect on local expression-backed columns. + gpu_class: str, optional + GPU class for Function workers. Must be a lowercase name of 1-63 + letters, digits, or hyphens, without a leading or trailing hyphen. + None keeps the Function's registered class or the deployment + default. LanceDB Enterprise only. + gpu_count: int, optional + Positive aggregate GPU budget for Function workers. None leaves + the server's configured budget unchanged. LanceDB Enterprise + only. + retry_policy: FunctionRetryPolicy, optional + Override retries of failed user-code calls. Only use when repeating + partial work is safe. Set max_attempts=1 to disable retries. + Enterprise Functions only; local refreshes reject this option. + error_policy: {"fail", "skip"}, optional + Action after failure or retry exhaustion. Skip records the error + and attempt count, subject to the server's failure limits. + max_failed_fraction: float, optional + Under a skip policy, fail the job once more than this share of + rows (0 to 1) has failed. LanceDB Enterprise only. + max_failed_rows: int, optional + Under a skip policy, fail the job once more than this many rows + have failed. LanceDB Enterprise only. + row_timeout_seconds: float, optional + Deadline for one Function call. LanceDB Enterprise only. + init_timeout_seconds: float, optional + Deadline for Function initialization. LanceDB Enterprise only. + num_workers: int, optional + Worker count for an expression column; registered Function + columns reject it. LanceDB Enterprise only. + max_executor_processes_per_worker: int, optional + Cap on executor processes per Function worker. LanceDB + Enterprise only. Returns ------- @@ -7451,7 +8146,23 @@ class AsyncTable: 'finished' """ return _typed_job( - await self._inner.refresh_column_async(column), + await self._inner.refresh_column_async( + column, + where=where, + batch_size=batch_size, + gpu_class=gpu_class, + gpu_count=gpu_count, + retry_policy=None + if retry_policy is None + else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(), + error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, + ), RefreshColumnJobResult.from_json, ) @@ -7482,6 +8193,9 @@ class AsyncTable: or "nullable". The legacy key "name" is also accepted for renaming. Unknown keys raise ValueError before any alterations are applied. + Local tables reject renaming source or vector columns used by an + embedding function with ValueError, preserving the embedding binding. + Returns ------- AlterColumnsResult @@ -7500,6 +8214,9 @@ class AsyncTable: """ Drop columns from the table. + Local tables reject dropping source or vector columns used by an + embedding function with ValueError, preserving the embedding binding. + Parameters ---------- columns : Iterable[str] @@ -7631,6 +8348,9 @@ class AsyncTable: """ Take a list of row ids from the table. + Results follow the requested row-id order. Repeated IDs produce repeated + rows; missing or deleted IDs are omitted. This also applies to remote tables. + Row ids are not stable and are relative to the current version of the table. They can change due to compaction and updates. @@ -7762,6 +8482,21 @@ class AsyncTable: """ Optimize the on-disk data and indices for better performance. + .. note:: + + On a LanceDB Enterprise (remote) table, only compaction is + currently supported. Pruning old versions and index optimization + are silently skipped there instead of being attempted, so this + call returns successfully, with zeroed pruning statistics, once + the compaction job has been submitted; it does not wait for that + job to finish. Remote compaction supports per-job + ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``, + and ``batch_size``. Omitted fields inherit table tuning, then + deployment/built-in defaults. Other non-default compaction settings raise + ``NotImplementedError`` before submission. The server must support + these SQL options; older-server errors are propagated without + dropping the requested settings. + Modeled after ``VACUUM`` in PostgreSQL. Optimization covers three operations: @@ -7832,6 +8567,12 @@ class AsyncTable: async def list_indices(self) -> Iterable[IndexConfig]: """ List all indices that have been created with Self::create_index + + On LanceDB Enterprise tables, an index whose build hasn't finished may + be missing (vector indices) or listed with 0 indexed rows (scalar and + FTS indices), and ``num_unindexed_rows`` may be ``None``. Use + [wait_for_index][lancedb.table.AsyncTable.wait_for_index] to wait until + an index is ready. """ return await self._inner.list_indices() @@ -7848,7 +8589,7 @@ class AsyncTable: Specify exactly one of ``column`` or ``index_name``. Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are - rebuilt in the client process from index metadata. In LanceDB Distributed, + rebuilt in the client process from index metadata. In LanceDB Enterprise, this means the same tokenizer model files must also exist locally (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the server uses. A mismatch cannot be detected: the returned tokens may @@ -7965,6 +8706,7 @@ class IndexStatistics: "BTREE", "BITMAP", "LABEL_LIST", + "NGRAM", ] distance_type: Optional[Literal["l2", "cosine", "dot"]] = None num_indices: Optional[int] = None diff --git a/python/python/lancedb/types.py b/python/python/lancedb/types.py index 567eecb4e..3d7168dcf 100644 --- a/python/python/lancedb/types.py +++ b/python/python/lancedb/types.py @@ -51,6 +51,7 @@ IndexType = Literal[ "BTREE", "BITMAP", "LABEL_LIST", + "NGRAM", "IVF_RQ", ] diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index b1da5472a..ceb43522e 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -7,12 +7,9 @@ import subprocess import sys import textwrap -import lance -import pandas as pd import pyarrow as pa import pyarrow.compute as pc import pytest -from lance.blob import Blob, BlobType as LanceBlobType import lancedb from lancedb import schema as schema_module @@ -114,6 +111,7 @@ def _assert_fetch_apis_reject_missing_row_ids(table, row_ids): def test_blob_factory_declares_v2_field(): + LanceBlobType = pytest.importorskip("lance.blob").BlobType field = lancedb.blob("image") assert isinstance(field.type, pa.ExtensionType) assert field.type.extension_name == "lance.blob.v2" @@ -163,6 +161,8 @@ def test_blob_without_thresholds_has_no_threshold_metadata(): ], ) def test_blob_thresholds_match_pylance(monkeypatch, nullable, thresholds): + lance = pytest.importorskip("lance") + LanceBlobType = pytest.importorskip("lance.blob").BlobType expected = lance.blob_field("payload", nullable=nullable, **thresholds) actual = lancedb.blob("payload", nullable=nullable, **thresholds) assert type(actual.type) is LanceBlobType @@ -304,6 +304,7 @@ def test_local_schema_restores_blob_extensions(tmp_path, use_async, with_pylance def test_blob_resolves_pylance_type_without_eager_import(): + pytest.importorskip("lance.blob") script = textwrap.dedent( """\ import sys @@ -375,6 +376,7 @@ def test_blob_fallback_fails_if_name_already_registered(): def test_blob_type_rejects_competing_registration_with_pylance(): + pytest.importorskip("lance.blob") script = textwrap.dedent( """\ import pyarrow as pa @@ -515,6 +517,7 @@ def _nested_blob_table(db, name): def test_nested_blob_to_pandas_bytes(tmp_path): + pytest.importorskip("pandas") table = _nested_blob_table(lancedb.connect(tmp_path), "nested_pandas_bytes") expected = [ {"name": "first", "blob": b"hello"}, @@ -538,6 +541,9 @@ def test_nested_blob_to_pandas_bytes(tmp_path): assert table.search().select({"b": "info.blob"}).to_pandas(blob_mode="bytes")[ "b" ].tolist() == [b"hello", None, None] + assert table.search().select([]).to_pandas(blob_mode="bytes")["info"].tolist() == ( + table.search().select([]).to_arrow(blob_mode="bytes")["info"].to_pylist() + ) def test_to_arrow_and_to_list_blob_mode(tmp_path): @@ -573,9 +579,6 @@ def test_to_arrow_and_to_list_blob_mode(tmp_path): assert [ row["info"] for row in table.search().select([]).to_list(blob_mode="bytes") ] == expected - assert table.search().select([]).to_pandas(blob_mode="bytes")["info"].tolist() == ( - table.search().select([]).to_arrow(blob_mode="bytes")["info"].to_pylist() - ) assert "_rowid" not in table.search().select([]).to_arrow().column_names # A flat non-blob column named like the nested blob path keeps its values. shadowed = table.search().select({"info": "info", "info.blob": "id"}) @@ -694,6 +697,7 @@ def test_vector_query_to_arrow_blob_mode_bytes(tmp_path): @pytest.mark.asyncio async def test_nested_blob_to_pandas_bytes_async(tmp_path): + pytest.importorskip("pandas") db = await lancedb.connect_async(tmp_path) schema = pa.schema( [ @@ -809,6 +813,7 @@ def test_blob_query_explicit_row_id_opt_in(): def test_table_to_pandas_descriptions_mode_omits_row_id(): + pytest.importorskip("pandas") table = _blob_table("descriptions_no_leak", [{"id": 1, "image": b"x"}]) df = table.to_pandas(blob_mode="descriptions") descriptor = df["image"].iloc[0] @@ -818,6 +823,7 @@ def test_table_to_pandas_descriptions_mode_omits_row_id(): @pytest.mark.asyncio async def test_async_table_to_pandas_descriptions_mode_omits_row_id(): + pytest.importorskip("pandas") db = await lancedb.connect_async("memory:///") schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) table = await db.create_table("descriptions_no_leak_async", schema=schema) @@ -983,6 +989,7 @@ def test_to_batches_validates_blob_mode(): def test_to_pandas_keeps_to_arrow_overrides_without_blob_mode(): + pytest.importorskip("pandas") from lancedb.query import LanceEmptyQueryBuilder class ToArrowWithoutBlobMode(LanceEmptyQueryBuilder): @@ -1000,6 +1007,7 @@ def test_to_pandas_keeps_to_arrow_overrides_without_blob_mode(): def test_take_queries_honor_blob_mode(): + pytest.importorskip("pandas") table = _blob_table( "take_blob_mode", [{"id": 1, "image": b"one"}, {"id": 2, "image": b"two"}] ) @@ -1449,6 +1457,7 @@ def test_merge_insert_bytes_after_reopen_without_pylance(tmp_path): def test_merge_insert_blob_array_into_reopened_table(tmp_path): + pytest.importorskip("lance") db = lancedb.connect(tmp_path) schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) table = db.create_table("images", schema=schema) @@ -1624,6 +1633,8 @@ def test_row_addressable_paths_exclude_list_children(): def test_merge_insert_writes_pylance_blob_array(): + lance = pytest.importorskip("lance") + LanceBlobType = pytest.importorskip("lance.blob").BlobType table = _blob_table("merge_pylance", [{"id": 1, "image": b"before"}]) image = lance.blob_array([b"updated", b"inserted"]) assert type(image.type) is LanceBlobType @@ -2085,6 +2096,7 @@ def test_fetch_legacy_v1_blobs(): @pytest.mark.asyncio async def test_async_fetch_legacy_v1_blobs(tmp_path): + lance = pytest.importorskip("lance") table = _legacy_v1_table("legacy_async_source") # Open a dataset written by Lance independently of the LanceDB connection. lance.write_dataset( @@ -2193,6 +2205,7 @@ def _blob_query_shape(table, shape): @pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"]) @pytest.mark.parametrize("shape", ["scan", "vector", "fts", "hybrid"]) def test_blob_mode_for_every_query_shape(shape, blob_mode, with_row_id): + pytest.importorskip("pandas") table = _hybrid_blob_table(lancedb.connect("memory:///")) query = _blob_query_shape(table, shape).select(["id", "image"]).limit(2) if with_row_id is not None: @@ -2218,6 +2231,7 @@ def test_blob_mode_for_every_query_shape(shape, blob_mode, with_row_id): @pytest.mark.asyncio @pytest.mark.parametrize("shape", ["scan", "vector", "fts", "hybrid"]) async def test_async_blob_bytes_for_every_query_shape(shape): + pytest.importorskip("pandas") db = await lancedb.connect_async("memory:///") table = await _hybrid_blob_table_async(db) query = table.query() @@ -2750,13 +2764,15 @@ def test_add_external_blob_range_matches_storage_schema( table = db.create_table( "ranges", schema=pa.schema([pa.field("id", pa.int64()), field]) ) - value = ( - Blob.from_uri(blob_path.as_uri(), position=position, size=6) - if as_blob - else {"uri": blob_path.as_uri(), "position": position, "size": 6} - ) + if as_blob: + Blob = pytest.importorskip("lance.blob").Blob + value = Blob.from_uri(blob_path.as_uri(), position=position, size=6) + else: + value = {"uri": blob_path.as_uri(), "position": position, "size": 6} rows = [{"id": 1, "image": b"inline"}, {"id": 2, "image": value}] - data = pd.DataFrame(rows) if as_pandas else rows + data = rows + if as_pandas: + data = pytest.importorskip("pandas").DataFrame(rows) if minimal_schema: with pytest.raises(ValueError, match="Blob column 'image'.*storage schema"): @@ -2775,6 +2791,7 @@ def test_add_external_blob_range_matches_storage_schema( def test_add_minimal_blob_schema_preserves_whole_file_and_inline_values( tmp_path, as_pandas ): + Blob = pytest.importorskip("lance.blob").Blob payload = b"whole-file" blob_path = tmp_path / "payload.bin" blob_path.write_bytes(payload) @@ -2797,10 +2814,10 @@ def test_add_minimal_blob_schema_preserves_whole_file_and_inline_values( {"uri": uri, "position": None, "size": None}, ] rows = [{"id": i, "image": value} for i, value in enumerate(values)] - table.add( - pd.DataFrame(rows) if as_pandas else rows, - allow_external_blob_outside_bases=True, - ) + data = rows + if as_pandas: + data = pytest.importorskip("pandas").DataFrame(rows) + table.add(data, allow_external_blob_outside_bases=True) by_id = _row_ids_by_id(table) assert table.fetch_blobs( @@ -2828,10 +2845,10 @@ def test_add_bytes_and_uri_in_one_batch_preserves_external_uri(tmp_path, as_pand schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) table = db.create_table("mixed", schema=schema) - table.add( - pd.DataFrame(rows) if as_pandas else rows, - allow_external_blob_outside_bases=True, - ) + data = rows + if as_pandas: + data = pytest.importorskip("pandas").DataFrame(rows) + table.add(data, allow_external_blob_outside_bases=True) by_id = _row_ids_by_id(table) assert table.fetch_blobs("image", [by_id[1], by_id[2]]).to_pylist() == [ @@ -2842,6 +2859,7 @@ def test_add_bytes_and_uri_in_one_batch_preserves_external_uri(tmp_path, as_pand @pytest.mark.parametrize("as_pandas", [False, True]) def test_add_mixed_python_blob_values_preserves_external_uris(tmp_path, as_pandas): + Blob = pytest.importorskip("lance.blob").Blob payload = b"external-payload" blob_path = tmp_path / "payload.bin" blob_path.write_bytes(payload) @@ -2859,10 +2877,10 @@ def test_add_mixed_python_blob_values_preserves_external_uris(tmp_path, as_panda schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) table = db.create_table("mixed", schema=schema) - table.add( - pd.DataFrame(rows) if as_pandas else rows, - allow_external_blob_outside_bases=True, - ) + data = rows + if as_pandas: + data = pytest.importorskip("pandas").DataFrame(rows) + table.add(data, allow_external_blob_outside_bases=True) by_id = _row_ids_by_id(table) assert table.fetch_blobs("image", [by_id[i] for i in range(1, 8)]).to_pylist() == [ @@ -2886,18 +2904,22 @@ def test_merge_insert_mixed_python_blobs_validates_external_uri(tmp_path, as_pan {"id": 2, "image": blob_path.as_uri()}, ] + data = rows + if as_pandas: + data = pytest.importorskip("pandas").DataFrame(rows) with pytest.raises(ValueError, match="outside registered external bases"): ( table.merge_insert("id") .when_matched_update_all() .when_not_matched_insert_all() - .execute(pd.DataFrame(rows) if as_pandas else rows) + .execute(data) ) assert table.count_rows() == 1 @pytest.mark.parametrize("as_pandas", [False, True]) def test_merge_insert_python_blob_dicts_and_objects(as_pandas): + Blob = pytest.importorskip("lance.blob").Blob table = _blob_table("merge_python_blobs", [{"id": 1, "image": b"before"}]) rows = [ {"id": 1, "image": b"updated"}, @@ -2905,11 +2927,14 @@ def test_merge_insert_python_blob_dicts_and_objects(as_pandas): {"id": 3, "image": Blob.from_bytes(b"from-blob")}, ] + data = rows + if as_pandas: + data = pytest.importorskip("pandas").DataFrame(rows) result = ( table.merge_insert("id") .when_matched_update_all() .when_not_matched_insert_all() - .execute(pd.DataFrame(rows) if as_pandas else rows) + .execute(data) ) assert result.num_updated_rows == 1 @@ -2923,6 +2948,7 @@ def test_merge_insert_python_blob_dicts_and_objects(as_pandas): def test_create_table_with_python_blob_dict_and_object(): + Blob = pytest.importorskip("lance.blob").Blob db = lancedb.connect("memory:///") schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) table = db.create_table( @@ -2979,6 +3005,7 @@ def _openable_descriptors(table, *, by_address): def test_open_blob_files_preserve_snapshot_order_nulls_and_empty_values( tmp_path, by_address ): + pytest.importorskip("lance") db = lancedb.connect(str(tmp_path)) schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) table = db.create_table("videos", schema=schema) @@ -3049,6 +3076,7 @@ def test_open_blob_files_does_not_open_ahead(monkeypatch): @pytest.mark.asyncio async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path): + pytest.importorskip("lance") db = lancedb.connect(str(tmp_path)) table = db.create_table( "videos", diff --git a/python/python/tests/test_blob_array.py b/python/python/tests/test_blob_array.py index 9eb8221f0..7204e72e1 100644 --- a/python/python/tests/test_blob_array.py +++ b/python/python/tests/test_blob_array.py @@ -10,6 +10,8 @@ import pytest @pytest.mark.parametrize("with_pylance", [False, True]) def test_blob_array(with_pylance): + if with_pylance: + pytest.importorskip("lance") # Use fresh processes so each extension class can own Arrow's registry. script = textwrap.dedent( """\ diff --git a/python/python/tests/test_blob_query_without_pylance.py b/python/python/tests/test_blob_query_without_pylance.py index cd9fd73ee..a5ce6db44 100644 --- a/python/python/tests/test_blob_query_without_pylance.py +++ b/python/python/tests/test_blob_query_without_pylance.py @@ -11,6 +11,8 @@ import pytest @pytest.mark.parametrize("api", ["sync", "async"]) @pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"]) def test_blob_query_without_pylance(tmp_path, api, result): + if result == "pandas": + pytest.importorskip("pandas") script = """\ import importlib.abc import sys diff --git a/python/python/tests/test_doc_links.py b/python/python/tests/test_doc_links.py new file mode 100644 index 000000000..89f5a4e35 --- /dev/null +++ b/python/python/tests/test_doc_links.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import lancedb +from lancedb._lancedb import __version__ as _core_version, _append_doc_url, _doc_url +from lancedb.db import DBConnection +from lancedb.job import AsyncJob, Job +import pytest + + +def test_python_sdk_utm_content_and_doc_links(tmp_path): + compaction_url = _doc_url("compaction") + expected_content = f"utm_content=python-{_core_version}" + assert ( + compaction_url + == f"https://docs.lancedb.com/performance?utm_source=lancedb_sdk&utm_medium=warning&utm_campaign=compaction&{expected_content}#compaction-and-cleanup" + ) + + db = lancedb.connect(tmp_path) + with pytest.raises(NotImplementedError) as sql_exc: + db.execute_query("SELECT 1") + assert _doc_url("sql") in str(sql_exc.value) + + with pytest.raises(NotImplementedError) as gpu_exc: + db.list_gpu_classes() + assert _doc_url("gpu_classes") in str(gpu_exc.value) + + with pytest.raises(NotImplementedError) as job_exc: + db.open_job("job-1") + assert _doc_url("jobs") in str(job_exc.value) + + with pytest.raises(NotImplementedError) as secret_exc: + db.create_secret("s", "v") + assert _doc_url("secrets") in str(secret_exc.value) + + with pytest.raises(NotImplementedError) as view_exc: + db.create_view("v", "SELECT 1") + assert _doc_url("views") in str(view_exc.value) + + with pytest.raises(NotImplementedError) as mv_exc: + DBConnection.open_materialized_view(db, "mv") + assert _doc_url("materialized_views") in str(mv_exc.value) + + with pytest.raises(NotImplementedError) as create_mv_exc: + DBConnection.create_materialized_view(db, "mv", "SELECT 1") + assert _doc_url("materialized_views") in str(create_mv_exc.value) + + local_job = Job(AsyncJob(None)) + with pytest.raises(NotImplementedError) as events_exc: + local_job.events() + assert _doc_url("jobs") in str(events_exc.value) + + appended = _append_doc_url("Something failed.", "sql") + assert appended.endswith(f"See {_doc_url('sql')}") diff --git a/python/python/tests/test_e2e_remote_db.py b/python/python/tests/test_e2e_remote_db.py index 74d5cd7de..8b06943da 100644 --- a/python/python/tests/test_e2e_remote_db.py +++ b/python/python/tests/test_e2e_remote_db.py @@ -10,7 +10,7 @@ import lancedb import numpy as np import pyarrow as pa import pytest -from lancedb import LanceDBConnection +from lancedb import LanceDBConnection, function from lancedb.index import FTS # TODO: setup integ test mark and script @@ -74,6 +74,106 @@ def test_json_fts_against_server(): conn.drop_table(name) +@pytest.mark.skipif( + not os.environ.get("LANCEDB_URI"), + reason="Set LANCEDB_URI to a server with Python Functions enabled", +) +def test_function_execution_controls_through_sql_and_materialized_view(): + """Exercise registered batch controls through the real remote runtime. + + The Function returns the input batch length for every row. A cap of two must + therefore produce only one- or two-element observations in both a direct + SELECT and a materialized view refreshed after an append. + """ + suffix = uuid4().hex[:12] + conn = lancedb.connect( + uri=os.environ["LANCEDB_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"), + ) + function_name = f"batch_probe_{suffix}" + source_name = f"batch_probe_source_{suffix}" + view_name = f"batch_probe_view_{suffix}" + registered_version = None + + @function( + name=function_name, + input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + output_schema=pa.int64(), + batch_size=2, + row_timeout_seconds=15, + ) + def observed_batch(value: pa.Array) -> pa.Array: + size = len(value) + return pa.array([size] * size, type=pa.int64()) + + def row_batch_sizes(table_name): + rows = ( + conn.execute_query( + f"SELECT {function_name}(value) AS observed FROM {table_name}" + ) + .read_all() + .to_pylist() + ) + return [row["observed"] for row in rows] + + def drop_table_if_present(table_name): + try: + conn.drop_table(table_name) + except Exception: + pass + + try: + table = conn.create_table( + source_name, + pa.table( + {"value": pa.array(range(8), type=pa.int64())}, + schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + ), + ) + registered_version = conn.create_function(observed_batch, namespace_path=None) + + direct = row_batch_sizes(source_name) + assert len(direct) == 8 + assert all(1 <= size <= 2 for size in direct) + + view = conn.create_materialized_view( + view_name, + source=source_name, + select=[("observed", f"{function_name}(value)")], + ) + initial_view = [ + row["observed"] + for row in view.table.search().select(["observed"]).to_list() + ] + assert len(initial_view) == 8 + assert all(1 <= size <= 2 for size in initial_view) + + table.add( + pa.table( + {"value": pa.array(range(8, 12), type=pa.int64())}, + schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + ) + ) + view.refresh() + refreshed = [ + row["observed"] + for row in view.table.search().select(["observed"]).to_list() + ] + assert len(refreshed) == 12 + assert all(1 <= size <= 2 for size in refreshed) + finally: + drop_table_if_present(view_name) + drop_table_if_present(source_name) + if registered_version is not None: + try: + conn.drop_function(function_name, version=registered_version.version) + except Exception: + pass + + @pytest.mark.skip(reason="Need to set up a local server") def test_against_local_server(): conn = LanceDBConnection("lancedb+http://localhost:10024") diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index 5eb3f095c..e9fb56c8a 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -2337,6 +2337,13 @@ def _failing_transform(bad_ids: set): return transform +def _fill_workers_transform(batch: pa.RecordBatch) -> list[dict]: + ids = batch.column("id").to_pylist() + if 0 in ids or 60 in ids: + raise BadRowError("bad row") + return [{"id": row_id} for row_id in ids] + + def _sequential_split_members(table) -> list[list[int]]: """Return each split's ids in yield order for shuffle=False. @@ -2367,6 +2374,115 @@ def test_on_transform_error_invalid_value(lance_table): StreamingDataset(lance_table, num_splits=NUM_SPLITS, on_transform_error="bogus") +def test_on_transform_error_fill_requires_one_replacement(lance_table): + kwargs = dict(num_splits=NUM_SPLITS, on_transform_error="fill") + with pytest.raises(ValueError, match="exactly one"): + StreamingDataset(lance_table, **kwargs) + with pytest.raises(ValueError, match="exactly one"): + StreamingDataset( + lance_table, **kwargs, fill_value={"id": -1}, repair=lambda exc, row: row + ) + with pytest.raises(ValueError, match="require on_transform_error='fill'"): + StreamingDataset(lance_table, num_splits=NUM_SPLITS, fill_value=None) + StreamingDataset(lance_table, **kwargs, fill_value=None) + + +def test_on_transform_error_fill_preserves_rows_and_positions(lance_table): + """Uneven failures are replaced in place, including an entirely bad split.""" + members = _sequential_split_members(lance_table) + bad_ids = set(members[0]) | {members[5][7]} + clean = [ + row["id"] + for row in StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + ] + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle=False, + transform=_failing_transform(bad_ids), + on_transform_error="fill", + fill_value={"id": -1, "vector": [0.0, 0.0]}, + ) + assert ds.rows_filled == 0 + rows = list(ds) + assert [row["id"] for row in rows] == [ + -1 if row_id in bad_ids else row_id for row_id in clean + ] + assert len(rows) == NUM_ROWS + assert ds.rows_filled == len(bad_ids) + assert ds.rows_skipped == 0 + + placeholders = [row for row in rows if row["id"] == -1] + placeholders[0]["vector"][0] = 1.0 + assert all(row["vector"] == [0.0, 0.0] for row in placeholders[1:]) + + +def test_on_transform_error_fill_repair_receives_failed_row(lance_table): + bad_ids = {5, 17, 46} + repaired = [] + + def repair(exc: Exception, row_batch: pa.RecordBatch) -> dict: + assert isinstance(exc, BadRowError) + assert row_batch.num_rows == 1 + row_id = row_batch.column("id")[0].as_py() + repaired.append(row_id) + return {"id": row_id, "repaired": True} + + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle=False, + transform=_failing_transform(bad_ids), + on_transform_error="fill", + repair=repair, + ) + rows = list(ds) + assert sorted(row["id"] for row in rows) == list(range(NUM_ROWS)) + assert set(repaired) == bad_ids + assert {row["id"] for row in rows if row.get("repaired")} == bad_ids + assert ds.rows_filled == len(bad_ids) + + +def test_on_transform_error_fill_repair_error_propagates(lance_table): + def broken_repair(exc: Exception, row_batch: pa.RecordBatch): + raise RuntimeError("repair failed") + + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + transform=_failing_transform({5}), + on_transform_error="fill", + repair=broken_repair, + ) + with pytest.raises(RuntimeError, match="repair failed"): + list(ds) + + +def test_on_transform_error_fill_counts_across_workers(lance_table): + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle=False, + transform=_fill_workers_transform, + on_transform_error="fill", + fill_value={"id": -1}, + ) + loader = StreamingDataLoader( + ds, + batch_size=6, + num_workers=2, + multiprocessing_context="spawn", + ) + iterator = iter(loader) + try: + ids = [row_id for batch in iterator for row_id in batch["id"].tolist()] + finally: + iterator._shutdown_workers() + assert len(ids) == NUM_ROWS + assert ids.count(-1) == 2 + assert ds.rows_filled == 2 + + def test_on_transform_error_skip_drops_bad_rows(lance_table): """With one bad row per split, 'skip' yields every good row exactly once and counts the dropped rows in rows_skipped.""" @@ -2471,9 +2587,10 @@ def test_on_transform_error_callable_selective(lance_table): list(ds2) -def test_transform_wrong_row_count_raises(lance_table): +@pytest.mark.parametrize("on_error", ["skip", "fill"]) +def test_transform_wrong_row_count_raises(lance_table, on_error): """A transform that returns the wrong number of rows is an error even with - on_transform_error='skip' — silent shrinkage would corrupt accounting.""" + error recovery enabled — silent shrinkage would corrupt accounting.""" def drops_rows(batch: pa.RecordBatch) -> list: return batch.column("id").to_pylist()[:-1] @@ -2483,7 +2600,8 @@ def test_transform_wrong_row_count_raises(lance_table): num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED, transform=drops_rows, - on_transform_error="skip", + on_transform_error=on_error, + **({"fill_value": {"id": -1}} if on_error == "fill" else {}), ) with pytest.raises(ValueError, match="one output row per input row"): list(ds) @@ -2561,6 +2679,61 @@ def test_skip_elastic_det_across_world_sizes(lance_table): assert collect(ws) == reference, f"world_size={ws} diverged" +def test_fill_elastic_determinism_and_checkpoint(lance_table): + """Uneven fills keep every global step and resume across world sizes.""" + members = _sequential_split_members(lance_table) + bad_ids = {members[0][0], members[0][2], members[6][1]} + kwargs = dict( + num_splits=NUM_SPLITS, + shuffle=False, + transform=_failing_transform(bad_ids), + on_transform_error="fill", + fill_value={"id": -1}, + ) + reference = [row["id"] for row in StreamingDataset(lance_table, **kwargs)] + ref_steps = [ + sorted(reference[start : start + GLOBAL_BATCH_SIZE]) + for start in range(0, len(reference), GLOBAL_BATCH_SIZE) + ] + assert len(ref_steps) == STEPS_PER_EPOCH + + for world_size in (1, 2, 3, 4): + micro = GLOBAL_BATCH_SIZE // world_size + datasets = [ + StreamingDataset(lance_table, rank=rank, world_size=world_size, **kwargs) + for rank in range(world_size) + ] + iters = [iter(ds) for ds in datasets] + steps = [ + sorted(next(it)["id"] for it in iters for _ in range(micro)) + for _ in range(STEPS_PER_EPOCH) + ] + assert steps == ref_steps + assert all(next(it, None) is None for it in iters) + + world_size = 2 + micro = GLOBAL_BATCH_SIZE // world_size + datasets = [ + StreamingDataset(lance_table, rank=rank, world_size=world_size, **kwargs) + for rank in range(world_size) + ] + iters = [iter(ds) for ds in datasets] + for _ in range(3): + for it in iters: + for _ in range(micro): + next(it) + states = [ds.state_dict() for ds in datasets] + for it in iters: + it.close() + merged = StreamingDataset.merge_state_dicts(states) + assert merged["positions_consumed_per_split"] == [3] * NUM_SPLITS + assert merged["samples_consumed_per_split"] == [3] * NUM_SPLITS + + resumed = StreamingDataset(lance_table, **kwargs) + resumed.load_state_dict(merged) + assert [row["id"] for row in resumed] == reference[3 * NUM_SPLITS :] + + def test_resumability_with_skips_same_topology(lance_table): """Checkpointing mid-epoch with skipped rows resumes exactly: no sample repeated, no sample lost, skipped rows stay skipped.""" @@ -3495,6 +3668,7 @@ def test_default_checkpoint_resumes_after_compaction(lance_table): on this path -- instead of relying on shuffle_seed/num_splits alone, as it does -- would reject this resume even though the seeded permutation itself is unchanged.""" + pytest.importorskip("lance") lance_table.add(pa.table({"id": [NUM_ROWS]})) # a second fragment to compact ds = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED) diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 32503c04f..78cd76ad2 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -33,6 +33,78 @@ def mock_embed_func(input_data): return [np.random.randn(128).tolist() for _ in range(len(input_data))] +@pytest.fixture +def embedding_schema(): + func = MockTextEmbeddingFunction.create() + + class Doc(LanceModel): + id: int + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + return Doc + + +@pytest.mark.parametrize("column", ["text", "vector", "`text`", "`vector`"]) +@pytest.mark.parametrize("operation", ["rename", "drop"]) +def test_embedding_columns_schema_evolution( + tmp_path, embedding_schema, column, operation +): + db = lancedb.connect(tmp_path) + table = db.create_table("docs", schema=embedding_schema) + table.add([{"id": 1, "text": "hello"}]) + schema, version = table.schema, table.version + + with pytest.raises(ValueError, match="used by an embedding function"): + if operation == "rename": + table.alter_columns( + {"path": "id", "rename": "doc_id"}, + {"path": column, "rename": "renamed"}, + ) + else: + table.drop_columns(["id", column]) + + assert table.schema == schema + assert table.version == version + assert table.embedding_functions["vector"].source_column == "text" + reopened = db.open_table("docs") + reopened.add([{"id": 2, "text": "world"}]) + assert reopened.count_rows() == 2 + assert reopened.to_arrow()["vector"].null_count == 0 + + # Columns outside the embedding binding can still evolve. + reopened.alter_columns({"path": "id", "rename": "doc_id"}) + reopened.drop_columns(["doc_id"]) + reopened.add([{"text": "again"}]) + assert reopened.count_rows() == 3 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("column", ["text", "vector"]) +@pytest.mark.parametrize("operation", ["rename", "drop"]) +async def test_async_embedding_columns_schema_evolution( + tmp_path, embedding_schema, column, operation +): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("docs", schema=embedding_schema) + await table.add([{"id": 1, "text": "hello"}]) + schema, version = await table.schema(), await table.version() + + with pytest.raises(ValueError, match="used by an embedding function"): + if operation == "rename": + await table.alter_columns({"path": column, "rename": "renamed"}) + else: + await table.drop_columns([column]) + + assert await table.schema() == schema + assert await table.version() == version + assert (await table.embedding_functions())["vector"].source_column == "text" + reopened = await db.open_table("docs") + await reopened.add([{"id": 2, "text": "world"}]) + assert await reopened.count_rows() == 2 + assert (await reopened.to_arrow())["vector"].null_count == 0 + + def test_embedding_function(tmp_path): registry = EmbeddingFunctionRegistry.get_instance() @@ -602,6 +674,51 @@ def test_openai_propagates_api_key(monkeypatch): assert len(actual.text) > 0 +@pytest.mark.parametrize("base_url", [None, "http://localhost:11434/v1"]) +def test_openai_compatible_model_uses_dim_for_ndims(base_url): + # Unlisted model names use the explicit dimension independently of base_url. + openai = get_registry().get("openai") + func = openai.create( + name="nomic-embed-text", + base_url=base_url, + dim=768, + ) + assert func.ndims() == 768 + + class Schema(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + schema = Schema.to_arrow_schema() + assert schema.field("vector").type == pa.list_(pa.float32(), 768) + + +def test_openai_unknown_model_without_dim_raises_clear_error(): + openai = get_registry().get("openai") + func = openai.create( + name="nomic-embed-text", + base_url="http://localhost:11434/v1", + ) + with pytest.raises(ValueError, match="dim"): + func.ndims() + + +@pytest.mark.parametrize( + ("name", "dim", "expected_dim"), + [ + ("text-embedding-ada-002", None, 1536), + ("text-embedding-ada-002", 512, 1536), + ("text-embedding-3-large", None, 3072), + ("text-embedding-3-large", 1024, 1024), + ("text-embedding-3-small", None, 1536), + ("text-embedding-3-small", 512, 512), + ], +) +def test_openai_known_model_ndims(name, dim, expected_dim): + func = get_registry().get("openai").create(name=name, dim=dim) + assert func.ndims() == expected_dim + + @patch("time.sleep") def test_openai_no_retry_on_401(mock_sleep): """ diff --git a/python/python/tests/test_embeddings_oci_genai.py b/python/python/tests/test_embeddings_oci_genai.py new file mode 100644 index 000000000..01d9bf020 --- /dev/null +++ b/python/python/tests/test_embeddings_oci_genai.py @@ -0,0 +1,351 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Unit tests for the OCI Generative AI embedding function. + +The ``oci`` SDK is replaced with a small fake so these run without the package +or cloud credentials. Live coverage lives in ``test_embeddings_slow.py``. +""" + +import os +import pickle +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import lancedb +import pytest +from lancedb.embeddings import OCIGenAIEmbeddings, get_registry +from lancedb.embeddings.oci_genai import EMBEDDING_BATCH_SIZE, OCIGenAIServiceError +from lancedb.pydantic import LanceModel, Vector +from pydantic import ValidationError + +DIMS = 8 +COMPARTMENT = "ocid1.compartment.oc1..test" + + +class FakeServiceError(Exception): + """Mimics ``oci.exceptions.ServiceError``.""" + + def __init__(self, status, code, message): + super().__init__(message) + self.status = status + self.code = code + self.message = message + + +def _fake_embed_text(details): + # Deterministic embeddings: first component encodes len(text) so ordering + # and nearest-neighbour behaviour can be asserted. + embeddings = [[float(len(text))] + [0.0] * (DIMS - 1) for text in details.inputs] + return SimpleNamespace(data=SimpleNamespace(embeddings=embeddings)) + + +@pytest.fixture +def fake_oci(): + """Stand-in for the ``oci`` package, injected via attempt_import_or_raise.""" + oci = MagicMock(name="oci") + oci.exceptions.ServiceError = FakeServiceError + models = oci.generative_ai_inference.models + models.EmbedTextDetails.side_effect = lambda **kw: SimpleNamespace(**kw) + models.OnDemandServingMode.side_effect = lambda **kw: SimpleNamespace( + serving_type="ON_DEMAND", **kw + ) + models.DedicatedServingMode.side_effect = lambda **kw: SimpleNamespace( + serving_type="DEDICATED", **kw + ) + oci.config.from_file.return_value = {"key_file": "~/.oci/key.pem"} + client = oci.generative_ai_inference.GenerativeAiInferenceClient.return_value + client.embed_text.side_effect = _fake_embed_text + with patch( + "lancedb.embeddings.oci_genai.attempt_import_or_raise", return_value=oci + ): + yield oci + + +def _create(**kwargs): + kwargs.setdefault("compartment_id", COMPARTMENT) + kwargs.setdefault("max_retries", 0) + return get_registry().get("oci-genai").create(**kwargs) + + +def _client(fake_oci): + return fake_oci.generative_ai_inference.GenerativeAiInferenceClient.return_value + + +def _client_kwargs(fake_oci): + return fake_oci.generative_ai_inference.GenerativeAiInferenceClient.call_args.kwargs + + +def _embed_requests(fake_oci): + return [call.args[0] for call in _client(fake_oci).embed_text.call_args_list] + + +def test_oci_genai_registered(): + assert get_registry().get("oci-genai") is OCIGenAIEmbeddings + assert "cohere.embed-v4.0" in OCIGenAIEmbeddings.model_names() + func = _create() + assert func.name == "cohere.embed-v4.0" + assert func.auth_type == "API_KEY" + assert func.truncate == "END" + assert func.sensitive_keys() == [] + + +def test_oci_genai_service_endpoint(fake_oci): + default = _create() + assert default.endpoints() == [] + default._client + assert ( + _client_kwargs(fake_oci)["service_endpoint"] + == "https://inference.generativeai.us-chicago-1.oci.oraclecloud.com" + ) + + regional = _create(region="eu-frankfurt-1") + regional_endpoint = ( + "https://inference.generativeai.eu-frankfurt-1.oci.oraclecloud.com" + ) + assert regional.endpoints() == [regional_endpoint] + regional._client + assert _client_kwargs(fake_oci)["service_endpoint"] == regional_endpoint + + custom = "https://inference.generativeai.us-langley-1.oci.oraclegovcloud.com" + explicit = _create(region="us-chicago-1", service_endpoint=custom) + assert explicit.endpoints() == [custom] + explicit._client + assert _client_kwargs(fake_oci)["service_endpoint"] == custom + + +def test_oci_genai_client_disables_sdk_retries(fake_oci): + _create()._client + kwargs = _client_kwargs(fake_oci) + assert kwargs["retry_strategy"] is fake_oci.retry.NoneRetryStrategy.return_value + + +def test_oci_genai_api_key_auth(fake_oci, tmp_path): + config_file = str(tmp_path / "config") + func = _create(auth_profile="MYPROFILE", auth_file_location=config_file) + func._client + fake_oci.config.from_file.assert_called_once_with( + file_location=config_file, profile_name="MYPROFILE" + ) + kwargs = _client_kwargs(fake_oci) + assert kwargs["config"] is fake_oci.config.from_file.return_value + assert "signer" not in kwargs + + +def test_oci_genai_api_key_rejects_session_profile(fake_oci): + fake_oci.config.from_file.return_value = { + "key_file": "~/.oci/sessions/x/key.pem", + "security_token_file": "~/.oci/sessions/x/token", + } + with pytest.raises(ValueError, match="SECURITY_TOKEN"): + _create(auth_type="API_KEY")._client + + +def test_oci_genai_security_token_auth(fake_oci, tmp_path): + token_file = tmp_path / "token" + token_file.write_text("session-token\n") + fake_oci.config.from_file.return_value = { + "key_file": "~/.oci/sessions/x/key.pem", + "security_token_file": str(token_file), + } + _create(auth_type="SECURITY_TOKEN", auth_profile="SESSION")._client + + fake_oci.signer.load_private_key_from_file.assert_called_once_with( + os.path.expanduser("~/.oci/sessions/x/key.pem"), None + ) + fake_oci.auth.signers.SecurityTokenSigner.assert_called_once_with( + "session-token", fake_oci.signer.load_private_key_from_file.return_value + ) + kwargs = _client_kwargs(fake_oci) + assert kwargs["signer"] is fake_oci.auth.signers.SecurityTokenSigner.return_value + assert kwargs["config"] is fake_oci.config.from_file.return_value + + +def test_oci_genai_security_token_requires_token_file(fake_oci): + with pytest.raises(ValueError, match="security_token_file"): + _create(auth_type="SECURITY_TOKEN")._client + + +@pytest.mark.parametrize( + "auth_type,factory", + [ + ("INSTANCE_PRINCIPAL", "InstancePrincipalsSecurityTokenSigner"), + ("RESOURCE_PRINCIPAL", "get_resource_principals_signer"), + ], +) +def test_oci_genai_principal_auth(fake_oci, auth_type, factory): + _create(auth_type=auth_type)._client + signer_factory = getattr(fake_oci.auth.signers, factory) + signer_factory.assert_called_once_with() + kwargs = _client_kwargs(fake_oci) + assert kwargs["config"] == {} + assert kwargs["signer"] is signer_factory.return_value + fake_oci.config.from_file.assert_not_called() + + +def test_oci_genai_rejects_invalid_config(): + with pytest.raises(ValidationError, match="auth_type"): + _create(auth_type="PASSWORD") + with pytest.raises(ValidationError, match="truncate"): + _create(truncate="MIDDLE") + + +def test_oci_genai_compartment_id_required(fake_oci, monkeypatch): + monkeypatch.delenv("OCI_COMPARTMENT_ID", raising=False) + func = get_registry().get("oci-genai").create(max_retries=0) + with pytest.raises(ValueError, match="OCI_COMPARTMENT_ID"): + func.compute_source_embeddings(["hello"]) + assert _embed_requests(fake_oci) == [] + + monkeypatch.setenv("OCI_COMPARTMENT_ID", "ocid1.compartment.oc1..from-env") + func.compute_source_embeddings(["hello"]) + assert _embed_requests(fake_oci)[0].compartment_id == ( + "ocid1.compartment.oc1..from-env" + ) + + +def test_oci_genai_request_shape(fake_oci): + func = _create(name="cohere.embed-multilingual-v3.0", truncate="START") + func.compute_source_embeddings(["hello"]) + (details,) = _embed_requests(fake_oci) + assert details.inputs == ["hello"] + assert details.compartment_id == COMPARTMENT + assert details.truncate == "START" + assert details.input_type == "SEARCH_DOCUMENT" + assert details.serving_mode.serving_type == "ON_DEMAND" + assert details.serving_mode.model_id == "cohere.embed-multilingual-v3.0" + # only sent when configured so older SDKs / models keep working + assert not hasattr(details, "output_dimensions") + + +def test_oci_genai_dedicated_endpoint(fake_oci): + endpoint = "ocid1.generativeaiendpoint.oc1.us-chicago-1.test" + _create(name=endpoint).compute_source_embeddings(["hello"]) + (details,) = _embed_requests(fake_oci) + assert details.serving_mode.serving_type == "DEDICATED" + assert details.serving_mode.endpoint_id == endpoint + + +def test_oci_genai_query_and_source_input_types(fake_oci): + func = _create() + func.compute_source_embeddings(["a document"]) + func.compute_query_embeddings("a query") + source, query = _embed_requests(fake_oci) + assert source.input_type == "SEARCH_DOCUMENT" + assert query.input_type == "SEARCH_QUERY" + + custom = _create(source_input_type="CLUSTERING", query_input_type="CLASSIFICATION") + custom.compute_source_embeddings(["a document"]) + custom.compute_query_embeddings("a query") + source, query = _embed_requests(fake_oci)[2:] + assert source.input_type == "CLUSTERING" + assert query.input_type == "CLASSIFICATION" + + +def test_oci_genai_batches_at_service_limit(fake_oci): + assert EMBEDDING_BATCH_SIZE == 96 + texts = [f"text {i:03d}" for i in range(2 * EMBEDDING_BATCH_SIZE + 8)] + embeddings = _create().compute_source_embeddings(texts) + + requests = _embed_requests(fake_oci) + assert [len(r.inputs) for r in requests] == [96, 96, 8] + assert [t for r in requests for t in r.inputs] == texts + assert all(r.input_type == "SEARCH_DOCUMENT" for r in requests) + assert len(embeddings) == len(texts) + assert [e[0] for e in embeddings] == [float(len(t)) for t in texts] + + +def test_oci_genai_empty_inputs_are_skipped(fake_oci): + func = _create() + assert func.compute_source_embeddings([]) == [] + assert _embed_requests(fake_oci) == [] + + embeddings = func.compute_source_embeddings(["hello", "", None, "world"]) + (details,) = _embed_requests(fake_oci) + assert details.inputs == ["hello", "world"] + assert embeddings[1] is None + assert embeddings[2] is None + assert embeddings[0][0] == 5.0 + assert embeddings[3][0] == 5.0 + + +def test_oci_genai_ndims_probe_is_cached(fake_oci): + func = _create() + assert func.ndims() == DIMS + assert func.ndims() == DIMS + assert len(_embed_requests(fake_oci)) == 1 + + +def test_oci_genai_output_dimensions(fake_oci): + func = _create(output_dimensions=512) + assert func.ndims() == 512 + assert _embed_requests(fake_oci) == [] # no probe request needed + + func.compute_source_embeddings(["hello"]) + (details,) = _embed_requests(fake_oci) + assert details.output_dimensions == 512 + + +@patch("time.sleep") +def test_oci_genai_auth_errors_are_not_retried(mock_sleep, fake_oci): + _client(fake_oci).embed_text.side_effect = FakeServiceError( + 401, "NotAuthenticated", "The required information was not provided." + ) + func = _create(max_retries=3) + with pytest.raises(OCIGenAIServiceError, match="HTTP 401") as exc_info: + func.compute_source_embeddings_with_retry(["hello"]) + + assert exc_info.value.status_code == 401 + assert "oci session authenticate" in str(exc_info.value) + assert isinstance(exc_info.value.__cause__, FakeServiceError) + assert _client(fake_oci).embed_text.call_count == 1 + mock_sleep.assert_not_called() + + +@patch("time.sleep") +def test_oci_genai_server_errors_are_retried(mock_sleep, fake_oci): + _client(fake_oci).embed_text.side_effect = FakeServiceError( + 500, "InternalError", "try again" + ) + func = _create(max_retries=2) + with pytest.raises(Exception, match="Maximum number of retries"): + func.compute_source_embeddings_with_retry(["hello"]) + assert _client(fake_oci).embed_text.call_count == 3 + + +def test_oci_genai_pickle_after_client_created(fake_oci): + func = _create(auth_profile="MYPROFILE") + func.compute_source_embeddings(["hello"]) + assert "_client" in func.__dict__ + + restored = pickle.loads(pickle.dumps(func)) + assert "_client" not in restored.__dict__ + assert restored.compartment_id == COMPARTMENT + assert restored.auth_profile == "MYPROFILE" + + +def test_oci_genai_table_round_trip(fake_oci): + func = _create(region="us-ashburn-1", auth_profile="MYPROFILE") + + class Docs(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + db = lancedb.connect("memory://") + tbl = db.create_table("docs", schema=Docs, mode="overwrite") + tbl.add([{"text": "hello"}, {"text": "goodbye world"}]) + assert len(tbl.to_arrow()["vector"][0].as_py()) == DIMS + + # the fake embeds len(text), so an equally long query lands on that row + hits = tbl.search("goodbye world").limit(1).to_arrow() + assert hits["text"][0].as_py() == "goodbye world" + assert _embed_requests(fake_oci)[-1].input_type == "SEARCH_QUERY" + + parsed = tbl.embedding_functions["vector"].function + assert isinstance(parsed, OCIGenAIEmbeddings) + assert parsed.safe_model_dump() == { + "compartment_id": COMPARTMENT, + "max_retries": 0, + "region": "us-ashburn-1", + "auth_profile": "MYPROFILE", + } diff --git a/python/python/tests/test_embeddings_slow.py b/python/python/tests/test_embeddings_slow.py index 4de85070f..c2d26ec5e 100644 --- a/python/python/tests/test_embeddings_slow.py +++ b/python/python/tests/test_embeddings_slow.py @@ -379,6 +379,58 @@ def test_bedrock_embedding(tmp_path): assert len(tbl.to_pandas()["vector"][0]) == model.ndims() +@pytest.mark.slow +@pytest.mark.skipif( + os.environ.get("OCI_COMPARTMENT_ID") is None, reason="OCI_COMPARTMENT_ID not set" +) +@pytest.mark.parametrize( + "model_name,output_dimensions,expected_dims", + [ + ("cohere.embed-v4.0", None, 1536), + ("cohere.embed-v4.0", 512, 512), + ("cohere.embed-multilingual-v3.0", None, 1024), + ], +) +def test_oci_genai_embedding(model_name, output_dimensions, expected_dims, tmp_path): + pytest.importorskip("oci") + # compartment_id comes from OCI_COMPARTMENT_ID; the profile / auth follow the + # OCI CLI's own OCI_CLI_PROFILE / OCI_CLI_AUTH / OCI_CLI_REGION variables so + # both API keys and `oci session authenticate` sessions work. + security_token = os.environ.get("OCI_CLI_AUTH") == "security_token" + model = ( + get_registry() + .get("oci-genai") + .create( + name=model_name, + output_dimensions=output_dimensions, + auth_type="SECURITY_TOKEN" if security_token else "API_KEY", + auth_profile=os.environ.get("OCI_CLI_PROFILE", "DEFAULT"), + region=os.environ.get("OCI_CLI_REGION", "us-chicago-1"), + max_retries=0, + ) + ) + assert model.ndims() == expected_dims + + class TextModel(LanceModel): + text: str = model.SourceField() + vector: Vector(model.ndims()) = model.VectorField() + + db = lancedb.connect(tmp_path) + tbl = db.create_table("oci_genai_test", schema=TextModel, mode="overwrite") + df = pd.DataFrame( + {"text": ["hello world", "goodbye world", "a recipe for lasagna", ""]} + ) + tbl.add(df, on_bad_vectors="null") + + tb = tbl.to_arrow() + assert tb.schema.field_by_name("vector").type == pa.list_( + pa.float32(), expected_dims + ) + # the empty input is not sent to the service and is stored as null + assert tb["vector"].is_null().to_pylist() == [False, False, False, True] + assert tbl.search("hello").limit(1).to_pandas()["text"][0] == "hello world" + + @pytest.mark.slow @pytest.mark.skipif( os.environ.get("OPENAI_API_KEY") is None, reason="OPENAI_API_KEY not set" diff --git a/python/python/tests/test_embeddings_trust.py b/python/python/tests/test_embeddings_trust.py index 92221c898..5eaed15a6 100644 --- a/python/python/tests/test_embeddings_trust.py +++ b/python/python/tests/test_embeddings_trust.py @@ -15,6 +15,7 @@ import pyarrow as pa import pytest from lancedb.embeddings import ( EmbeddingFunctionConfig, + OCIGenAIEmbeddings, OllamaEmbeddings, OpenAIEmbeddings, SentenceTransformerEmbeddings, @@ -220,6 +221,9 @@ def test_trusting_one_model_does_not_trust_a_swapped_name(): ATTACKER_URL = "https://attacker.example/v1" +OCI_REGION_ENDPOINT = ( + "https://inference.generativeai.eu-frankfurt-1.oci.oraclecloud.com" +) @pytest.mark.parametrize( @@ -247,6 +251,31 @@ def test_default_endpoints_need_no_allowlist(): ) +@pytest.mark.parametrize( + "model,endpoint", + [ + ({"service_endpoint": ATTACKER_URL}, ATTACKER_URL), + ({"region": "eu-frankfurt-1"}, OCI_REGION_ENDPOINT), + ], +) +def test_restored_oci_custom_endpoint_requires_allowlist(model, endpoint): + func = restore("oci-genai", model) + assert isinstance(func, UntrustedEmbeddingFunction) + with pytest.raises(UntrustedEmbeddingConfigError, match="allow_endpoint"): + func.compute_query_embeddings("hello") + + get_registry().allow_endpoint(endpoint) + restored = restore("oci-genai", model) + assert isinstance(restored, OCIGenAIEmbeddings) + assert restored.endpoints() == [endpoint] + + +def test_restored_oci_default_endpoint_needs_no_allowlist(): + func = restore("oci-genai", {}) + assert isinstance(func, OCIGenAIEmbeddings) + assert func.endpoints() == [] + + def test_endpoint_allowlist_ignores_trailing_slash(): get_registry().allow_endpoint("http://my-host:11434/") assert isinstance( diff --git a/python/python/tests/test_errors.py b/python/python/tests/test_errors.py index 0e362e5d8..12a193074 100644 --- a/python/python/tests/test_errors.py +++ b/python/python/tests/test_errors.py @@ -4,9 +4,22 @@ import pickle import pytest +from lance_namespace.errors import ErrorCode +from lance_namespace.errors import TableNotFoundError as NamespaceTableNotFoundError from lancedb.db import DBConnection -from lancedb.remote.errors import HttpError, LanceDBClientError, RetryError +from lancedb.remote.errors import ( + AlreadyExistsError, + ConflictError, + FunctionNotFoundError, + HttpError, + LanceDBClientError, + NamespaceNotFoundError, + ResponseInterruptedError, + RetryError, + SecretNotFoundError, + TableNotFoundError, +) from lancedb.table import Table @@ -50,6 +63,150 @@ def test_pickle_http_error(): assert str(restored) == "not found" assert restored.request_id == "req-789" assert restored.status_code == 404 + assert restored.is_transport_error is False + + +def test_pickle_http_transport_error(): + err = HttpError("connection reset", "req-789", is_transport_error=True) + restored = pickle.loads(pickle.dumps(err)) + assert isinstance(restored, HttpError) + assert restored.is_transport_error is True + assert restored.request_id == "req-789" + + +def test_pickle_response_interrupted_error(): + err = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7, True) + restored = pickle.loads(pickle.dumps(err)) + assert type(restored) is ResponseInterruptedError + assert str(restored) == "interrupted" + assert restored.request_id == "req-1" + assert (restored.batches, restored.rows, restored.table_version) == (2, 2048, 7) + assert restored.is_transport_error is True + assert restored.status_code is None + + +@pytest.mark.parametrize("error_code", [None, "conflict", "future_conflict_code"]) +def test_http_conflict_error_preserves_reason_and_metadata(error_code): + reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files" + original = HttpError(reason, "req-conflict", 409, error_code) + for error in [original, pickle.loads(pickle.dumps(original))]: + assert type(error) is ConflictError + assert isinstance(error, HttpError) + assert str(error) == reason + assert error.request_id == "req-conflict" + assert error.status_code == 409 + assert error.error_code == error_code + assert error.is_transport_error is False + + +@pytest.mark.parametrize( + "error_code,resource_kind,status_code,expected_type", + [ + ("not_found", "secret", 404, SecretNotFoundError), + ("not_found", "function", 404, FunctionNotFoundError), + ("not_found", "namespace", 404, NamespaceNotFoundError), + ("already_exists", "secret", 409, AlreadyExistsError), + ], +) +def test_http_error_structured_resource_error( + error_code, resource_kind, status_code, expected_type +): + err = HttpError( + "resource request failed", + "req-structured", + status_code, + error_code, + resource_kind, + "resource-name", + ["parent", "child"], + ) + + assert type(err) is expected_type + assert isinstance(err, HttpError) + assert err.error_code == error_code + assert err.resource_kind == resource_kind + assert err.resource_name == "resource-name" + assert err.namespace_path == ("parent", "child") + assert err.request_id == "req-structured" + assert err.status_code == status_code + assert err.is_transport_error is False + + +@pytest.mark.parametrize( + "error_code,resource_kind", + [ + (None, None), + ("not_found", None), + ("not_found", "unknown"), + ("invalid", "secret"), + ], +) +def test_http_error_without_known_structured_fields_stays_generic( + error_code, resource_kind +): + err = HttpError( + "not found", + "req-generic", + 404, + error_code, + resource_kind, + "resource-name", + [], + ) + + assert type(err) is HttpError + assert err.error_code == error_code + assert err.resource_kind == resource_kind + + +@pytest.mark.parametrize( + "exception_type,error_code,resource_kind", + [ + (SecretNotFoundError, "not_found", "secret"), + (FunctionNotFoundError, "not_found", "function"), + (NamespaceNotFoundError, "not_found", "namespace"), + (AlreadyExistsError, "already_exists", "namespace"), + ], +) +@pytest.mark.parametrize("is_transport_error", [False, True]) +def test_pickle_structured_http_error( + exception_type, error_code, resource_kind, is_transport_error +): + err = HttpError( + "resource request failed", + "req-pickle", + 409 if error_code == "already_exists" else 404, + error_code, + resource_kind, + "resource-name", + ["parent"], + is_transport_error=is_transport_error, + ) + assert type(err) is exception_type + + restored = pickle.loads(pickle.dumps(err)) + + assert type(restored) is exception_type + assert restored.error_code == error_code + assert restored.resource_kind == resource_kind + assert restored.resource_name == "resource-name" + assert restored.namespace_path == ("parent",) + assert restored.request_id == "req-pickle" + assert restored.status_code == err.status_code + assert restored.is_transport_error is is_transport_error + + +def test_pickle_table_not_found_error(): + err = TableNotFoundError("Table 'missing' was not found", "req-missing", 404) + restored = pickle.loads(pickle.dumps(err)) + assert isinstance(restored, TableNotFoundError) + assert isinstance(restored, NamespaceTableNotFoundError) + assert isinstance(restored, ValueError) + assert isinstance(restored, HttpError) + assert restored.code == ErrorCode.TABLE_NOT_FOUND + assert str(restored) == "Table 'missing' was not found" + assert restored.request_id == "req-missing" + assert restored.status_code == 404 def test_pickle_retry_error(): @@ -75,3 +232,87 @@ def test_pickle_retry_error(): assert restored.max_connect_failures == 3 assert restored.max_read_failures == 3 assert restored.status_code == 503 + + +@pytest.mark.parametrize( + "code,category,type_name", + [ + (3, "column_not_found", "SqlColumnNotFoundError"), + (3, "schema_mismatch", "SqlSchemaMismatchError"), + (5, "table_not_found", "SqlTableNotFoundError"), + (5, "reference_not_found", "SqlReferenceNotFoundError"), + (13, "column_not_found", "SqlError"), + (14, "table_not_found", "SqlError"), + (3, None, "SqlError"), + (5, "future_code", "SqlError"), + ], +) +def test_sql_errors_use_only_server_codes(code, category, type_name): + from lancedb.remote import errors + + original = errors.SqlError( + "column_not_found: user/file.rs:12", + "current", + code, + category, + "sql-job", + "worker", + ) + for error in [original, pickle.loads(pickle.dumps(original))]: + assert type(error) is getattr(errors, type_name) + assert str(error) == "column_not_found: user/file.rs:12" + assert error.request_id == "current" + assert error.grpc_code == code + assert error.error_code == category + assert error.job_id == "sql-job" + assert error.job_request_id == "worker" + assert error.status_code is None + if type_name != "SqlError": + assert isinstance(error, ValueError) + + +@pytest.mark.parametrize( + "status,category,type_name", + [ + (400, "column_not_found", "ColumnNotFoundError"), + (400, "schema_mismatch", "SchemaMismatchError"), + (404, "table_not_found", "TableNotFoundError"), + (404, "reference_not_found", "ReferenceNotFoundError"), + (409, None, "ConflictError"), + (409, "conflict", "ConflictError"), + (500, "conflict", "HttpError"), + (500, "column_not_found", "HttpError"), + (503, "table_not_found", "HttpError"), + ], +) +def test_http_input_errors_keep_status_and_job_metadata(status, category, type_name): + from lancedb.remote import errors + + original = errors.HttpError( + "original diagnostic", + "current", + status, + error_code=category, + job_id="sql-job", + job_request_id="worker", + ) + for error in [original, pickle.loads(pickle.dumps(original))]: + assert type(error) is getattr(errors, type_name) + assert error.status_code == status + assert error.job_id == "sql-job" + assert error.job_request_id == "worker" + assert error.request_id == "current" + + +def test_local_query_keeps_missing_column_type(tmp_path): + import lancedb + from lancedb.exceptions import ColumnNotFoundError + + db = lancedb.connect(tmp_path) + table = db.create_table("events", [{"id": 1}]) + with pytest.raises(ColumnNotFoundError) as exc_info: + table.search().where("missing > 0").to_arrow() + assert "missing" in str(exc_info.value) + assert exc_info.value.request_id is None + assert exc_info.value.job_id is None + assert exc_info.value.job_request_id is None diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 64a610b53..27a9a9376 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -2,7 +2,9 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import json +from collections import UserDict from pathlib import Path +from types import MappingProxyType import pytest @@ -167,6 +169,33 @@ def test_function_version_preserves_source_digest(source_digest): version.source_digest = "sha256:changed" +def test_function_version_exposes_registered_gpu_class(): + value = job_result("remote_function_job.json") + legacy = FunctionVersion.from_json(json.dumps(value)) + assert legacy.gpu_class is None + + value["gpu_class"] = "a10g" + version = FunctionVersion.from_json(json.dumps(value)) + assert version.gpu_class == "a10g" + assert json.loads(version.to_canonical_json())["gpu_class"] == "a10g" + + +def test_function_version_preserves_execution_controls(): + value = job_result("remote_function_job.json") + value.update( + batch_size=12, + row_timeout_seconds=8.0, + result_stability="input_and_context", + ) + version = FunctionVersion.from_json(json.dumps(value)) + encoded = json.loads(version.to_canonical_json()) + + assert encoded == value + assert type(encoded["batch_size"]) is int + assert type(encoded["row_timeout_seconds"]) is float + assert type(encoded["result_stability"]) is str + + def test_function_version_binds_named_columns_as_one_immutable_application(): version = FunctionVersion.from_json( json.dumps(job_result("remote_function_job.json")) @@ -272,10 +301,15 @@ def test_unknown_fields_and_discriminators_are_forward_decodable(): version = FunctionVersion.from_json(json.dumps(value)) assert version.image.descriptor["future_interface"] == {"kind": "wasm"} - assert json.loads(version.to_canonical_json())["image"]["descriptor"][ - "future_interface" - ] == {"kind": "wasm"} assert version.signature.output.kind == "future_output_shape" + assert not hasattr(version, "future_version_metadata") + + canonical = json.loads(version.to_canonical_json()) + expected = json.loads(fixture("remote_function_version.canonical.json")) + expected["image"]["descriptor"]["future_interface"] = {"kind": "wasm"} + expected["signature"]["output"]["kind"] = "future_output_shape" + assert canonical == expected + assert "future_version_metadata" not in canonical def test_function_application_uses_rename_columns_only(): @@ -444,13 +478,16 @@ def known_application() -> FunctionApplication: @pytest.mark.asyncio -async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomically(): +@pytest.mark.parametrize("mapping_type", [dict, UserDict, MappingProxyType]) +async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomically( + mapping_type, +): inner = _FunctionDeclarationInner() table = AsyncTable(inner) application = known_application() result = await table.add_columns( - {"features": application._copy(update={"columns": {}})} + mapping_type({"features": application._copy(update={"columns": {}})}) ) assert result == "declared" assert inner.calls[-1][1] == "features" diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 562a90eb4..53b0189f5 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -7,6 +7,7 @@ import base64 import contextlib import functools import importlib.util +import inspect import types from datetime import date import http.server @@ -15,6 +16,7 @@ import os from pathlib import Path import subprocess import sys +import typing import urllib.parse from typing import Optional @@ -23,16 +25,21 @@ import pytest import lancedb from lancedb import BlobReader +from lancedb.db import AsyncConnection from lancedb.functions import ( + FunctionVersion, + HuggingFaceModel, PythonRuntimeSpec, SecretBinding, SecretReference, - UdfDefinition, + FunctionDefinition, _canonical_arrow_type, + _exact_arrow_type, _GRAMMAR_PRIMITIVES, - udf, + function, ) from lancedb.secrets import EnvVarSecret +from lancedb.remote.db import RemoteDBConnection from utils import start_server_thread THRESHOLD = 20 @@ -55,7 +62,7 @@ FUNCTION_VERSION = json.loads( )["version"] -@udf( +@function( pip=["numpy>=2"], env={"MODE": "test"}, python_version="3.12", @@ -64,7 +71,7 @@ def normalize_score(value: float) -> float: return value / 100.0 -@udf( +@function( pip=["openai==3.7.0"], env={"MODE": "test"}, python_version="3.12", @@ -73,8 +80,8 @@ def analyze_caption(caption: str) -> str: return caption.strip() -def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): - assert isinstance(normalize_score, UdfDefinition) +def test_scalar_function_matches_shared_registration_golden_and_remains_callable(): + assert isinstance(normalize_score, FunctionDefinition) assert normalize_score(25.0) == 0.25 assert ( normalize_score.registration_request.to_canonical_json() @@ -89,20 +96,131 @@ def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): } +def test_function_declares_pinned_hugging_face_models(): + model = HuggingFaceModel( + repo="sentence-transformers/all-MiniLM-L6-v2", + revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41", + ) + + @function(pip=["sentence-transformers==3.3.1"], models=[model]) + def embed_text(value: str) -> list[float]: + return [1.0] + + request = json.loads(embed_text.registration_request.to_canonical_json()) + assert request["models"] == [ + { + "repo": "sentence-transformers/all-MiniLM-L6-v2", + "revision": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41", + } + ] + undeclared = json.loads(normalize_score.registration_request.to_canonical_json()) + assert "models" not in undeclared + + with pytest.raises(ValueError, match="once"): + function(name="duplicate_model", models=[model, model])(lambda value: value) + with pytest.raises(ValueError, match="40-character"): + HuggingFaceModel(repo="owner/model", revision="main") + with pytest.raises(ValueError, match="reserve"): + function( + name="reserved_model_env", + models=[model], + env={"HF_HOME": "/tmp/model"}, + )(lambda value: value) + + +def test_function_execution_controls_match_shared_registration_golden(): + controlled = function( + pip=["numpy>=2"], + env={"MODE": "test"}, + python_version="3.12", + batch_size=2, + row_timeout_seconds=0.75, + )(normalize_score.__wrapped__) + assert ( + controlled.registration_request.to_canonical_json() + == (FIXTURES / "remote_function_controlled_registration_request.canonical.json") + .read_text() + .strip() + ) + + +def test_function_execution_controls_apply_to_vectorized_functions(): + @function( + input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + output_schema=pa.int64(), + batch_size=3, + row_timeout_seconds=1.25, + ) + def identity(value: pa.Array) -> pa.Array: + return value + + request = json.loads(identity.registration_request.to_canonical_json()) + assert request["batch_size"] == 3 + assert request["row_timeout_seconds"] == 1.25 + + +def test_function_retry_policy_is_part_of_registration(): + policy = lancedb.FunctionRetryPolicy(transient=True, max_attempts=4) + definition = function(retry_policy=policy)(normalize_score.__wrapped__) + request = json.loads(definition.registration_request.to_canonical_json()) + assert request["retry_policy"] == {"max_attempts": 4, "transient": True} + assert lancedb.FunctionRetryPolicy(max_attempts=1).max_attempts == 1 + + +@pytest.mark.parametrize( + "options", + [ + {"max_attempts": 0, "transient": True}, + {"max_attempts": 101, "transient": True}, + {"max_attempts": True}, + {"max_attempts": 3}, + {"transient": True, "initial_backoff_seconds": -1}, + {"transient": True, "max_backoff_seconds": float("inf")}, + {"transient": True, "max_backoff_seconds": 0}, + {"message_pattern": "["}, + {"exception_types": [""]}, + {"transient": True, "typo": 1}, + ], +) +def test_function_retry_policy_rejects_invalid_options(options): + with pytest.raises(ValueError): + lancedb.FunctionRetryPolicy(**options) + + +@pytest.mark.parametrize( + ("options", "field"), + [ + ({"batch_size": 0}, "batch_size"), + ({"batch_size": 2**32}, "batch_size"), + ({"batch_size": True}, "batch_size"), + ({"row_timeout_seconds": 0}, "row_timeout_seconds"), + ({"row_timeout_seconds": -0.25}, "row_timeout_seconds"), + ({"row_timeout_seconds": float("inf")}, "row_timeout_seconds"), + ({"row_timeout_seconds": True}, "row_timeout_seconds"), + ], +) +def test_function_execution_controls_require_their_positive_ranges(options, field): + def identity(value: int) -> int: + return value + + with pytest.raises(ValueError, match=field): + function(**options)(identity) + + @pytest.mark.parametrize( "name", ["examples.image_info", "image-info", "image_info.", "image_info-"] ) -def test_udf_rejects_function_names_with_periods_or_hyphens(name): +def test_function_rejects_function_names_with_periods_or_hyphens(name): with pytest.raises(ValueError, match="invalid Function name"): - @udf(name=name) + @function(name=name) def image_info(value: int) -> int: return value @pytest.mark.parametrize("name", ["image_info", "ImageInfo123", "_image_info", "f"]) -def test_udf_accepts_function_names_with_letters_digits_and_underscores(name): - @udf(name=name) +def test_function_accepts_function_names_with_letters_digits_and_underscores(name): + @function(name=name) def image_info(value: int) -> int: return value @@ -110,7 +228,7 @@ def test_udf_accepts_function_names_with_letters_digits_and_underscores(name): assert image_info(1) == 1 -def test_secret_bound_udf_matches_its_shared_registration_golden(): +def test_secret_bound_function_matches_its_shared_registration_golden(): assert analyze_caption(" hello ") == "hello" bound = analyze_caption.bind_secrets( [EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")] @@ -243,81 +361,45 @@ def test_bindings_may_not_collide_with_plain_configuration(): ) -def test_a_binding_envelope_reaches_the_service_for_it_to_judge(): - """Binding rules are the service's: it owns the runtime the names land in. - - The client sends what it was given, so a rule it duplicated could disagree - with the service's without either side noticing. What is checked here is - that the envelope arrives intact -- the shape the service judges is the - shape the caller wrote. - """ - with _mock_remote_function_catalog() as (host, state): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - bindings = [ - EnvVarSecret(secret_name=f"secret-{index}", env_variable=f"TOKEN_{index}") - for index in range(17) - ] - db.create_function(normalize_score, secrets=bindings) - - sent = state["requests"][0][1] - assert len(sent["secret_bindings"]) == 17 - assert { - "kind": "env", - "variable": "TOKEN_0", - "secret_ref": {"name": "secret-0"}, - } in sent["secret_bindings"] - - _SECRET_DEBUG_LOG_SOURCE = """ -import http.server -import json -import threading +import pyarrow as pa +import pyarrow.flight as flight import lancedb -class Handler(http.server.BaseHTTPRequestHandler): - def log_message(self, *args): - pass +class SecretServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") - def do_POST(self): - self.rfile.read(int(self.headers.get("Content-Length", "0"))) - payload = json.dumps({}).encode() - self.send_response(200) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(payload))) - self.end_headers() - self.wfile.write(payload) + def do_exchange(self, context, descriptor, reader, writer): + assert b"SECRET_VALUE_SENTINEL" not in descriptor.command + parameters = reader.read_all() + assert parameters.column(0).to_pylist() == ["SECRET_VALUE_SENTINEL"] + result = pa.table({"status": ["created"]}) + writer.begin(result.schema) + writer.write_table(result) + writer.close() -server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) -threading.Thread( - target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True -).start() -try: +with SecretServer() as server: db = lancedb.connect( "db://dev", api_key="API_KEY_SENTINEL", - host_override="http://127.0.0.1:%d" % server.server_address[1], - client_config={"retry_config": {"retries": 0}}, + host_override="http://localhost:10024", + sql_host_override=f"grpc://127.0.0.1:{server.port}", ) db.create_secret("openai-prod", "SECRET_VALUE_SENTINEL") -finally: - server.shutdown() """ def test_a_credential_never_reaches_a_debug_log(tmp_path): - """The logger sees the serialized body, so no value-side redaction reaches it. + """Credential parameters and authentication stay out of Flight debug logs. Runs in a subprocess because the Rust logger reads ``LANCEDB_LOG`` once, at import. """ + pytest.importorskip("pyarrow.flight") script = tmp_path / "write_secret.py" script.write_text(_SECRET_DEBUG_LOG_SOURCE) @@ -331,7 +413,7 @@ def test_a_credential_never_reaches_a_debug_log(tmp_path): output = result.stdout + result.stderr # Without this the test passes when debug logging is simply off. - assert "Sending request_id=" in output, output + assert "Created client for host:" in output, output assert "SECRET_VALUE_SENTINEL" not in output assert "API_KEY_SENTINEL" not in output @@ -392,15 +474,15 @@ def test_a_secret_name_admits_what_a_namespace_name_does(): ) -def _main_udf_source( +def _main_function_source( *, threshold: int = 20, input_annotation: str = "int", comparison: str = ">=" ) -> str: return ( "from __future__ import annotations\n" - "from lancedb.functions import udf\n" + "from lancedb.functions import function\n" f"THRESHOLD = {threshold}\n" "\n" - "@udf\n" + "@function\n" f"def label(value: {input_annotation}) -> str:\n" f" return 'big' if value {comparison} THRESHOLD else 'small'\n" "\n" @@ -409,7 +491,7 @@ def _main_udf_source( ) -def _run_main_udf(path: Path, source: str) -> dict: +def _run_main_function(path: Path, source: str) -> dict: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(source) result = subprocess.run( @@ -421,15 +503,15 @@ def _run_main_udf(path: Path, source: str) -> dict: return json.loads(result.stdout) -def test_main_udf_registration_identity_is_stable_across_processes_and_paths( +def test_main_function_registration_identity_is_stable_across_processes_and_paths( tmp_path, ): - source = _main_udf_source() + source = _main_function_source() original_path = tmp_path / "original" / "job.py" moved_path = tmp_path / "moved" / "renamed_job.py" - original_runs = [_run_main_udf(original_path, source) for _ in range(2)] - moved_run = _run_main_udf(moved_path, source) + original_runs = [_run_main_function(original_path, source) for _ in range(2)] + moved_run = _run_main_function(moved_path, source) assert len({run["artifact"]["digest"] for run in [*original_runs, moved_run]}) == 1 assert all( @@ -438,15 +520,15 @@ def test_main_udf_registration_identity_is_stable_across_processes_and_paths( ) assert original_runs[0] == original_runs[1] == moved_run - body_change = _run_main_udf( - tmp_path / "changes" / "body.py", _main_udf_source(comparison=">") + body_change = _run_main_function( + tmp_path / "changes" / "body.py", _main_function_source(comparison=">") ) - global_change = _run_main_udf( - tmp_path / "changes" / "global.py", _main_udf_source(threshold=21) + global_change = _run_main_function( + tmp_path / "changes" / "global.py", _main_function_source(threshold=21) ) - annotation_change = _run_main_udf( + annotation_change = _run_main_function( tmp_path / "changes" / "annotation.py", - _main_udf_source(input_annotation="float"), + _main_function_source(input_annotation="float"), ) baseline = original_runs[0] @@ -470,12 +552,41 @@ def _run_packaged(definition, *args): """Execute the shipped artifact in a fresh namespace, as a worker would.""" source = base64.b64decode(definition.registration_request.artifact.content.data) namespace: dict = {} - exec(compile(source, "", "exec"), namespace) + exec(compile(source, "", "exec"), namespace) return namespace[definition.registration_request.artifact.entrypoint](*args) -def test_udf_conda_environment(): - @udf(conda=["scipy", "numpy"], conda_channels=["conda-forge", "defaults"]) +def _execute_registered_array_function_v1( + request: dict, batch: pa.RecordBatch +) -> pa.Array: + """Exercise adapter-v1 annotation dispatch over a registered artifact.""" + assert request["artifact"]["adapter"] == { + "kind": "scalar_to_arrow_batch", + "version": 1, + } + source = base64.b64decode(request["artifact"]["content"]["data"]) + namespace = { + "pa": pa, + "pyarrow": pa, + "Array": pa.Array, + "RecordBatch": pa.RecordBatch, + "typing": typing, + } + exec(compile(source, "", "exec"), namespace) + function = namespace[request["artifact"]["entrypoint"]] + parameters = tuple(inspect.signature(function).parameters.values()) + annotations = typing.get_type_hints(function) + assert parameters and all( + annotations.get(parameter.name) is pa.Array for parameter in parameters + ) + assert annotations.get("return") is pa.Array + result = function(*(batch.column(parameter.name) for parameter in parameters)) + assert isinstance(result, pa.Array) + return result + + +def test_function_conda_environment(): + @function(conda=["scipy", "numpy"], conda_channels=["conda-forge", "defaults"]) def halve(value: float) -> float: return value / 2 @@ -489,13 +600,13 @@ def test_udf_conda_environment(): assert "channels" not in pip_request["runtime"]["environment"] with pytest.raises(ValueError, match="not both"): - udf(name="both", pip=["numpy"], conda=["numpy"])(lambda value: value) + function(name="both", pip=["numpy"], conda=["numpy"])(lambda value: value) with pytest.raises(ValueError, match="requires conda"): - udf(name="channels", conda_channels=["conda-forge"])(lambda value: value) + function(name="channels", conda_channels=["conda-forge"])(lambda value: value) -def test_udf_apt_system_packages(): - @udf(pip=["torchcodec"], apt=["libavutil58", "libavcodec60", "libavutil58"]) +def test_function_apt_system_packages(): + @function(pip=["torchcodec"], apt=["libavutil58", "libavcodec60", "libavutil58"]) def decode(value: float) -> float: return value @@ -506,7 +617,7 @@ def test_udf_apt_system_packages(): "system_packages": ["libavcodec60", "libavutil58"], } - @udf(conda=["numpy"], apt=["libsndfile1"]) + @function(conda=["numpy"], apt=["libsndfile1"]) def conda_decode(value: float) -> float: return value @@ -515,19 +626,42 @@ def test_udf_apt_system_packages(): pip_request = json.loads(normalize_score.registration_request.to_canonical_json()) assert "system_packages" not in pip_request["runtime"]["environment"] with pytest.raises(ValueError, match="trimmed"): - udf(name="padded", apt=[" libsndfile1"])(lambda value: value) + function(name="padded", apt=[" libsndfile1"])(lambda value: value) -def test_udf_gpu_marker_uses_gpu_runtime(): - @udf(pip=["cupy-cuda12x"], gpu=True) +@pytest.mark.parametrize("packages", [{"pip": ["numpy"]}, {"conda": ["numpy"]}]) +def test_function_image(packages): + image = "ghcr.io/acme/embedder@sha256:" + "a" * 64 + + @function(image=image, **packages) + def embed(value: float) -> float: + return value + + request = json.loads(embed.registration_request.to_canonical_json()) + assert request["runtime"]["environment"]["image"] == image + pip_request = json.loads(normalize_score.registration_request.to_canonical_json()) + assert "image" not in pip_request["runtime"]["environment"] + + +@pytest.mark.parametrize( + "image", ["ghcr.io/acme/embedder:latest", "embedder@sha256:" + "a" * 64, ""] +) +def test_function_image_requires_digest_reference(image): + with pytest.raises(ValueError, match="sha256"): + function(name="pinned", image=image)(lambda value: value) + + +def test_function_gpu_marker_uses_gpu_runtime(): + @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") def double_on_gpu(value: int) -> int: return value * 2 request = json.loads(double_on_gpu.registration_request.to_canonical_json()) assert request["runtime"]["kind"] == "python_v2" assert request["runtime"]["gpu"] is True + assert request["runtime"]["gpu_class"] == "a10g" - @udf(pip=["pyarrow"]) + @function(pip=["pyarrow"]) def cpu_function(value: int) -> int: return value @@ -536,13 +670,19 @@ def test_udf_gpu_marker_uses_gpu_runtime(): ] assert cpu_runtime["kind"] == "python" assert "gpu" not in cpu_runtime + assert "gpu_class" not in cpu_runtime def identity(value: int) -> int: return value for invalid in [None, 0, 1, -1, 1.5, "", "true", "1", "H100"]: with pytest.raises(ValueError, match="gpu must be a boolean"): - udf(name="invalid_gpu", gpu=invalid)(identity) + function(name="invalid_gpu", gpu=invalid)(identity) + for invalid in ["H100", "a_b", "-a10g", "a10g-", "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) base_runtime = { "kind": "python_v2", @@ -551,14 +691,26 @@ def test_udf_gpu_marker_uses_gpu_runtime(): } runtime = PythonRuntimeSpec.model_validate({**base_runtime, "gpu": True}) assert runtime.gpu is True + runtime = PythonRuntimeSpec.model_validate( + {**base_runtime, "gpu": True, "gpu_class": "a10g"} + ) + assert runtime.gpu_class == "a10g" for invalid in [False, 1, 0, "", "true", "1", "H100"]: with pytest.raises(ValueError, match="runtime.gpu must be true"): PythonRuntimeSpec.model_validate({**base_runtime, "gpu": invalid}) + with pytest.raises(ValueError, match="gpu_class"): + PythonRuntimeSpec.model_validate( + {**base_runtime, "gpu": True, "gpu_class": "H100"} + ) def test_unknown_runtime_discards_payload_before_known_field_validation(): for payload in [ - {"kind": "python_v3", "gpu": {"model": "H100"}}, + { + "kind": "python_v3", + "gpu": {"model": "H100"}, + "gpu_class": "a10g", + }, {"kind": "python_v3", "resources": []}, { "kind": "python_v3", @@ -570,8 +722,8 @@ def test_unknown_runtime_discards_payload_before_known_field_validation(): assert runtime.to_canonical_json() == '{"kind":"python_v3"}' -def test_udf_packages_attribute_access_and_body_imports(): - @udf +def test_function_packages_attribute_access_and_body_imports(): + @function def word_norm(body: str) -> float: import numpy as np @@ -584,14 +736,14 @@ def test_udf_packages_attribute_access_and_body_imports(): assert _run_packaged(word_norm, "aa bb") == pytest.approx(8**0.5) -def test_udf_packages_module_globals_and_global_caches(): - @udf +def test_function_packages_module_globals_and_global_caches(): + @function def label(value: int) -> str: return "big" if value >= THRESHOLD else "small" assert _run_packaged(label, 21) == "big" - @udf + @function def cached(value: int) -> int: global _CACHE if _CACHE is None: @@ -601,16 +753,16 @@ def test_udf_packages_module_globals_and_global_caches(): assert _run_packaged(cached, 2) == 42 -def test_udf_annotations_are_not_runtime_names(): - @udf +def test_function_annotations_are_not_runtime_names(): + @function def identity(value: date) -> date: return value assert _run_packaged(identity, date(2026, 8, 25)) == date(2026, 8, 25) -def test_udf_nested_scopes_resolve_lexically(): - @udf +def test_function_nested_scopes_resolve_lexically(): + @function def score(value: int) -> int: offset = 2 @@ -622,7 +774,7 @@ def test_udf_nested_scopes_resolve_lexically(): assert _run_packaged(score, 3) == 5 -def test_udf_resolves_module_globals_before_builtins(tmp_path): +def test_function_resolves_module_globals_before_builtins(tmp_path): module_path = tmp_path / "shadowing_udfs.py" module_path.write_text( "max = 7\n" @@ -643,10 +795,10 @@ def test_udf_resolves_module_globals_before_builtins(tmp_path): spec.loader.exec_module(module) # The module's `max = 7` is what the interpreter would use, so it ships. - assert _run_packaged(udf(module.uses_literal_shadow), 1) == 8 + assert _run_packaged(function(module.uses_literal_shadow), 1) == 8 # A callable global cannot ship; it must not be silently swapped for the builtin. with pytest.raises(TypeError, match="unsupported global value of type function"): - udf(module.uses_callable_shadow) + function(module.uses_callable_shadow) def test_canonical_arrow_type_prefers_the_compact_grammar(): @@ -679,8 +831,8 @@ def test_canonical_arrow_type_prefers_the_compact_grammar(): _canonical_arrow_type(outside) -def test_udf_nested_annotations_are_postponed_in_the_artifact(): - @udf +def test_function_nested_annotations_are_postponed_in_the_artifact(): + @function def score(value: int) -> int: def identity(item: date) -> date: return item @@ -691,8 +843,8 @@ def test_udf_nested_annotations_are_postponed_in_the_artifact(): assert _run_packaged(score, 3) == 3 -def test_udf_ships_globals_the_body_deletes(): - @udf +def test_function_ships_globals_the_body_deletes(): + @function def clear(value: int) -> int: global _CACHE del _CACHE @@ -701,7 +853,7 @@ def test_udf_ships_globals_the_body_deletes(): assert _run_packaged(clear, 3) == 3 -def test_udf_rejects_a_module_global_that_does_not_import_as_itself(tmp_path): +def test_function_rejects_a_module_global_that_does_not_import_as_itself(tmp_path): module_path = tmp_path / "fake_module_udfs.py" module_path.write_text( "import types\n" @@ -715,10 +867,10 @@ def test_udf_rejects_a_module_global_that_does_not_import_as_itself(tmp_path): module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) with pytest.raises(TypeError, match="does not import as 'numpy'"): - udf(module.score) + function(module.score) -def test_udf_rejects_a_module_level_namespace_alias(tmp_path): +def test_function_rejects_a_module_level_namespace_alias(tmp_path): module_path = tmp_path / "aliasing_udfs.py" module_path.write_text( "import builtins as b\n" @@ -731,7 +883,7 @@ def test_udf_rejects_a_module_level_namespace_alias(tmp_path): module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) with pytest.raises(ValueError, match="dynamic namespace access"): - udf(module.score) + function(module.score) @pytest.mark.parametrize( @@ -744,7 +896,7 @@ def test_udf_rejects_a_module_level_namespace_alias(tmp_path): "sys.modules[__name__].THRESHOLD", ], ) -def test_udf_rejects_dynamic_namespace_access(access): +def test_function_rejects_dynamic_namespace_access(access): namespace: dict = {} exec( f"def score(value: int) -> int:\n return value + {access}\n", @@ -764,9 +916,11 @@ def _package_from_text(source: str, module_globals: dict | None = None): import tempfile directory = tempfile.mkdtemp() - path = Path(directory) / "generated_udf_module.py" + path = Path(directory) / "generated_function_module.py" path.write_text(source) - spec = importlib.util.spec_from_file_location(f"generated_udf_{id(source)}", path) + spec = importlib.util.spec_from_file_location( + f"generated_function_{id(source)}", path + ) module = importlib.util.module_from_spec(spec) if module_globals: module.__dict__.update(module_globals) @@ -776,10 +930,10 @@ def _package_from_text(source: str, module_globals: dict | None = None): for value in vars(module).values() if callable(value) and getattr(value, "__module__", None) == module.__name__ ] - return udf(functions[0]) + return function(functions[0]) -def test_udf_rejects_a_non_standard_builtins_environment(): +def test_function_rejects_a_non_standard_builtins_environment(): def score(value: int) -> int: return len([1]) + value @@ -794,7 +948,7 @@ def test_udf_rejects_a_non_standard_builtins_environment(): patched.__annotations__ = score.__annotations__ assert patched(3) == 102 with pytest.raises(ValueError, match="non-standard builtins environment"): - udf(patched) + function(patched) class ReportingDict(dict): # reports standard entries, resolves differently def __missing__(self, key): @@ -806,7 +960,7 @@ def test_udf_rejects_a_non_standard_builtins_environment(): disguised.__annotations__ = score.__annotations__ assert disguised(3) == 102 with pytest.raises(ValueError, match="non-standard builtins environment"): - udf(disguised) + function(disguised) hooked = types.FunctionType( score.__code__, @@ -815,10 +969,10 @@ def test_udf_rejects_a_non_standard_builtins_environment(): ) hooked.__annotations__ = score.__annotations__ with pytest.raises(ValueError, match="non-standard builtins environment"): - udf(hooked) + function(hooked) -def test_udf_recursion_versus_a_rebound_module_name(tmp_path): +def test_function_recursion_versus_a_rebound_module_name(tmp_path): module_path = tmp_path / "rebound_udfs.py" module_path.write_text( "def fact(value: int) -> int:\n" @@ -830,20 +984,20 @@ def test_udf_recursion_versus_a_rebound_module_name(tmp_path): spec = importlib.util.spec_from_file_location("rebound_udfs", module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) - assert _run_packaged(udf(module.fact), 5) == 120 + assert _run_packaged(function(module.fact), 5) == 120 raw = module.score module.score = 10 with pytest.raises(ValueError, match="binds that name to another value"): - udf(raw) + function(raw) # A wrapper that merely exposes __wrapped__ is not the function. module.score = functools.wraps(raw)(lambda value: 41) with pytest.raises(ValueError, match="binds that name to another value"): - udf(raw) + function(raw) # The decorator's own result is; a subclass of it is not. - module.fact = udf(module.fact) + module.fact = function(module.fact) assert _run_packaged(module.fact, 4) == 24 - class Twisted(UdfDefinition): + class Twisted(FunctionDefinition): def __call__(self, *args, **kwargs): return 41 @@ -858,7 +1012,7 @@ def test_udf_recursion_versus_a_rebound_module_name(tmp_path): python_version=None, ) with pytest.raises(ValueError, match="binds that name to another value"): - udf(raw_fact) + function(raw_fact) def test_canonical_arrow_type_uses_exact_json_for_list_child_properties(): @@ -929,12 +1083,12 @@ def _shadows_missing_in_a_lambda(value: int) -> int: @pytest.mark.parametrize( - "function", + "target", [_calls_missing, _shadows_missing_in_a_comprehension, _shadows_missing_in_a_lambda], ) -def test_udf_rejects_a_truly_unresolved_global(function): +def test_function_rejects_a_truly_unresolved_global(target): with pytest.raises(ValueError, match=r"unresolved global names: \['missing'\]"): - udf(function) + function(target) def _arrow_type_from_golden(spec: dict) -> pa.DataType: @@ -989,7 +1143,7 @@ def test_explicit_arrow_schema_is_deterministic(): nullable=False, ) - @udf(input_schema=input_schema, output_schema=output_schema) + @function(input_schema=input_schema, output_schema=output_schema) def explicit(value): return [value, value, value] @@ -1001,7 +1155,7 @@ def test_explicit_arrow_schema_is_deterministic(): def test_blob_fields_use_the_scalar_function_semantic_type(): - @udf( + @function( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), output_schema=lancedb.blob("result", nullable=False), ) @@ -1015,12 +1169,12 @@ def test_blob_fields_use_the_scalar_function_semantic_type(): def test_blob_input_access_is_inferred_from_annotations(): - @udf + @function def read_blob(video: BlobReader, timestamp_s: float) -> bytes: video.seek(int(timestamp_s)) return video.read(4) - @udf + @function def read_bytes(video: bytes) -> int: return len(video) @@ -1037,11 +1191,11 @@ def test_blob_input_access_is_inferred_from_annotations(): def test_nullable_blob_reader_and_explicit_blob_bytes(): - @udf + @function def nullable(video: Optional[BlobReader]) -> int: return 0 if video is None else video.size() - @udf( + @function( input_schema=pa.schema([lancedb.blob("video", nullable=False)]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1061,7 +1215,7 @@ def test_blob_reader_rejects_an_incompatible_explicit_schema(): return video.size() with pytest.raises(TypeError, match="requires a Blob V2 field"): - udf( + function( read, input_schema=pa.schema([pa.field("video", pa.int64(), nullable=False)]), output_schema=pa.field("size", pa.int64(), nullable=False), @@ -1069,7 +1223,7 @@ def test_blob_reader_rejects_an_incompatible_explicit_schema(): def test_whole_named_struct_function_can_include_a_blob_result_field(): - @udf( + @function( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), output_schema=pa.field( "payload", @@ -1123,7 +1277,7 @@ def test_struct_blob_signature_fields_preserve_exact_metadata_and_nullability(): nullable=False, ) - @udf(input_schema=pa.schema([nested_input]), output_schema=nested_output) + @function(input_schema=pa.schema([nested_input]), output_schema=nested_output) def copy_payload(payload): return payload @@ -1167,7 +1321,7 @@ def test_struct_blob_signature_supports_multiple_struct_levels(): nullable=False, ) - @udf( + @function( input_schema=pa.schema([recursive]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1179,6 +1333,74 @@ def test_struct_blob_signature_supports_multiple_struct_levels(): assert blob["metadata"]["ARROW:extension:name"] == "lance.blob.v2" +@pytest.mark.parametrize( + "data_type", + [ + pa.list_(lancedb.blob("item", nullable=False)), + pa.large_list(lancedb.blob("item", nullable=False)), + pa.list_(pa.struct([lancedb.blob("image", nullable=False)])), + ], +) +def test_blob_output_accepts_list_ancestors(data_type): + @function( + input_schema=pa.schema([lancedb.blob("video", nullable=False)]), + output_schema=pa.field("frames", data_type, nullable=False), + ) + def extract_frames(video: bytes) -> list: + return [video] + + output = extract_frames.registration_request.signature.output + assert json.loads(output.arrow_type) == _exact_arrow_type( + data_type, collection_blobs=True + ) + assert "lance.blob.v2" in output.arrow_type + + +@pytest.mark.parametrize( + "data_type", + [ + pa.map_(pa.string(), lancedb.blob("value", nullable=False).type), + pa.list_(lancedb.blob("item", nullable=False), 2), + pa.list_(pa.list_(lancedb.blob("item", nullable=False), 2)), + ], +) +def test_blob_output_rejects_map_and_fixed_size_list_ancestors(data_type): + with pytest.raises(TypeError, match="nested under collection types"): + + @function( + input_schema=pa.schema([pa.field("id", pa.int64(), nullable=False)]), + output_schema=pa.field("frames", data_type, nullable=False), + ) + def frames(id: int) -> dict: + return {} + + +def test_blob_output_named_struct_accepts_list_ancestor(): + frames_type = pa.list_(lancedb.blob("item", nullable=False)) + + @function( + input_schema=pa.schema([pa.field("id", pa.int64(), nullable=False)]), + output_schema=pa.schema( + [ + pa.field("frames", frames_type, nullable=False), + pa.field("count", pa.int64(), nullable=False), + ] + ), + ) + def extract_frames(id: int) -> dict: + return {"frames": [], "count": 0} + + output = extract_frames.registration_request.signature.output + assert output.kind == "named_struct" + assert [field.name for field in output.fields] == ["frames", "count"] + assert json.loads(output.fields[0].arrow_type) == _exact_arrow_type( + frames_type, collection_blobs=True + ) + assert "lance.blob.v2" in output.fields[0].arrow_type + assert output.fields[1].arrow_type == "int64" + assert output.fields[1].nullable is False + + @pytest.mark.parametrize( "data_type", [ @@ -1194,7 +1416,7 @@ def test_blob_signature_rejects_collection_ancestors(data_type): match="Blob v2 fields nested under collection types are not supported", ): - @udf( + @function( input_schema=pa.schema([pa.field("value", data_type, nullable=False)]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1221,7 +1443,7 @@ def test_blob_signature_rejects_collection_below_a_struct(): match="Blob v2 fields nested under collection types are not supported", ): - @udf( + @function( input_schema=pa.schema([nested]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1229,8 +1451,59 @@ def test_blob_signature_rejects_collection_below_a_struct(): return len(value["images"]) +def test_blob_fields_support_vectorized_pyarrow_arrays(): + @function( + input_schema=pa.schema([lancedb.blob("image", nullable=True)]), + output_schema=lancedb.blob("result", nullable=False), + ) + def copy_blobs(image: pa.Array) -> pa.Array: + return pa.array( + [value.as_py() if value.is_valid else b"" for value in image], + type=pa.large_binary(), + ) + + values = pa.array([b"large blob", b"", None], type=pa.large_binary()) + request = json.loads(copy_blobs.registration_request.to_canonical_json()) + batch = pa.RecordBatch.from_arrays([values], names=["image"]) + result = _execute_registered_array_function_v1(request, batch) + assert isinstance(result, pa.LargeBinaryArray) + assert result.to_pylist() == [b"large blob", b"", b""] + + signature = copy_blobs.registration_request.signature + assert signature.inputs[0].arrow_type == "blob_v2" + assert signature.inputs[0].nullable is True + assert signature.output.arrow_type == "blob_v2" + assert signature.output.nullable is False + assert copy_blobs.registration_request.artifact.adapter.kind == ( + "scalar_to_arrow_batch" + ) + assert copy_blobs.registration_request.artifact.adapter.version == 1 + + source = base64.b64decode( + copy_blobs.registration_request.artifact.content.data + ).decode("utf-8") + assert "def copy_blobs(image: pa.Array) -> pa.Array:" in source + + +def test_documented_blob_array_identity_executes_packaged_artifact(): + @function( + input_schema=pa.schema([lancedb.blob("image", nullable=False)]), + output_schema=lancedb.blob("copy", nullable=False), + ) + def copy_blobs(image: pa.Array) -> pa.Array: + return image + + values = pa.array([b"large blob", b""], type=pa.large_binary()) + request = json.loads(copy_blobs.registration_request.to_canonical_json()) + result = _execute_registered_array_function_v1( + request, + pa.RecordBatch.from_arrays([values], names=["image"]), + ) + assert result.equals(values) + + def test_named_struct_function_can_include_a_blob_result_field(): - @udf( + @function( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), output_schema=pa.schema( [ @@ -1251,7 +1524,7 @@ def test_named_struct_function_can_include_a_blob_result_field(): def test_named_struct_function_preserves_nullable_result_fields(): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), output_schema=pa.schema( [ @@ -1269,7 +1542,7 @@ def test_named_struct_function_preserves_nullable_result_fields(): ("failure_code", False), ] - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), output_schema=pa.schema( [ @@ -1299,7 +1572,7 @@ def test_metadata_marked_blob_field_uses_the_semantic_type(): metadata={"ARROW:extension:name": "lance.blob.v2"}, ) - @udf( + @function( input_schema=pa.schema([metadata_blob]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1319,7 +1592,7 @@ def test_blob_marker_rejects_invalid_storage_layout(): with pytest.raises(TypeError, match="requires a supported Blob storage layout"): - @udf( + @function( input_schema=pa.schema([malformed]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1346,7 +1619,7 @@ def test_nested_non_blob_extension_is_not_silently_unwrapped(): ) with pytest.raises(TypeError, match="unsupported Arrow type"): - @udf( + @function( input_schema=pa.schema([nested]), output_schema=pa.field("result", pa.int64(), nullable=False), ) @@ -1358,7 +1631,7 @@ def test_explicit_large_utf8_schemas_use_the_canonical_function_name(): input_schema = pa.schema([pa.field("text", pa.large_string(), nullable=True)]) output_schema = pa.field("result", pa.large_string(), nullable=False) - @udf(input_schema=input_schema, output_schema=output_schema) + @function(input_schema=input_schema, output_schema=output_schema) def preserve(text): return text @@ -1384,7 +1657,7 @@ def test_explicit_large_utf8_schemas_use_the_canonical_function_name(): def test_large_binary_schemas_use_the_canonical_function_name(): payload = pa.field("data", pa.large_binary(), nullable=True) - @udf( + @function( input_schema=pa.schema([payload]), output_schema=pa.field("result", pa.large_binary(), nullable=False), ) @@ -1455,7 +1728,7 @@ def test_nested_struct_output_uses_canonical_exact_json(): ] ) - @udf( + @function( input_schema=pa.schema([pa.field("text", pa.string(), nullable=False)]), output_schema=pa.field("analysis", analysis, nullable=False), ) @@ -1505,31 +1778,31 @@ def test_nested_struct_output_uses_canonical_exact_json(): def test_annotation_and_explicit_schema_validation_fail_closed(): with pytest.raises(TypeError, match="missing Function annotations"): - @udf + @function def missing(value): return value with pytest.raises(TypeError, match="unsupported Function annotation"): - @udf + @function def unsupported(value: set[str]) -> str: return "" with pytest.raises(ValueError, match="output must be non-nullable"): - @udf + @function def nullable_output(value: int) -> Optional[int]: return value with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"): - @udf(input_schema=pa.schema([pa.field("value", pa.int64())])) + @function(input_schema=pa.schema([pa.field("value", pa.int64())])) def partial_schema(value): return value with pytest.raises(ValueError, match="exactly match callable parameters"): - @udf( + @function( input_schema=pa.schema([pa.field("other", pa.int64())]), output_schema=pa.int64(), ) @@ -1538,7 +1811,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): with pytest.raises(ValueError, match="output must be non-nullable"): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64())]), output_schema=pa.field("result", pa.int64(), nullable=True), ) @@ -1551,7 +1824,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): ]: with pytest.raises(TypeError, match="unsupported Arrow type"): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64())]), output_schema=pa.schema([invalid_field]), ) @@ -1560,7 +1833,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): with pytest.raises(TypeError, match="unsupported Arrow type"): - @udf( + @function( input_schema=pa.schema( [pa.field("value", pa.int64(), metadata={"k": "v"})] ), @@ -1571,7 +1844,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): with pytest.raises(TypeError, match="unsupported Arrow type"): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64())]), output_schema=pa.field( "result", pa.int64(), nullable=False, metadata={"k": "v"} @@ -1583,7 +1856,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): struct_type = pa.struct([pa.field("value", pa.int64(), nullable=False)]) with pytest.raises(TypeError, match="unsupported Arrow type"): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64())]), output_schema=pa.field( "result", struct_type, nullable=False, metadata={"k": "v"} @@ -1607,7 +1880,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): ]: with pytest.raises(TypeError, match="schema metadata"): - @udf(input_schema=input_schema, output_schema=output_schema) + @function(input_schema=input_schema, output_schema=output_schema) def schema_metadata(value): return value @@ -1627,6 +1900,117 @@ def test_local_function_catalog_operations_are_not_supported(tmp_path): db.drop_function("normalize_score", version=FUNCTION_VERSION) +class _RawFunctionCatalog: + def __init__(self, definition, *, encode=False): + self.definition = json.dumps(definition) if encode else definition + + async def get_function(self, _name, version, namespace_path): + return self.definition + + def list_functions(self, *, namespace_path=None, page_token=None, page_limit=None): + return self + + def __aiter__(self): + return self + + async def __anext__(self): + if self.definition is None: + raise StopAsyncIteration + definition, self.definition = self.definition, None + return definition + + def num_page_results(self): + return int(self.definition is not None) + + def page_token(self): + return None + + +def _assert_execution_control_encoding(version): + encoded = json.loads(version.to_canonical_json()) + assert type(encoded["batch_size"]) is int + assert type(encoded["row_timeout_seconds"]) is float + assert type(encoded["result_stability"]) is str + return encoded + + +@pytest.mark.asyncio +async def test_async_catalog_path_preserves_execution_controls(): + definition = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + definition.update( + batch_size=12, + row_timeout_seconds=8.0, + result_stability="input_and_context", + ) + connection = AsyncConnection(_RawFunctionCatalog(definition, encode=True)) + + exact = await connection.get_function("embed", version="1") + listed = [item async for item in connection.list_functions(page_limit=32)] + assert len(listed) == 1 + for version in [exact, *listed]: + assert _assert_execution_control_encoding(version) == definition + + +def test_sync_catalog_path_preserves_execution_controls(): + definition = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + definition.update( + batch_size=12, + row_timeout_seconds=8.0, + result_stability="input_and_context", + ) + connection = object.__new__(RemoteDBConnection) + connection._conn = _RawFunctionCatalog(FunctionVersion(**definition)) + + exact = connection.get_function("embed", version="1") + listed = list(connection.list_functions(page_limit=32)) + assert len(listed) == 1 + for version in [exact, *listed]: + assert _assert_execution_control_encoding(version) == definition + + +def test_sync_drop_function_emits_server_warnings_without_changing_bool_api(): + class _DropConnection: + async def drop_function(self, name, *, version, namespace_path=None): + return True + + async def _drop_function_with_warnings( + self, name, *, version, namespace_path=None + ): + return True, [ + 'materialized view "pinned" references Function "embed" version "1"' + ] + + connection = object.__new__(RemoteDBConnection) + connection._conn = _DropConnection() + + with pytest.warns(UserWarning, match="references Function"): + assert connection.drop_function("embed", version="1") is True + + +@pytest.mark.asyncio +async def test_async_drop_function_emits_server_warnings_without_changing_bool_api(): + class _Inner: + async def _drop_function_with_warnings( + self, name, version, namespace_path=None + ): + return True, [ + 'materialized view "pinned" references Function "embed" version "1"' + ] + + async def drop_function(self, name, version, namespace_path=None): + return True + + connection = object.__new__(AsyncConnection) + connection._inner = _Inner() + + with pytest.warns(UserWarning, match="references Function"): + assert await connection.drop_function("embed", version="1") is True + + @contextlib.contextmanager def _mock_remote_function_catalog(): state = {"requests": [], "version": None} @@ -1766,109 +2150,6 @@ def _mock_remote_function_catalog(): thread.join() -def test_remote_registration_job_and_exact_version_reopen_round_trip(): - with _mock_remote_function_catalog() as (host, state): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - registration = db.create_function_async(normalize_score) - assert registration.id == "job-register" - assert registration.job_type is None - assert registration.status() == "finished" - assert registration.job_type == "create_function" - created = registration.wait() - assert registration.job_type == "create_function" - reopened = db.get_function("normalize_score", version=created.version) - - assert created == reopened - assert reopened.name == "normalize_score" - assert reopened.version == FUNCTION_VERSION - assert ( - reopened.source_digest == normalize_score.registration_request.artifact.digest - ) - create_request = state["requests"][0][1] - expected_request = json.loads( - normalize_score.registration_request.to_canonical_json() - ) - expected_request.pop("name") - assert create_request == expected_request - - -def test_remote_registration_sends_bindings_and_never_a_credential(): - with _mock_remote_function_catalog() as (host, state): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - created = db.create_function( - analyze_caption, - secrets=[ - EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY") - ], - ) - - assert list(created.secret_bindings) == [ - SecretBinding( - kind="env", - variable="OPENAI_API_KEY", - secret_ref=SecretReference(name="openai-prod"), - ) - ] - path, create_request = state["requests"][0] - assert path == "/v1/function/analyze_caption/create" - assert create_request["secret_bindings"] == [ - { - "kind": "env", - "variable": "OPENAI_API_KEY", - "secret_ref": {"name": "openai-prod"}, - } - ] - # The request names a Secret and carries nothing that could be one. The - # Function's own name is the path identifier rather than a body field, so - # it is the one key the body does not repeat. - expected = json.loads( - analyze_caption.bind_secrets( - [EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")] - ).to_canonical_json() - ) - assert expected.pop("name") == "analyze_caption" - assert create_request == expected - - -def test_remote_secret_verbs_round_trip(): - with _mock_remote_function_catalog() as (host, state): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - assert db.create_secret("openai-prod", "sk-live-0001") is None - assert db.alter_secret("openai-prod", "sk-live-0002") is None - assert list(db.list_secrets()) == ["openai-prod", "hf-prod"] - assert db.drop_secret("openai-prod") is None - - routes = [path for path, _ in state["requests"]] - assert routes == [ - "/v1/secret/openai-prod/create", - "/v1/secret/openai-prod/alter", - "/v1/namespace/$/secret/list", - "/v1/namespace/$/secret/list", - "/v1/secret/openai-prod/drop", - ] - # The Secret is the path identifier, so the body is the value alone. - assert state["requests"][0][1] == {"value": "sk-live-0001"} - # Listing is a GET: the first page asks for nothing, the second resumes on - # the token the server handed back, and neither carries a body. - assert state["requests"][2][1] == {} - assert state["requests"][3][1] == {"page_token": "next"} - - def test_building_a_binding_contacts_no_server(): """A binding is a local value: it says nothing about whether the Secret exists. @@ -1883,193 +2164,157 @@ def test_building_a_binding_contacts_no_server(): assert state["requests"] == [] -def test_blocking_remote_registration_returns_function_version(): - with _mock_remote_function_catalog() as (host, state): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - created = db.create_function(normalize_score) - - assert created.name == "normalize_score" - assert created.version == FUNCTION_VERSION - assert created.source_digest == normalize_score.registration_request.artifact.digest - assert [path for path, _ in state["requests"]] == [ - "/v1/function/normalize_score/create", - "/v1/jobs/describe", - ] - - -def test_remote_list_functions_paginates_and_returns_typed_versions(): - with _mock_remote_function_catalog() as (host, state): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - created = db.create_function(normalize_score) - state["requests"].clear() - functions = list(db.list_functions()) - - assert functions == [created] - assert functions[0].source_digest == ( - normalize_score.registration_request.artifact.digest +def test_vectorized_blob_function_executes_packaged_artifact_and_publishes(tmp_path): + @function( + input_schema=pa.schema([lancedb.blob("image", nullable=True)]), + output_schema=lancedb.blob("copy", nullable=False), ) - assert state["requests"] == [ - ("/v1/namespace/$/function/list", {"include_definition": "true"}), - ( - "/v1/namespace/$/function/list", - {"include_definition": "true", "page_token": "next"}, + def copy_blobs(image: pa.Array) -> pa.Array: + assert isinstance(image, pa.LargeBinaryArray) + return pa.array( + [ + b"missing" if value.as_py() is None else b"copy:" + value.as_py() + for value in image + ], + type=pa.large_binary(), + ) + + registration = json.loads(copy_blobs.registration_request.to_canonical_json()) + + local = lancedb.connect(tmp_path) + source = local.create_table( + "blob_input", + schema=pa.schema( + [pa.field("id", pa.int64()), lancedb.blob("image", nullable=True)] ), - ] - - -@pytest.mark.asyncio -async def test_async_remote_list_functions_returns_typed_versions(): - with _mock_remote_function_catalog() as (host, state): - db = await lancedb.connect_async( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - registration = await db.create_function_async(normalize_score) - created = await registration.wait() - state["requests"].clear() - functions = [item async for item in db.list_functions()] - - assert functions == [created] - assert functions[0].source_digest == ( - normalize_score.registration_request.artifact.digest ) - assert [path for path, _ in state["requests"]] == [ - "/v1/namespace/$/function/list", - "/v1/namespace/$/function/list", + source.add( + pa.Table.from_arrays( + [ + pa.array([0, 1, 2], type=pa.int64()), + pa.array([b"large blob", b"", None], type=pa.large_binary()), + ], + names=["id", "image"], + ) + ) + input_hits = ( + source.search() + .with_row_id(True) + .limit(3) + .to_arrow() + .sort_by([("id", "ascending")]) + ) + hydrated = source.fetch_blobs("image", input_hits) + assert isinstance(hydrated, pa.LargeBinaryArray) + result = _execute_registered_array_function_v1( + registration, + pa.RecordBatch.from_arrays([hydrated], names=["image"]), + ) + assert result.to_pylist() == [b"copy:large blob", b"copy:", b"missing"] + + published = local.create_table( + "blob_output", + schema=pa.schema( + [pa.field("id", pa.int64()), lancedb.blob("copy", nullable=False)] + ), + ) + published.add( + pa.Table.from_arrays( + [pa.array(range(len(result)), type=pa.int64()), result], + names=["id", "copy"], + ) + ) + output_hits = ( + published.search() + .with_row_id(True) + .limit(3) + .to_arrow() + .sort_by([("id", "ascending")]) + ) + assert published.fetch_blobs("copy", output_hits).to_pylist() == [ + b"copy:large blob", + b"copy:", + b"missing", ] -def test_remote_drop_function_sends_exact_version(): - with _mock_remote_function_catalog() as (host, state): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - assert db.drop_function("normalize_score", version=FUNCTION_VERSION) is True +@pytest.mark.parametrize( + ("declared_list", "physical_list", "array_type", "declared_name"), + [ + (pa.list_, pa.list_, pa.ListArray, "list"), + (pa.large_list, pa.large_list, pa.LargeListArray, "large_list"), + ], + ids=["list", "large_list"], +) +def test_blob_list_output_fresh_artifact_survives_local_reopen( + tmp_path, declared_list, physical_list, array_type, declared_name +): + input_type = physical_list(pa.int64()) + item = lancedb.blob("item", nullable=True) - assert state["requests"] == [ - ( - "/v1/function/normalize_score/drop", - {"version": FUNCTION_VERSION}, + @function( + input_schema=pa.schema([pa.field("frames", input_type, nullable=False)]), + output_schema=pa.field("frames", declared_list(item), nullable=False), + ) + def extract_frames(frames: pa.Array) -> pa.Array: + output_type = ( + pa.large_list(pa.large_binary()) + if isinstance(frames, pa.LargeListArray) + else pa.list_(pa.large_binary()) ) - ] + return pa.array([[b"abc", None, b""], []], type=output_type) + request = json.loads(extract_frames.registration_request.to_canonical_json()) + declared = json.loads(request["signature"]["output"]["arrow_type"]) + assert declared["type"] == declared_name + item_field = declared["fields"][0] + assert item_field["metadata"]["ARROW:extension:name"] == "lance.blob.v2" -@pytest.mark.asyncio -async def test_async_remote_drop_function_sends_exact_version(): - with _mock_remote_function_catalog() as (host, state): - db = await lancedb.connect_async( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - assert ( - await db.drop_function("normalize_score", version=FUNCTION_VERSION) is True - ) + result = _execute_registered_array_function_v1( + request, + pa.RecordBatch.from_arrays( + [pa.array([[0], [1]], type=input_type)], + names=["frames"], + ), + ) + assert isinstance(result, array_type) + assert result.type == physical_list(pa.large_binary()) + assert result.offsets.to_pylist() == [0, 3, 3] + assert result.values.to_pylist() == [b"abc", None, b""] + assert result.to_pylist() == [[b"abc", None, b""], []] - assert state["requests"] == [ - ( - "/v1/function/normalize_score/drop", - {"version": FUNCTION_VERSION}, + db = lancedb.connect(tmp_path) + table = db.create_table( + "fresh_artifact_frames", + schema=pa.schema( + [ + pa.field("id", pa.int64(), nullable=False), + pa.field("frames", declared_list(item), nullable=False), + ] + ), + ) + table.add( + pa.Table.from_arrays( + [pa.array([1, 2], type=pa.int64()), result], + names=["id", "frames"], ) - ] + ) + reopened = lancedb.connect(tmp_path).open_table("fresh_artifact_frames") + reopened_item = reopened.schema.field("frames").type.value_field + assert reopened_item.type.extension_name == "lance.blob.v2" + assert reopened.blob_columns() == [] + hits = reopened.search().limit(2).to_arrow().sort_by([("id", "ascending")]) + lists = hits["frames"].combine_chunks() + assert isinstance(lists, array_type) + assert lists.offsets.to_pylist() == [0, 3, 3] -def test_remote_function_verbs_address_a_namespace_in_the_path(): - """A Function's namespace is part of the identifier each route addresses; - no body carries it, so a namespaced request differs only in its path.""" - namespace = ["analytics", "features"] - with _mock_remote_function_catalog() as (host, state): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - created = db.create_function(normalize_score, namespace_path=namespace) - # The returned parts are what the other verbs take, so a created - # Function reopens from its own fields. - assert created.name == "normalize_score" - assert created.namespace_path == tuple(namespace) - reopened = db.get_function( - created.name, - version=created.version, - namespace_path=list(created.namespace_path), - ) - assert reopened == created - assert reopened(value=lancedb.col("score")).function.namespace_path == tuple( - namespace - ) - list(db.list_functions(namespace_path=namespace)) - assert ( - db.drop_function( - "normalize_score", version=FUNCTION_VERSION, namespace_path=namespace - ) - is True - ) - dropped, _ = db.drop_function_async( - "normalize_score", version=FUNCTION_VERSION, namespace_path=namespace - ) - assert dropped is True - - assert [path for path, _ in state["requests"]] == [ - "/v1/function/analytics$features$normalize_score/create", - "/v1/jobs/describe", - "/v1/function/analytics$features$normalize_score/describe", - "/v1/namespace/analytics$features/function/list", - "/v1/namespace/analytics$features/function/list", - "/v1/function/analytics$features$normalize_score/drop", - "/v1/function/analytics$features$normalize_score/drop", - ] - - -@pytest.mark.asyncio -async def test_async_remote_function_verbs_address_a_namespace_in_the_path(): - namespace = ["analytics", "features"] - with _mock_remote_function_catalog() as (host, state): - db = await lancedb.connect_async( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - registration = await db.create_function_async( - normalize_score, namespace_path=namespace - ) - await registration.wait() - await db.get_function( - "normalize_score", version=FUNCTION_VERSION, namespace_path=namespace - ) - [item async for item in db.list_functions(namespace_path=namespace)] - assert ( - await db.drop_function( - "normalize_score", version=FUNCTION_VERSION, namespace_path=namespace - ) - is True - ) - - assert [path for path, _ in state["requests"]] == [ - "/v1/function/analytics$features$normalize_score/create", - "/v1/jobs/describe", - "/v1/function/analytics$features$normalize_score/describe", - "/v1/namespace/analytics$features/function/list", - "/v1/namespace/analytics$features/function/list", - "/v1/function/analytics$features$normalize_score/drop", + rows = lists.to_pylist() + assert rows[1] == [] + assert [None if value is None else value["size"] for value in rows[0]] == [ + 3, + None, + 0, ] @@ -2090,11 +2335,11 @@ def test_a_function_namespace_path_must_be_a_list_of_segments(): def test_one_explicit_schema_infers_the_other_from_annotations(): - @udf(input_schema=pa.schema([pa.field("value", pa.int64())])) + @function(input_schema=pa.schema([pa.field("value", pa.int64())])) def explicit_input(value) -> float: return float(value or 0) - @udf(output_schema=pa.field("result", pa.float32(), nullable=False)) + @function(output_schema=pa.field("result", pa.float32(), nullable=False)) def explicit_output(value: Optional[int]): return float(value or 0) diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index 6714f35d9..f2fcc970b 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -39,7 +39,6 @@ from lancedb.query import ( ) import numpy as np import pyarrow as pa -import pandas as pd import pytest import pytest_asyncio from utils import exception_output @@ -154,7 +153,7 @@ def table(tmp_path) -> ldb.table.LanceTable: count = [local_random.randint(1, 10000) for _ in range(100)] table = db.create_table( "test", - data=pd.DataFrame( + data=pa.table( { "vector": vectors, "id": [i % 2 for i in range(100)], @@ -239,7 +238,7 @@ async def async_table(tmp_path) -> ldb.table.AsyncTable: count = [local_random.randint(1, 10000) for _ in range(100)] table = await db.create_table( "test", - data=pd.DataFrame( + data=pa.table( { "vector": vectors, "id": [i % 2 for i in range(100)], @@ -760,9 +759,9 @@ def test_search_order_by_ascending(table): def test_create_index_from_table(tmp_path, table): table.create_fts_index("text") - df = table.search("puppy").limit(5).select(["text"]).to_pandas() - assert len(df) <= 5 - assert "text" in df.columns + result = table.search("puppy").limit(5).select(["text"]).to_arrow() + assert len(result) <= 5 + assert "text" in result.column_names # Check whether it can be updated table.add( @@ -782,7 +781,7 @@ def test_create_index_from_table(tmp_path, table): table.create_fts_index("text") table.create_fts_index("text", replace=True) - assert len(table.search("gorilla").limit(1).to_pandas()) == 1 + assert len(table.search("gorilla").limit(1).to_arrow()) == 1 def test_create_index_multiple_columns(tmp_path, table): @@ -1832,3 +1831,120 @@ async def test_fts_fast_search_async(async_table): .to_list() ) assert len(results) > 0 + + +CODE_TEXT = "parseHTTPRequest user_id utf8" + + +def _token_texts(tokens): + return [token.text for token in tokens] + + +def test_tokenize_code_analyzer_flags(): + default = _token_texts(ldb.tokenize(CODE_TEXT, analyzer="code")) + assert default == _token_texts(ldb.tokenize(CODE_TEXT, base_tokenizer="code")) + + no_split = _token_texts( + ldb.tokenize(CODE_TEXT, analyzer="code", split_identifiers=False) + ) + split = _token_texts( + ldb.tokenize(CODE_TEXT, analyzer="code", split_identifiers=True) + ) + assert "parsehttprequest" in no_split + assert "parse" not in no_split + assert {"parse", "http", "request", "user", "id"} <= set(split) + + numerics = _token_texts( + ldb.tokenize( + CODE_TEXT, + analyzer="code", + split_identifiers=True, + split_on_numerics=True, + ) + ) + no_numerics = _token_texts( + ldb.tokenize( + CODE_TEXT, + analyzer="code", + split_identifiers=True, + split_on_numerics=False, + ) + ) + assert "utf" in numerics and "8" in numerics + assert "utf8" in no_numerics + + operators = _token_texts( + ldb.tokenize("a::b -> c != d", analyzer="code", index_operators=True) + ) + plain = _token_texts( + ldb.tokenize("a::b -> c != d", analyzer="code", index_operators=False) + ) + assert {"::", "->", "!="} <= set(operators) + assert not {"::", "->", "!="} & set(plain) + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"analyzer": "code", "base_tokenizer": "ngram"}, "requires base_tokenizer"), + ({"analyzer": "text", "base_tokenizer": "code"}, "requires analyzer='code'"), + ({"analyzer": "java"}, "analyzer must be"), + ({"split_identifiers": True}, "require analyzer='code'"), + ({"base_tokenizer": "raw", "index_operators": True}, "require analyzer='code'"), + ], +) +def test_code_analyzer_options_are_validated(mem_db, kwargs, message): + with pytest.raises(ValueError, match=message): + ldb.tokenize(CODE_TEXT, **kwargs) + + table = mem_db.create_table("t", data=[{"text": CODE_TEXT}]) + with pytest.raises(ValueError, match=message): + table.create_index("text", config=FTS(**kwargs)) + + +def test_code_analyzer_flags_false_are_allowed_for_text(mem_db): + tokens = ldb.tokenize("Running in cafés", split_identifiers=False) + assert _token_texts(tokens) == ["run", "cafe"] + + +def test_fts_code_analyzer_index_matches_subwords(mem_db): + table = mem_db.create_table( + "code", + data=[{"text": "def parseHTTPRequest(user_id): pass"}, {"text": "unrelated"}], + ) + table.create_index( + "text", + config=FTS(analyzer="code", split_identifiers=True, preserve_original=True), + ) + + details = table.list_indices()[0].index_details + assert details["base_tokenizer"] == "code" + assert details["split_identifiers"] is True + assert details["preserve_original"] is True + + for query in ["http", "request", "parseHTTPRequest"]: + rows = table.search(query, query_type="fts").to_list() + assert [row["text"] for row in rows] == ["def parseHTTPRequest(user_id): pass"] + + +def test_fts_code_analyzer_without_splitting_does_not_match_subwords(mem_db): + table = mem_db.create_table( + "code", data=[{"text": "def parseHTTPRequest(user_id): pass"}] + ) + table.create_index("text", config=FTS(analyzer="code", split_identifiers=False)) + + assert table.search("request", query_type="fts").to_list() == [] + assert len(table.search("parseHTTPRequest", query_type="fts").to_list()) == 1 + + +@pytest.mark.asyncio +async def test_async_fts_code_analyzer(mem_db_async): + table = await mem_db_async.create_table( + "code", data=[{"text": "def parseHTTPRequest(user_id): pass"}] + ) + await table.create_index( + "text", config=FTS(analyzer="code", split_identifiers=True) + ) + + rows = await table.query().nearest_to_text("http").to_list() + assert len(rows) == 1 diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index a61588777..050aeb3ea 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -20,7 +20,7 @@ import pyarrow as pa import pytest from lancedb import col -from lancedb.functions import FunctionVersion, udf +from lancedb.functions import FunctionDefinition, FunctionVersion, function FIXTURES = ( Path(__file__).parents[3] @@ -63,7 +63,7 @@ def helper_package(tmp_path, monkeypatch): return write -@udf +@function class scale: def __init__( self, @@ -114,11 +114,11 @@ def test_class_function_declares_inputs_output_and_initialization(): assert scale.registration_request.artifact.entrypoint == "scale" source = artifact(scale).decode() assert source.startswith("from __future__ import annotations\n") - assert "class scale:" in source and "@udf" not in source + assert "class scale:" in source and "@function" not in source def test_function_without_initialization_keeps_its_wire_form(): - @udf + @function def double(value: int) -> int: return value * 2 @@ -147,11 +147,11 @@ def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_pac """ module = helper_package("fx_batch_annotations", {"__init__.py": source}) with pytest.raises(TypeError, match="input_schema and output_schema"): - udf(module.identity) + function(module.identity) def test_array_batch_annotations_accept_explicit_schemas(): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), output_schema=pa.int64(), ) @@ -168,7 +168,7 @@ def test_array_batch_annotations_accept_explicit_schemas(): assert identity(values).equals(values) -@pytest.mark.parametrize("class_udf", [False, True]) +@pytest.mark.parametrize("class_function", [False, True]) @pytest.mark.parametrize("postponed", [False, True]) @pytest.mark.parametrize( ("annotation", "nullable"), @@ -185,13 +185,13 @@ def test_array_batch_annotations_accept_explicit_schemas(): ], ) def test_blob_reader_annotations_resolve_in_the_artifact( - helper_package, monkeypatch, class_udf, postponed, annotation, nullable + helper_package, monkeypatch, class_function, postponed, annotation, nullable ): definition = ( f"class read_blob:\n" f" def __call__(self, video: {annotation}) -> int:\n" f" return 0\n" - if class_udf + if class_function else f"def read_blob(video: {annotation}) -> int:\n return 0\n" ) module = helper_package( @@ -202,9 +202,9 @@ def test_blob_reader_annotations_resolve_in_the_artifact( + "import lancedb\n" "from typing import Optional\n" "from lancedb import BlobReader, BlobReader as Reader\n" - "from lancedb.functions import udf\n" + "from lancedb.functions import function\n" "MaybeReader = Optional[Reader]\n\n" - f"@udf\n{definition}" + f"@function\n{definition}" ) }, ) @@ -221,7 +221,7 @@ def test_blob_reader_annotations_resolve_in_the_artifact( namespace = {} exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace) packaged = namespace["read_blob"] - if class_udf: + if class_function: packaged = packaged.__call__ assert get_type_hints(packaged) == { "video": Optional[worker.BlobReader] if nullable else worker.BlobReader, @@ -237,11 +237,11 @@ def test_blob_reader_annotation_does_not_shadow_body_globals( { "__init__.py": """ from lancedb import BlobReader - from lancedb.functions import udf + from lancedb.functions import function _lance_blob_reader = 7 - @udf + @function def read_blob(video: BlobReader) -> int: return _lance_blob_reader """ @@ -280,14 +280,14 @@ def test_class_function_rejects_unsupported_initialization(init, message): namespace, ) with pytest.raises((TypeError, ValueError), match=message): - udf(namespace["bad"]) + function(namespace["bad"]) def test_class_function_requires_call_and_a_plain_close(): with pytest.raises(TypeError, match="synchronous __call__"): - udf(NoCall) + function(NoCall) with pytest.raises(TypeError, match="close must be a method taking no"): - udf(BadClose) + function(BadClose) def test_nested_class_and_closure_are_rejected_with_the_reason(): @@ -299,13 +299,13 @@ def test_nested_class_and_closure_are_rejected_with_the_reason(): return nested with pytest.raises(ValueError, match="defined at module level"): - udf(build()) + function(build()) factor = 3 with pytest.raises(ValueError, match="capture closure values"): - @udf + @function def closes_over(value: int) -> int: return value * factor @@ -372,10 +372,10 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source( """ import fx_helpers from fx_helpers.rate import TokenBucket - from lancedb import udf + from lancedb import function - @udf(code=[fx_helpers]) + @function(code=[fx_helpers]) class limited: def __init__(self, tpm: int): self.limiter = TokenBucket(tpm) @@ -388,9 +388,24 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source( def define(): sys.modules.pop("fx_helpers_functions", None) + importlib.invalidate_caches() return importlib.import_module("fx_helpers_functions").limited - first = define() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + first = define() + assert len(caught) == 1 + warning = str(caught[0].message) + assert "fx_helpers/fixtures/data.json" in warning + assert "fx_helpers/not-a-module.py" in warning + assert warning.index("fx_helpers/fixtures/data.json") < warning.index( + "fx_helpers/not-a-module.py" + ) + assert "remove 'fx_helpers' from code=" in warning + assert "pip=" in warning + assert "conda=" in warning + assert "__pycache__" not in warning + assert ".pyc" not in warning shipped = bundle_files(first) assert sorted(shipped) == [ "fx_helpers/__init__.py", @@ -406,7 +421,10 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source( helper_package( "fx_helpers", {**files, "rate.py": textwrap.dedent(files["rate.py"]) + "# v2\n"} ) - second = define() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + second = define() + assert len(caught) == 1 assert ( first.registration_request.artifact.digest != second.registration_request.artifact.digest @@ -414,6 +432,57 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source( assert first.registration_request.runtime == second.registration_request.runtime +def test_code_package_cache_artifacts_do_not_warn(helper_package): + cache = helper_package( + "fx_cache", + { + "__init__.py": "", + "__pycache__/ignored.cpython-312.pyc": "", + "stale.pyo": "", + }, + ) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + + @function(code=[cache]) + def cache_only(value: int) -> int: + return value + + assert not caught + assert sorted(bundle_files(cache_only)) == [ + "fx_cache/__init__.py", + "user_function.py", + ] + + +def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_package): + resources = helper_package( + "fx_resources", + { + "__init__.py": "", + "label-maps/labels.json": "{}", + }, + ) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + + @function(code=[resources]) + def resource_boundary(value: int) -> int: + return value + + assert len(caught) == 1 + warning = str(caught[0].message) + assert "fx_resources/label-maps/" in warning + assert "remove 'fx_resources' from code=" in warning + assert "labels.json" not in warning + assert sorted(bundle_files(resource_boundary)) == [ + "fx_resources/__init__.py", + "user_function.py", + ] + + def test_code_rejects_submodules_duplicates_and_non_modules(helper_package): helpers = helper_package("fx_rejects", {"__init__.py": "", "sub.py": ""}) import fx_rejects.sub @@ -426,7 +495,7 @@ def test_code_rejects_submodules_duplicates_and_non_modules(helper_package): ]: with pytest.raises((TypeError, ValueError), match=message): - @udf(code=code) + @function(code=code) def f(value: int) -> int: return value @@ -445,15 +514,16 @@ def test_local_module_outside_code_warns_at_registration(tmp_path, helper_packag textwrap.dedent( f""" from fx_local import normalize - from lancedb import udf + from lancedb import function - @udf({options}) + @function({options}) def {name}(value: int) -> int: return normalize(value) """ ) ) + importlib.invalidate_caches() return getattr(importlib.import_module(name), name) with pytest.warns(UserWarning, match=r"local module.*code=\[fx_local\]"): @@ -467,6 +537,132 @@ def test_local_module_outside_code_warns_at_registration(tmp_path, helper_packag assert "from fx_local import normalize" in artifact(installed).decode() +def test_local_module_imported_in_function_body_warns_at_registration( + tmp_path, helper_package +): + """A direct import inside the packaged definition is checked too.""" + helper_package( + "fx_body_local", + {"__init__.py": "def normalize(value):\n return value\n"}, + ) + sys.modules.pop("fx_body_local", None) + + def define(name, options): + (tmp_path / f"{name}.py").write_text( + textwrap.dedent( + f""" + from lancedb import function + + + @function({options}) + def {name}(value: int) -> int: + import fx_body_local + + return fx_body_local.normalize(value) + """ + ) + ) + importlib.invalidate_caches() + return getattr(importlib.import_module(name), name) + + with pytest.warns(UserWarning, match=r"local module.*code=\[fx_body_local\]"): + local = define("fx_body_uses_local", "") + assert "import fx_body_local" in artifact(local).decode() + + with warnings.catch_warnings(): + warnings.simplefilter("error") + installed = define("fx_body_uses_installed", "pip=['fx-body-local==1.0']") + assert "import fx_body_local" in artifact(installed).decode() + + +def test_missing_module_without_declared_package_warns_at_registration( + tmp_path, monkeypatch +): + package = "fx_missing_remote_package_ent3448" + monkeypatch.syspath_prepend(str(tmp_path)) + + def define(name): + (tmp_path / f"{name}.py").write_text( + textwrap.dedent( + f""" + from lancedb import function + + + @function(pip=()) + def {name}(value: int) -> int: + import {package}.plugin + + return value + """ + ) + ) + importlib.invalidate_caches() + return getattr(importlib.import_module(name), name) + + with pytest.warns(UserWarning) as caught: + definition = define("fx_uses_missing_package") + + message = str(caught[0].message) + assert f"imports {package!r}" in message + assert "unavailable in the client environment" in message + assert "no declared pip/conda dependencies" in message + assert "Remote availability cannot be verified" in message + assert "confirm that the base image provides it" in message + assert "cannot import" not in message + assert f"import {package}.plugin" in artifact(definition).decode() + + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + with pytest.raises(UserWarning, match="Remote availability cannot be verified"): + define("fx_missing_package_as_error") + + +def test_resolved_or_declared_module_imports_do_not_warn(tmp_path, helper_package): + package = "fx_missing_remote_package_ent3448" + helper_package("fx_declared_code_package", {"__init__.py": ""}) + + def define(name, body, options, imports=""): + (tmp_path / f"{name}.py").write_text( + textwrap.dedent( + f""" + {imports} + from lancedb import function + + + @function({options}) + def {name}(value: int) -> int: + {body} + return value + """ + ) + ) + importlib.invalidate_caches() + return getattr(importlib.import_module(name), name) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + define("fx_imports_stdlib", "import os.path", "") + # Distribution names need not match the imported top-level module. + define( + "fx_imports_declared_pip", + f"import {package}.plugin", + "pip=['Pillow>=10']", + ) + define( + "fx_imports_declared_conda", + f"import {package}.plugin", + "conda=['numpy']", + ) + define( + "fx_imports_shipped_code", + "import fx_declared_code_package", + "code=[fx_declared_code_package]", + "import fx_declared_code_package", + ) + + assert not caught + + MMLB_HELPERS = { "__init__.py": "", "rate.py": """ @@ -502,20 +698,20 @@ import pyarrow as pa import fx_mmlb from fx_mmlb.embedding import OpenAIEmbedder -from lancedb import udf +from lancedb import function TEXT = pa.schema([pa.field("text", pa.string())]) EMBEDDING = pa.list_(pa.field("item", pa.float64(), nullable=False)) -@udf(code=[fx_mmlb], input_schema=TEXT, output_schema=EMBEDDING) +@function(code=[fx_mmlb], input_schema=TEXT, output_schema=EMBEDDING) class openai_embedding_batch(OpenAIEmbedder): def __call__(self, text: pa.Array) -> pa.Array: item = pa.field("item", pa.float64(), nullable=False) return pa.array(self.embed(text.to_pylist()), pa.list_(item)) -@udf(code=[fx_mmlb]) +@function(code=[fx_mmlb]) class openai_embedding(OpenAIEmbedder): def __call__(self, text: str) -> list[float]: return self.embed([text])[0] @@ -527,6 +723,7 @@ def test_shared_helpers_construct_state_on_every_path(tmp_path, helper_package): initialized through the same helper, so neither path can skip it.""" helper_package("fx_mmlb", MMLB_HELPERS) (tmp_path / "fx_mmlb_functions.py").write_text(MMLB_FUNCTIONS) + importlib.invalidate_caches() functions = importlib.import_module("fx_mmlb_functions") signatures = [ @@ -586,7 +783,7 @@ def test_main_definitions_travel_by_source(tmp_path): import math from dataclasses import dataclass - from lancedb import udf + from lancedb import function SCALE = 2 @@ -605,7 +802,7 @@ def test_main_definitions_travel_by_source(tmp_path): return helper(value) * self.settings.factor - @udf + @function class scaled(Base): def __init__(self, factor: int): self.settings = Settings(factor) @@ -641,11 +838,11 @@ def test_main_lambdas_are_rejected(tmp_path): script.write_text( textwrap.dedent( """ - from lancedb import udf + from lancedb import function double = lambda value: value * 2 - @udf + @function def uses_lambda(value: int) -> int: return double(value) """ @@ -656,3 +853,33 @@ def test_main_lambdas_are_rejected(tmp_path): ) assert result.returncode != 0 assert "not lambdas, closures, or nested definitions" in result.stderr + + +def test_udf_alias_warns_and_packages_like_function(helper_package): + def source(decorator: str) -> str: + return f""" + import lancedb + from lancedb import function, udf + + @{decorator} + def double(value: int) -> int: + return value * 2 + """ + + current = helper_package("fx_alias_current", {"__init__.py": source("function")}) + expected = current.double.registration_request.artifact.digest + for name, decorator in (("fx_alias_bare", "udf"), ("fx_alias_attr", "lancedb.udf")): + with pytest.warns(DeprecationWarning, match="lancedb.udf is deprecated"): + module = helper_package(name, {"__init__.py": source(decorator)}) + assert isinstance(module.double, FunctionDefinition) + assert "udf" not in artifact(module.double).decode() + assert module.double.registration_request.artifact.digest == expected + + +def test_udf_definition_alias_warns(): + with pytest.warns(DeprecationWarning, match="UdfDefinition is deprecated"): + from lancedb import UdfDefinition + assert UdfDefinition is FunctionDefinition + with pytest.warns(DeprecationWarning, match="UdfDefinition is deprecated"): + from lancedb.functions import UdfDefinition as module_alias + assert module_alias is FunctionDefinition diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index c432bac59..443fdebc4 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -103,6 +103,7 @@ async def test_async_hybrid_query_filters(table: AsyncTable): async def test_hybrid_query_with_stale_fixed_size_binary_prefilter( tmpdir_factory, ): + pytest.importorskip("lance") tmp_path = str(tmpdir_factory.mktemp("stale_scalar_prefilter")) db = await lancedb.connect_async(tmp_path) diff --git a/python/python/tests/test_import.py b/python/python/tests/test_import.py index e8373b03b..6f9b00e5d 100644 --- a/python/python/tests/test_import.py +++ b/python/python/tests/test_import.py @@ -34,9 +34,23 @@ def test_native_extension_does_not_link_openssl(): ) -def test_top_level_version_comes_from_native_module(): +@pytest.mark.parametrize( + "native_version, expected_version", + [ + ("0.41.0", "0.41.0"), + ("0.41.0-alpha.1", "0.41.0a1"), + ("0.41.0-beta.17", "0.41.0b17"), + ("0.41.0-rc.1", "0.41.0rc1"), + ("0.41.0-dev.1", "0.41.0.dev1"), + ], +) +def test_top_level_version_comes_from_native_module(native_version, expected_version): child_code = """ +import importlib import importlib.metadata +import sys + +from packaging.version import Version orig_version = importlib.metadata.version @@ -51,13 +65,17 @@ import lancedb import lancedb._lancedb as native_module import lancedb.db -assert lancedb.__version__ == native_module.__version__ +assert lancedb.__version__ == str(Version(native_module.__version__)) + +native_module.__version__ = sys.argv[1] +importlib.reload(lancedb) +assert lancedb.__version__ == sys.argv[2] """ env = os.environ.copy() env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path) result = subprocess.run( - [sys.executable, "-c", child_code], + [sys.executable, "-c", child_code, native_version, expected_version], check=False, capture_output=True, text=True, diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index a1ec1e04b..1b252f993 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -21,6 +21,7 @@ from lancedb.index import ( Bitmap, LabelList, Fm, + NGram, HnswPq, HnswSq, HnswFlat, @@ -248,6 +249,36 @@ async def test_create_fm_index(some_table: AsyncTable): assert indices[0].columns == ["data"] +@pytest.mark.asyncio +async def test_create_ngram_index(db_async): + # NGram indexes accelerate substring filters on UTF-8 string columns. + data = pa.table( + { + "id": list(range(5)), + "text": ["cat", "category", "concatenate", "dog", "cathedral"], + } + ) + table = await db_async.create_table("ngram_table", data) + await table.create_index("text", config=NGram()) + + indices = await table.list_indices() + assert len(indices) == 1 + assert indices[0].index_type == "NGram" + assert indices[0].columns == ["text"] + + stats = await table.index_stats(indices[0].name) + assert stats.index_type == "NGRAM" + assert stats.num_indexed_rows == await table.count_rows() + assert stats.num_unindexed_rows == 0 + + # The index accelerates substring predicates without changing their results. + result = await table.query().where("contains(text, 'cat')").to_arrow() + assert sorted(result["id"].to_pylist()) == [0, 1, 2, 4] + + plan = await table.query().where("contains(text, 'cat')").explain_plan() + assert "ScalarIndexQuery" in plan + + @pytest.mark.asyncio async def test_create_bitmap_index(some_table: AsyncTable): await some_table.create_index("id", config=Bitmap()) @@ -559,6 +590,7 @@ def test_index_statistics_index_type_lists_all_supported_values(): "BTREE", "BITMAP", "LABEL_LIST", + "NGRAM", } assert ( diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py new file mode 100644 index 000000000..c3189cbad --- /dev/null +++ b/python/python/tests/test_job.py @@ -0,0 +1,708 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import asyncio +import time +from datetime import timedelta +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from lancedb.exceptions import JobCancelledError, JobFailedError +from lancedb.job import AsyncJob, Job, _progress_eta +from lancedb.remote.errors import HttpError, RetryError + + +@pytest.fixture(params=["async", "sync"]) +def wait_job(request): + async def wait(inner, timeout=None, result_decoder=None): + job = AsyncJob(inner, result_decoder) + if request.param == "sync": + return await asyncio.to_thread(Job(job).wait, timeout) + return await job.wait(timeout) + + return wait + + +def transport_error(kind): + if kind == "http": + return HttpError("error sending request", "req-1", is_transport_error=True) + error = RetryError("retries exhausted", "req-1", 0, 3, 0, 3, 3, 3, None) + error.__cause__ = transport_error("http") + return error + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["http", "retry"]) +async def test_wait_recovers_from_transport_errors(wait_job, kind, monkeypatch): + inner = MagicMock(id="job-1", job_type=None) + inner.wait = AsyncMock(side_effect=[transport_error(kind), '{"rows": 7}']) + inner.status = AsyncMock(side_effect=[transport_error(kind), "running"]) + sleep = AsyncMock() + monkeypatch.setattr("lancedb.job.asyncio.sleep", sleep) + + result = await wait_job( + inner, timedelta(hours=24), result_decoder=lambda value: ("decoded", value) + ) + + assert result == ("decoded", '{"rows": 7}') + assert inner.wait.await_count == 2 + assert inner.status.await_count == 2 + assert [call.args[0] for call in sleep.await_args_list] == [0.25, 0.5] + inner.cancel.assert_not_called() + + +@pytest.mark.asyncio +async def test_wait_disconnection_timeout_explains_how_to_reconnect(wait_job): + error = transport_error("http") + inner = MagicMock(id="job-1", job_type=None) + inner.wait = AsyncMock(side_effect=error) + inner.status = AsyncMock(side_effect=error) + + with pytest.raises( + ConnectionError, match="job 'job-1' may still be running" + ) as exc: + await wait_job(inner, timedelta(milliseconds=10)) + + assert "db.open_job('job-1')" in str(exc.value) + assert "call wait()" in str(exc.value) + assert exc.value.__cause__ is error + inner.cancel.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "error", + [ + HttpError("unauthorized", "req-1", 401), + HttpError("not found", "req-1", 404), + HttpError( + "secret not found", + "req-1", + 404, + error_code="not_found", + resource_kind="secret", + ), + HttpError("failed to parse job description", "req-1"), + RetryError("service unavailable", "req-1", 3, 0, 0, 3, 3, 3, 503), + JobFailedError("worker failed"), + JobCancelledError("job cancelled"), + ], +) +async def test_wait_propagates_permanent_and_terminal_errors(wait_job, error): + inner = MagicMock(id="job-1") + inner.wait = AsyncMock(side_effect=error) + + with pytest.raises(type(error)) as exc: + await wait_job(inner, timedelta(seconds=1)) + + assert exc.value is error + assert inner.wait.await_count == 1 + inner.status.assert_not_called() + + +@pytest.mark.asyncio +async def test_wait_running_job_timeout_is_not_a_connection_error(wait_job): + async def running(): + await asyncio.Event().wait() + + inner = MagicMock(id="job-1") + inner.wait = AsyncMock(side_effect=running) + with pytest.raises(TimeoutError): + await wait_job(inner, timedelta(milliseconds=10)) + inner.cancel.assert_not_called() + + +@pytest.mark.asyncio +async def test_wait_completed_job(wait_job): + assert await wait_job(None) is None + + +@pytest.mark.asyncio +async def test_wait_retries_without_a_timeout_and_caps_backoff(wait_job, monkeypatch): + inner = MagicMock(id="job-1", job_type=None) + inner.wait = AsyncMock(side_effect=[transport_error("http"), None]) + inner.status = AsyncMock(side_effect=[transport_error("retry")] * 9 + ["running"]) + sleep = AsyncMock() + monkeypatch.setattr("lancedb.job.asyncio.sleep", sleep) + + assert await wait_job(inner) is None + assert [call.args[0] for call in sleep.await_args_list] == [ + 0.25, + 0.5, + 1, + 2, + 4, + 8, + 16, + 30, + 30, + 30, + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("job_type", [None, "query"]) +async def test_wait_timeout_after_recovery_is_not_a_connection_error( + wait_job, monkeypatch, job_type +): + async def running(): + await asyncio.Event().wait() + + inner = MagicMock(id="job-1", job_type=job_type) + inner.wait = AsyncMock() + + async def wait(): + if inner.wait.await_count == 1: + raise transport_error("http") + return await running() + + inner.wait.side_effect = wait + inner.status = AsyncMock(return_value="running") + monkeypatch.setattr("lancedb.job.asyncio.sleep", AsyncMock()) + + with pytest.raises(TimeoutError) as exc: + await wait_job(inner, timedelta(milliseconds=10)) + message = str(exc.value) + assert "still running after 0.01 seconds" in message + assert "continues on the server" in message + if job_type == "query": + assert "keep this handle to continue waiting" in message + assert "db.open_job" not in message + else: + assert "db.open_job('job-1').wait()" in message + assert inner.status.await_count == 1 + assert inner.wait.await_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "error", [JobFailedError("failed"), JobCancelledError("cancel")] +) +async def test_wait_reports_terminal_error_after_recovery(wait_job, monkeypatch, error): + inner = MagicMock(id="job-1", job_type=None) + inner.wait = AsyncMock(side_effect=[transport_error("retry"), error]) + inner.status = AsyncMock(return_value="running") + monkeypatch.setattr("lancedb.job.asyncio.sleep", AsyncMock()) + + with pytest.raises(type(error)) as exc: + await wait_job(inner, timedelta(seconds=1)) + assert exc.value is error + assert inner.wait.await_count == 2 + + +@pytest.mark.asyncio +async def test_wait_cancellation_interrupts_backoff(monkeypatch): + inner = MagicMock(id="job-1", job_type=None) + inner.wait = AsyncMock(side_effect=transport_error("http")) + sleeping = asyncio.Event() + + async def sleep(delay): + sleeping.set() + await asyncio.Event().wait() + + monkeypatch.setattr("lancedb.job.asyncio.sleep", sleep) + task = asyncio.create_task(AsyncJob(inner).wait()) + await asyncio.wait_for(sleeping.wait(), 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + inner.cancel.assert_not_called() + + +@pytest.mark.asyncio +async def test_query_wait_disconnection_does_not_suggest_open_job(wait_job): + inner = MagicMock(id="query-1", job_type="query") + inner.wait = AsyncMock(side_effect=transport_error("http")) + + with pytest.raises(ConnectionError) as exc: + await wait_job(inner, timedelta(milliseconds=10)) + + assert "query-1" in str(exc.value) + assert "this job handle" in str(exc.value) + assert "open_job" not in str(exc.value) + + +class _PendingJob: + id = "job-timeout" + job_type = None + + async def wait(self): + await asyncio.sleep(60) + + +class _PendingQuery: + id = "query-timeout" + job_type = "query" + + async def wait(self): + await asyncio.sleep(60) + + +class _ProgressJob: + id = "job-progress" + job_type = "refresh_column" + + async def status(self): + return "finished" + + async def wait(self, progress=None): + if progress is not None: + progress({"state": "running", "rows_planned": 4, "rows_computed": 2}) + progress({"state": "finished", "rows_planned": 4, "rows_computed": 4}) + return None + + +def _assert_timeout(error: TimeoutError) -> None: + message = str(error) + assert "job 'job-timeout' still running after 0.01 seconds" in message + assert "continues on the server" in message + assert "db.open_job('job-timeout').wait()" in message + + +@pytest.mark.asyncio +async def test_async_job_wait_timeout_explains_reattach(): + job = AsyncJob(_PendingJob()) + + with pytest.raises(TimeoutError) as exc_info: + await job.wait(timeout=timedelta(seconds=0.01)) + + _assert_timeout(exc_info.value) + + +def test_job_wait_timeout_explains_reattach(): + job = Job(AsyncJob(_PendingJob())) + + with pytest.raises(TimeoutError) as exc_info: + job.wait(timeout=timedelta(seconds=0.01)) + + _assert_timeout(exc_info.value) + + +@pytest.mark.asyncio +async def test_progress_is_additive_to_string_status_and_returns_none_locally(): + inner = MagicMock(id="job-progress", job_type="refresh_column") + inner.status = AsyncMock(return_value="running") + inner._description = type( + "Description", (), {"progress": {"state": "running", "rows_computed": 2}} + )() + job = AsyncJob(inner) + + assert await job.status() == "running" + assert await job.progress() == {"state": "running", "rows_computed": 2} + assert await AsyncJob(None).progress() is None + assert await AsyncJob(_ProgressJob()).progress() is None + assert Job(AsyncJob(None)).progress() is None + + +def test_progress_eta_uses_two_stable_advancing_same_epoch_samples(): + now = int(time.time() * 1_000) + previous = { + "state": "running", + "execution_epoch": 7, + "sample_at_millis": now - 1_000, + "rows_planned": 100, + "rows_computed": 20, + "rows_skipped": 0, + "rows_remaining": 80, + "fragments_planned": 4, + } + current = { + **previous, + "sample_at_millis": now, + "rows_computed": 40, + "rows_remaining": 60, + } + assert _progress_eta(previous, current) == 3_000 + assert _progress_eta(previous, {**current, "rows_planned": 120}) is None + assert _progress_eta(previous, {**current, "execution_epoch": 8}) is None + assert _progress_eta(previous, {**current, "rows_computed": 20}) is None + stale = { + **current, + "sample_at_millis": now - 11 * 60 * 1_000, + } + assert ( + _progress_eta({**previous, "sample_at_millis": now - 12 * 60 * 1_000}, stale) + is None + ) + assert _progress_eta(previous, {**current, "state": "finished"}) is None + assert ( + _progress_eta(previous, {**current, "state": "finished", "rows_remaining": 0}) + == 0 + ) + + +@pytest.mark.asyncio +async def test_progress_retains_eta_from_same_handle_observations(): + now = int(time.time() * 1_000) + first = { + "state": "running", + "execution_epoch": 7, + "sample_at_millis": now - 1_000, + "rows_planned": 100, + "rows_computed": 20, + "rows_skipped": 0, + "rows_remaining": 80, + "fragments_planned": 4, + } + second = { + **first, + "sample_at_millis": now, + "rows_computed": 40, + "rows_remaining": 60, + } + inner = MagicMock(id="job-progress", job_type="refresh_column") + inner.status = AsyncMock(return_value="running") + description = type("Description", (), {"progress": first})() + inner._description = description + job = AsyncJob(inner) + + assert await job.progress() == first + description.progress = second + assert (await job.progress())["estimated_remaining_time_millis"] == 3_000 + + +@pytest.mark.asyncio +async def test_wait_progress_callback_observes_backend_poll_updates(): + updates = [] + + result = await AsyncJob(_ProgressJob()).wait(progress=updates.append) + + assert result is None + assert updates == [ + {"state": "running", "rows_planned": 4, "rows_computed": 2}, + {"state": "finished", "rows_planned": 4, "rows_computed": 4}, + ] + + +@pytest.mark.asyncio +async def test_wait_progress_callback_uses_the_public_eta_enrichment(monkeypatch): + now = 10_000_000 + monkeypatch.setattr("lancedb.job.time.time", lambda: now / 1_000) + + class EtaJob: + id = "job-eta" + job_type = "refresh_column" + + async def wait(self, progress): + first = { + "state": "running", + "execution_epoch": 7, + "sample_at_millis": now - 1_000, + "rows_planned": 100, + "rows_computed": 20, + "rows_skipped": 0, + "rows_remaining": 80, + "fragments_planned": 4, + } + progress(first) + progress( + { + **first, + "sample_at_millis": now, + "rows_computed": 40, + "rows_remaining": 60, + } + ) + + updates = [] + assert await AsyncJob(EtaJob()).wait(progress=updates.append) is None + + assert "estimated_remaining_time_millis" not in updates[0] + assert updates[1]["estimated_remaining_time_millis"] == 3_000 + + +@pytest.mark.asyncio +async def test_wait_progress_true_updates_and_closes_only_the_owned_bar(monkeypatch): + tqdm_module = pytest.importorskip("tqdm.auto") + + class Bar: + def __init__(self): + self.total = None + self.updates = [] + self.phases = [] + self.closed = False + + def update(self, delta): + self.updates.append(delta) + + def set_postfix_str(self, phase): + self.phases.append(phase) + + def close(self): + self.closed = True + + bar = Bar() + monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar) + + assert await AsyncJob(_ProgressJob()).wait(progress=True) is None + assert bar.total == 4 + assert bar.updates == [2, 2] + assert bar.phases == ["running", "finished"] + assert bar.closed + + +@pytest.mark.asyncio +async def test_wait_progress_bar_resumes_caller_owned_bar_after_timeout(): + class ResumableJob: + id = "job-resume" + job_type = "refresh_column" + + def __init__(self, bar): + self.calls = 0 + self.bar = bar + + async def wait(self, progress): + self.calls += 1 + if self.calls == 1: + progress( + { + "state": "running", + "execution_epoch": 1, + "rows_planned": 4, + "rows_remaining": 2, + } + ) + await asyncio.sleep(0.1) + else: + progress( + { + "state": "running", + "execution_epoch": 2, + "rows_planned": 4, + "rows_remaining": 3, + } + ) + assert self.bar.n == 1 + progress( + { + "state": "finished", + "execution_epoch": 2, + "rows_planned": 4, + "rows_remaining": 0, + } + ) + + class Bar: + def __init__(self): + self.total = None + self.n = 0 + self.updates = [] + + def update(self, delta): + self.updates.append(delta) + self.n += delta + + def set_postfix_str(self, _phase): + pass + + bar = Bar() + job = AsyncJob(ResumableJob(bar)) + + with pytest.raises(TimeoutError): + await job.wait(timeout=timedelta(seconds=0.01), progress=bar) + + assert await job.wait(progress=bar) is None + assert bar.total == 4 + assert bar.n == 4 + assert bar.updates == [2, 3] + + +@pytest.mark.asyncio +async def test_wait_progress_bar_resets_display_for_new_plan_or_epoch(): + class ReplannedJob: + id = "job-replanned" + job_type = "refresh_column" + + async def wait(self, progress): + progress( + { + "state": "running", + "execution_epoch": 1, + "rows_planned": 6, + "rows_remaining": 2, + } + ) + progress( + { + "state": "running", + "execution_epoch": 1, + "rows_planned": 4, + "rows_remaining": 3, + } + ) + progress( + { + "state": "running", + "execution_epoch": 2, + "rows_planned": 4, + "rows_remaining": 3, + } + ) + progress( + { + "state": "finished", + "execution_epoch": 2, + "rows_planned": 4, + "rows_remaining": 0, + } + ) + + class Bar: + def __init__(self): + self.total = None + self.n = 0 + self.updates = [] + self.resets = [] + + def update(self, delta): + self.updates.append(delta) + self.n += delta + + def reset(self, total=None): + self.resets.append(total) + self.total = total + self.n = 0 + + def set_postfix_str(self, _phase): + pass + + bar = Bar() + + assert await AsyncJob(ReplannedJob()).wait(progress=bar) is None + assert bar.total == 4 + assert bar.n == 4 + assert bar.n <= bar.total + assert bar.resets == [4, 4] + assert bar.updates == [4, 1, 1, 3] + + +@pytest.mark.asyncio +async def test_wait_progress_bar_uses_remaining_rows_when_computation_is_repeated( + monkeypatch, +): + tqdm_module = pytest.importorskip("tqdm.auto") + + class Bar: + def __init__(self): + self.total = None + self.updates = [] + self.closed = False + + def update(self, delta): + self.updates.append(delta) + + def set_postfix_str(self, _phase): + pass + + def close(self): + self.closed = True + + class RepeatedComputationJob: + id = "job-recomputed" + job_type = "refresh_column" + + async def wait(self, progress): + progress( + { + "state": "running", + "rows_planned": 4, + "rows_computed": 6, + "rows_remaining": 2, + } + ) + progress( + { + "state": "finished", + "rows_planned": 4, + "rows_computed": 8, + "rows_remaining": 0, + } + ) + + bar = Bar() + monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar) + + assert await AsyncJob(RepeatedComputationJob()).wait(progress=True) is None + assert bar.total == 4 + assert bar.updates == [2, 2] + assert bar.closed + + +@pytest.mark.asyncio +async def test_wait_progress_bar_tracks_late_planning_without_regressing( + monkeypatch, +): + tqdm_module = pytest.importorskip("tqdm.auto") + + class Bar: + def __init__(self): + self.total = None + self.updates = [] + self.closed = False + + def update(self, delta): + self.updates.append(delta) + + def set_postfix_str(self, _phase): + pass + + def close(self): + self.closed = True + + class RegressingPlanJob: + id = "job-regressing-plan" + job_type = "refresh_column" + + async def wait(self, progress): + samples = [ + (0, 0), + (4, 2), + (4, 3), + (4, 2), + (6, 1), + (6, 0), + ] + for planned, remaining in samples: + progress( + { + "state": "running", + "rows_planned": planned, + "rows_remaining": remaining, + } + ) + + bar = Bar() + monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar) + + assert await AsyncJob(RegressingPlanJob()).wait(progress=True) is None + assert bar.total == 6 + # The remaining-row dip at (4, 3) must not rewind the high-water mark. + assert bar.updates == [2, 3, 1] + assert bar.closed + + +@pytest.mark.asyncio +async def test_wait_progress_false_keeps_legacy_inner_wait_call(): + class NoProgressArgument: + id = "job-legacy" + job_type = None + + async def wait(self): + return None + + assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None + + +@pytest.mark.asyncio +async def test_query_wait_timeout_requires_keeping_original_handle(): + job = AsyncJob(_PendingQuery()) + + with pytest.raises(TimeoutError) as exc_info: + await job.wait(timeout=timedelta(seconds=0.01)) + + message = str(exc_info.value) + assert "query 'query-timeout' still running after 0.01 seconds" in message + assert "continues on the server" in message + assert "keep this handle to continue waiting" in message + assert "db.open_job" not in message diff --git a/python/python/tests/test_listing.py b/python/python/tests/test_listing.py index 4cf37b631..cc1c44e90 100644 --- a/python/python/tests/test_listing.py +++ b/python/python/tests/test_listing.py @@ -84,7 +84,7 @@ async def advance(items, asynchronous): return await items.__anext__() if asynchronous else next(items) -KINDS = ["secrets", "views", "jobs", "functions"] +KINDS = ["jobs"] @pytest.mark.asyncio diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 891b49164..bf964102b 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -63,7 +63,17 @@ def mock_remote_materialized_view_refresh(): @pytest.mark.parametrize("sync", [False, True]) @pytest.mark.parametrize("background", [False, True]) @pytest.mark.parametrize("full", [False, True]) -async def test_remote_refresh_reports_unknown_metrics(sync, background, full): +@pytest.mark.parametrize( + "resources", + [ + {}, + {"gpu_count": 2, "gpu_class": "h100"}, + {"cpu_millis": 8000, "memory_bytes": 16 * 1024**3, "gpu_count": 0}, + ], +) +async def test_remote_refresh_reports_unknown_metrics( + sync, background, full, resources +): flight = pytest.importorskip("pyarrow.flight") class RefreshServer(flight.FlightServerBase): @@ -90,7 +100,7 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full): mock_remote_materialized_view_refresh() as (host, requests), RefreshServer() as server, ): - options = {"full": True} if full else {} + options = {"full": full, **resources} connect = lancedb.connect if sync else lancedb.connect_async db = connect( "db://dev", @@ -140,7 +150,28 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full): ) (refresh,) = refreshes assert b'REFRESH MATERIALIZED VIEW "view"' in refresh - assert (b"WITH (full = true)" in refresh) is full + assert (b"full = true" in refresh) is full + for key, value in resources.items(): + expected = ( + f"{key} = '{value}'" if key == "gpu_class" else f"{key} = {value}" + ) + assert expected.encode() in refresh + previous = len(server.commands) + for invalid in [ + {"cpu_millis": 0}, + {"memory_bytes": 1}, + {"gpu_count": -1}, + {"gpu_count": True}, + {"gpu_count": 2**32}, + {"gpu_class": "H200:8"}, + {"gpu_count": 0, "gpu_class": "h100"}, + ]: + with pytest.raises(ValueError): + if sync: + view.refresh(**invalid) + else: + await view.refresh(**invalid) + assert len(server.commands) == previous assert not any("count_rows" in path for path in requests) @@ -725,7 +756,7 @@ def test_embedded_create_refuses_automatic_refresh_before_creating_view( tmp_path, options ): db = make_db(tmp_path) - with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"): + with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"): db.create_materialized_view("adults", "people", **options) assert "adults" not in db.table_names() @@ -742,7 +773,7 @@ def test_remote_create_rejects_invalid_interval_without_request(seconds): @pytest.mark.experimental_functions def test_namespace_forwards_automatic_refresh_request(tmp_path): db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) - with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"): + with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"): db.create_materialized_view("mv", "source", auto_refresh_enabled=True) @@ -750,7 +781,7 @@ def test_namespace_forwards_automatic_refresh_request(tmp_path): @pytest.mark.asyncio async def test_async_namespace_forwards_automatic_refresh_request(tmp_path): db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}) - with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"): + with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"): await db.create_materialized_view("mv", "source", auto_refresh_enabled=True) diff --git a/python/python/tests/test_merge_insert_lsm.py b/python/python/tests/test_merge_insert_lsm.py index c7d69d779..f5280383c 100644 --- a/python/python/tests/test_merge_insert_lsm.py +++ b/python/python/tests/test_merge_insert_lsm.py @@ -278,7 +278,7 @@ def test_lsm_read_unsupported_shape_errors_without_use_rte_false(tmp_path): # with_row_id is unsupported by the LSM scanner; on an RTE table the default # (auto-routed) read hard-errors instead of silently reading a stale base. - with pytest.raises(Exception): + with pytest.raises(Exception, match=r"with_row_id.*use_rte\(false\)"): table.search().with_row_id(True).to_arrow() # use_rte(False) is the escape hatch: it reads the base table only. @@ -563,19 +563,28 @@ def test_lsm_read_time_travel_errors(tmp_path): assert sorted(base["id"].to_pylist()) == [1, 2, 3] -def test_lsm_read_take_row_ids_errors(tmp_path): +@pytest.mark.parametrize("with_row_id", [False, True]) +@pytest.mark.parametrize("use_rte", [None, True]) +def test_lsm_read_take_row_ids_errors(tmp_path, with_row_id, use_rte): db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0)) table = db.create_table("t", _reader([1, 2, 3])) table.set_unenforced_primary_key("id") table.enable_rte(RTEWriteSpec.unsharded()) _lsm_upsert(table, [4]) - # take-by-row-id auto-routes through the LSM scanner, which has no stable _rowid, - # so it hard-errors instead of failing with an opaque column-not-found error. - with pytest.raises(Exception, match="row id"): - table.take_row_ids([0, 1]).to_arrow() + # Automatic and explicit RTE routing must explain the unsupported take, + # including when row IDs are only requested internally for ordering. + take = table.take_row_ids([1, 0, 1, 2**64 - 1], with_row_id=with_row_id) + if use_rte is not None: + take = take.use_rte(use_rte) + with pytest.raises(Exception, match=r"take by row id.*use_rte\(false\)"): + take.to_arrow() # use_rte(False) is the escape hatch: it reads the base table. - base = table.take_row_ids([0, 1]).use_rte(False).to_arrow() - assert base.num_rows == 2 + base = take.use_rte(False).to_arrow() + assert base["id"].to_pylist() == [2, 1, 2] + assert base["value"].to_pylist() == [1, 0, 1] + assert ("_rowid" in base.column_names) == with_row_id + if with_row_id: + assert base["_rowid"].to_pylist() == [1, 0, 1] def test_lsm_read_fts_postfilter_errors(tmp_path): diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 663172e77..5eb9c02bd 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -11,13 +11,20 @@ import http.server import json from urllib.parse import parse_qs, unquote, urlparse import pytest +import builtins +import copy import pyarrow as pa import lancedb from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from utils import start_server_thread from lancedb.listing import AsyncListing, Listing from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY -from lancedb.namespace import _MAX_QUERY_K, _query_to_namespace_request +from lancedb.namespace import ( + _MAX_QUERY_K, + LanceNamespace, + LanceNamespaceDBConnection, + _query_to_namespace_request, +) from lancedb.query import Query from lancedb.table import AsyncTable, LanceTable @@ -31,6 +38,7 @@ class TestNamespaceCreateTableOptions: @pytest.mark.parametrize("version", ["legacy", "stable"]) @pytest.mark.parametrize("empty", [False, True]) def test_deprecated_storage_version(self, tmp_path, version, empty): + pytest.importorskip("lance") db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "namespace")}) data = None if empty else [{"id": 1}] schema = pa.schema([("id", pa.int64())]) @@ -64,6 +72,7 @@ class TestNamespaceCreateTableOptions: @pytest.mark.parametrize("version", ["legacy", "stable"]) @pytest.mark.parametrize("empty", [False, True]) async def test_deprecated_storage_version_async(self, tmp_path, version, empty): + pytest.importorskip("lance") root = str(tmp_path / "namespace") db = lancedb.connect_namespace_async("dir", {"root": root}) data = None if empty else [{"id": 1}] @@ -166,6 +175,9 @@ class _FailingSyncInner: async def to_arrow(self): raise RuntimeError("direct table to_arrow should not be used") + async def _execute_query(self, query, **kwargs): + raise RuntimeError("local execution reached") + class _FailingAsyncInner: def name(self): @@ -441,13 +453,14 @@ class TestNamespaceConnection: assert len(table_names) == 1 # Verify empty table - result = table.to_pandas() + result = table.to_arrow() assert len(result) == 0 - assert list(result.columns) == ["id", "vector", "text"] + assert result.column_names == ["id", "vector", "text"] def test_table_to_pandas_blob_lazy_through_namespace(self): """Namespace-backed tables should use Lance blob-aware pandas conversion.""" pytest.importorskip("lance") + pytest.importorskip("pandas") db = lancedb.connect_namespace("dir", {"root": self.temp_dir}) db.create_namespace(["test_ns"]) data = pa.table( @@ -504,9 +517,9 @@ class TestNamespaceConnection: assert table.id == "test_ns$test_table" # Verify empty table with correct schema - result = table.to_pandas() + result = table.to_arrow() assert len(result) == 0 - assert list(result.columns) == ["id", "vector"] + assert result.column_names == ["id", "vector"] def test_drop_table_through_namespace(self): """Test dropping a table through namespace.""" @@ -575,37 +588,43 @@ class TestNamespaceConnection: assert table_schema.field("id").type == pa.int64() assert table_schema.field("text").type == pa.string() - def test_rename_table(self): - """Test that rename_table renames a table in the namespace. - - The `dir` namespace implementation in lance-namespace-impls does not - implement `rename_table` yet (only the `rest` backend does), so it - currently falls back to the default trait method which raises - NotSupported. This is expected to start passing once the `dir` - backend gains rename_table support upstream. - """ + @pytest.mark.parametrize("destination_namespace", ["test_ns", "destination_ns"]) + def test_rename_table(self, destination_namespace): + """Test that renaming a table preserves its data and namespace registration.""" db = lancedb.connect_namespace("dir", {"root": self.temp_dir}) - - # Create a child namespace first db.create_namespace(["test_ns"]) + if destination_namespace != "test_ns": + db.create_namespace([destination_namespace]) - # Create a table in child namespace schema = pa.schema( [ pa.field("id", pa.int64()), pa.field("vector", pa.list_(pa.float32(), 2)), ] ) - db.create_table("old_name", schema=schema, namespace_path=["test_ns"]) + data = pa.Table.from_pylist( + [{"id": 1, "vector": [1.0, 2.0]}, {"id": 2, "vector": [3.0, 4.0]}], + schema=schema, + ) + db.create_table("old_name", data=data, namespace_path=["test_ns"]) - # Rename the table within the same namespace - with pytest.raises(NotImplementedError, match="rename_table not implemented"): - db.rename_table( - "old_name", - "new_name", - cur_namespace_path=["test_ns"], - new_namespace_path=["test_ns"], - ) + db.rename_table( + "old_name", + "new_name", + cur_namespace_path=["test_ns"], + new_namespace_path=[destination_namespace], + ) + + reopened = lancedb.connect_namespace("dir", {"root": self.temp_dir}) + assert "old_name" not in reopened.table_names(namespace_path=["test_ns"]) + assert "new_name" in reopened.table_names( + namespace_path=[destination_namespace] + ) + with pytest.raises(TableNotFoundError): + reopened.open_table("old_name", namespace_path=["test_ns"]) + table = reopened.open_table("new_name", namespace_path=[destination_namespace]) + assert table.namespace == [destination_namespace] + assert table.to_arrow().equals(data) def test_drop_all_tables(self): """Test dropping all tables through namespace.""" @@ -656,9 +675,9 @@ class TestNamespaceConnection: table = db.create_table("test_table", schema=schema, namespace_path=["test_ns"]) # Verify empty table was created - result = table.to_pandas() + result = table.to_arrow() assert len(result) == 0 - assert list(result.columns) == ["id", "vector", "text"] + assert result.column_names == ["id", "vector", "text"] # Test add data to the table new_data = [ @@ -666,19 +685,19 @@ class TestNamespaceConnection: {"id": 2, "vector": [2.0, 3.0], "text": "item_2"}, ] table.add(new_data) - result = table.to_pandas() + result = table.to_arrow() assert len(result) == 2 # Test delete table.delete("id = 1") - result = table.to_pandas() + result = table.to_arrow() assert len(result) == 1 - assert result["id"].values[0] == 2 + assert result["id"][0].as_py() == 2 # Test update table.update(where="id = 2", values={"text": "updated"}) - result = table.to_pandas() - assert result["text"].values[0] == "updated" + result = table.to_arrow() + assert result["text"][0].as_py() == "updated" def test_storage_options(self): """Test passing storage options through namespace connection.""" @@ -818,28 +837,28 @@ class TestNamespaceConnection: opened_table_a = db.open_table( "same_name_table", namespace_path=["namespace_a"] ) - result_a = opened_table_a.to_pandas().sort_values("id").reset_index(drop=True) + result_a = opened_table_a.to_arrow().sort_by([("id", "ascending")]) assert len(result_a) == 2 - assert result_a["id"].tolist() == [1, 2] - assert result_a["text"].tolist() == [ + assert result_a["id"].to_pylist() == [1, 2] + assert result_a["text"].to_pylist() == [ "data_from_namespace_a", "also_from_namespace_a", ] - assert [v.tolist() for v in result_a["vector"]] == [[1.0, 2.0], [3.0, 4.0]] + assert result_a["vector"].to_pylist() == [[1.0, 2.0], [3.0, 4.0]] # Verify data in namespace_b table opened_table_b = db.open_table( "same_name_table", namespace_path=["namespace_b"] ) - result_b = opened_table_b.to_pandas().sort_values("id").reset_index(drop=True) + result_b = opened_table_b.to_arrow().sort_by([("id", "ascending")]) assert len(result_b) == 3 - assert result_b["id"].tolist() == [10, 20, 30] - assert result_b["text"].tolist() == [ + assert result_b["id"].to_pylist() == [10, 20, 30] + assert result_b["text"].to_pylist() == [ "data_from_namespace_b", "also_from_namespace_b", "more_from_namespace_b", ] - assert [v.tolist() for v in result_b["vector"]] == [ + assert result_b["vector"].to_pylist() == [ [10.0, 20.0], [30.0, 40.0], [50.0, 60.0], @@ -1020,9 +1039,8 @@ class TestAsyncNamespaceConnection: assert result.schema.field("vector").type == pa.list_(pa.float32(), 2) # Verify data content - result_df = result.to_pandas() - assert result_df["id"].tolist() == [1, 2, 3] - assert [v.tolist() for v in result_df["vector"]] == [ + assert result["id"].to_pylist() == [1, 2, 3] + assert result["vector"].to_pylist() == [ [1.0, 2.0], [3.0, 4.0], [5.0, 6.0], @@ -1031,15 +1049,13 @@ class TestAsyncNamespaceConnection: # Test update operation await table.update({"id": 20}, where="id = 2") result = await table.to_arrow() - result_df = result.to_pandas().sort_values("id").reset_index(drop=True) - assert result_df["id"].tolist() == [1, 3, 20] + assert result.sort_by([("id", "ascending")])["id"].to_pylist() == [1, 3, 20] # Test delete operation await table.delete("id = 1") result = await table.to_arrow() assert len(result) == 2 - result_df = result.to_pandas().sort_values("id").reset_index(drop=True) - assert result_df["id"].tolist() == [3, 20] + assert result.sort_by([("id", "ascending")])["id"].to_pylist() == [3, 20] async def test_drop_table_async(self): """Test dropping a table asynchronously through namespace.""" @@ -1232,25 +1248,45 @@ class TestPushdownOperations: db = lancedb.connect_namespace_async("dir", {"root": self.temp_dir}) assert db._route_pushdown_to_rust is True - def test_lance_table_to_arrow_uses_query_pushdown(self): + @pytest.mark.parametrize("as_pandas", [False, True], ids=["arrow", "pandas"]) + def test_lance_table_query_pushdown(self, as_pandas): + if as_pandas: + pytest.importorskip("pandas") namespace_client = _NamespaceClient() table = _namespace_lance_table(namespace_client) - assert table.to_arrow().equals(PUSHDOWN_DATA) - assert table.to_pandas()["id"].tolist() == list(range(12)) - assert len(namespace_client.requests) == 2 + if as_pandas: + assert table.to_pandas()["id"].tolist() == list(range(12)) + else: + assert table.to_arrow().equals(PUSHDOWN_DATA) + assert len(namespace_client.requests) == 1 assert [request.id for request in namespace_client.requests] == [ - ["geneva", "hist"], - ["geneva", "hist"], + ["geneva", "hist"] ] # Unlimited reads cap k at i32::MAX (the namespace query_table `k` # field is i32); sys.maxsize would overflow the Rust binding. - assert [request.k for request in namespace_client.requests] == [ - _MAX_QUERY_K, - _MAX_QUERY_K, - ] + 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) + @pytest.mark.parametrize( + "query_kwargs", + [ + {"approx_mode": "fast"}, + {"search_effort": 0.75}, + {"approx_mode": "fast", "search_effort": 0.75}, + ], + ids=["approx_mode", "search_effort", "both"], + ) + def test_lance_table_local_only_options_are_not_pushed_down(self, query_kwargs): + namespace_client = _NamespaceClient() + table = _namespace_lance_table(namespace_client) + + # The QueryTable request cannot carry these options, so the query has to + # run locally rather than silently ignore them. + with pytest.raises(RuntimeError, match="local execution reached"): + table._execute_query(Query(vector=[1.0, 2.0], **query_kwargs)) + assert namespace_client.requests == [] + def test_probe_fields_pass_through_independently(self): request = _query_to_namespace_request( ["geneva", "hist"], @@ -1310,7 +1346,10 @@ class TestAsyncPushdownOperations: db = lancedb.connect_namespace_async("dir", {"root": self.temp_dir}) assert len(db._namespace_client_pushdown_operations) == 0 - async def test_async_table_to_arrow_uses_query_pushdown(self): + @pytest.mark.parametrize("as_pandas", [False, True], ids=["arrow", "pandas"]) + async def test_async_table_query_pushdown(self, as_pandas): + if as_pandas: + pytest.importorskip("pandas") namespace_client = _NamespaceClient() table = AsyncTable( @@ -1320,23 +1359,49 @@ class TestAsyncPushdownOperations: pushdown_operations={"QueryTable"}, ) - assert (await table.to_arrow()).equals(PUSHDOWN_DATA) - assert (await table.to_pandas())["id"].tolist() == list(range(12)) - assert len(namespace_client.requests) == 2 + if as_pandas: + assert (await table.to_pandas())["id"].tolist() == list(range(12)) + else: + assert (await table.to_arrow()).equals(PUSHDOWN_DATA) + assert len(namespace_client.requests) == 1 assert [request.id for request in namespace_client.requests] == [ - ["geneva", "hist"], - ["geneva", "hist"], + ["geneva", "hist"] ] # Unlimited reads cap k at i32::MAX (the namespace query_table `k` # field is i32); sys.maxsize would overflow the Rust binding. - assert [request.k for request in namespace_client.requests] == [ - _MAX_QUERY_K, - _MAX_QUERY_K, - ] + 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) + @pytest.mark.parametrize( + "query_kwargs", + [ + {"approx_mode": "fast"}, + {"search_effort": 0.75}, + {"approx_mode": "fast", "search_effort": 0.75}, + ], + ids=["approx_mode", "search_effort", "both"], + ) + async def test_async_table_local_only_options_are_not_pushed_down( + self, query_kwargs + ): + namespace_client = _NamespaceClient() -def test_local_table_to_arrow_and_to_pandas_are_unchanged(tmp_path): + table = AsyncTable( + _FailingAsyncInner(), + namespace_path=["geneva"], + namespace_client=namespace_client, + pushdown_operations={"QueryTable"}, + ) + + with pytest.raises(AssertionError, match="direct async query"): + await table._execute_query(Query(vector=[1.0, 2.0], **query_kwargs)) + assert namespace_client.requests == [] + + +@pytest.mark.parametrize("as_pandas", [False, True], ids=["arrow", "pandas"]) +def test_local_table_to_arrow_and_to_pandas_are_unchanged(tmp_path, as_pandas): + if as_pandas: + pytest.importorskip("pandas") db = lancedb.connect(str(tmp_path / "db")) table = db.create_table( "local", @@ -1346,8 +1411,10 @@ def test_local_table_to_arrow_and_to_pandas_are_unchanged(tmp_path): ], ) - assert table.to_arrow().column("id").to_pylist() == [1, 2] - assert table.to_pandas()["id"].tolist() == [1, 2] + if as_pandas: + assert table.to_pandas()["id"].tolist() == [1, 2] + else: + assert table.to_arrow().column("id").to_pylist() == [1, 2] @pytest.mark.parametrize("effort", [0.0, 0.5, 1.0]) @@ -1360,3 +1427,59 @@ def test_namespace_request_rejects_search_effort(effort): _query_to_namespace_request( ["test"], Query(vector=[1.0, 0.0], search_effort=effort) ) + + +class AttributeAccessNamespace(LanceNamespace): + """A Python namespace that reads request fields as attributes. + + Python implementations such as ``lance_namespace_impls.glue.GlueNamespace`` + read requests like pydantic models (``request.id``), and expect omitted + optional fields to be ``None``. This fake records what it read and then + delegates to ``DirectoryNamespace`` so the test runs locally. + """ + + def __init__(self, root: str): + from lance.namespace import DirectoryNamespace + + self._inner = DirectoryNamespace(root=root) + self.seen = {} + + def namespace_id(self) -> str: + return f"AttributeAccessNamespace[{self._inner.namespace_id()}]" + + def list_tables(self, request): + self.seen["list_tables"] = request + _ = request.id + _ = request.page_token + return self._inner.list_tables(request) + + def describe_table(self, request): + self.seen["describe_table"] = request + _ = request.id + # Optional field omitted by the Rust side; must read as None. + assert request.load_detailed_metadata is None + return self._inner.describe_table(request) + + +def test_python_namespace_attribute_access(tmp_path): + pytest.importorskip("lance.namespace") + root = str(tmp_path) + data = pa.table({"id": [1, 2, 3], "text": ["alpha", "beta", "gamma"]}) + lancedb.connect_namespace("dir", {"root": root}).create_table("t", data) + + ns = AttributeAccessNamespace(root) + db = LanceNamespaceDBConnection(ns) + + assert list(db.list_tables()) == ["t"] + assert db.open_table("t").to_arrow().to_pylist() == data.to_pylist() + + # Mapping access and model_dump() keep working. + request = ns.seen["describe_table"] + assert isinstance(request, builtins._DictWithModelDump) + assert request["id"] == request.id == ["t"] + assert request.model_dump() == dict(request) + assert "load_detailed_metadata" not in request + + # Missing dunder lookups still raise, so copy/hasattr probes work. + assert not hasattr(request, "__missing_dunder__") + assert copy.deepcopy(request) == request diff --git a/python/python/tests/test_package_metadata.py b/python/python/tests/test_package_metadata.py index 58f4e7267..1b4d3a711 100644 --- a/python/python/tests/test_package_metadata.py +++ b/python/python/tests/test_package_metadata.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import importlib +import importlib.metadata import re import sys from pathlib import Path @@ -9,6 +10,18 @@ from pathlib import Path import pytest +@pytest.mark.parametrize("distribution", ["lancedb", "lancedb-compat"]) +def test_version_matches_package_metadata(distribution): + import lancedb + + try: + package_version = importlib.metadata.version(distribution) + except importlib.metadata.PackageNotFoundError: + pytest.skip(f"{distribution} is not installed") + + assert lancedb.__version__ == package_version + + @pytest.mark.parametrize("name", ["JobInfo", "JobDescription", "JobFailureInfo"]) def test_job_metadata_types_have_resolvable_modules(name): """Documentation tools resolve re-exports through each type's module.""" @@ -18,6 +31,15 @@ def test_job_metadata_types_have_resolvable_modules(name): assert getattr(defining_module, public_type.__name__, None) is public_type +def test_gpu_class_reexport_has_resolvable_module(): + import lancedb + + public_type = lancedb.GpuClass + defining_module = importlib.import_module(public_type.__module__) + + assert getattr(defining_module, public_type.__name__, None) is public_type + + def test_pyo3_abi_matches_minimum_supported_python(): project_dir = Path(__file__).parents[2] pyproject = (project_dir / "pyproject.toml").read_text() diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index bc5c1649c..46d6493ed 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -946,12 +946,12 @@ def test_iter_with_different_formats(some_permutation: Permutation): python_batches = list(python_perm.iter(batch_size, skip_last_batch=False)) assert all(isinstance(batch, list) for batch in python_batches) - # Test with pandas format + +def test_iter_with_pandas_format(some_permutation: Permutation): + pd = pytest.importorskip("pandas") + batch_size = 100 pandas_perm = some_permutation.with_format("pandas") pandas_batches = list(pandas_perm.iter(batch_size, skip_last_batch=False)) - # Import pandas to check the type - import pandas as pd - assert all(isinstance(batch, pd.DataFrame) for batch in pandas_batches) @@ -1053,8 +1053,6 @@ def test_identity_permutation(mem_db): def test_transform_fn(mem_db): - import numpy as np - import pandas as pd import polars as pl tbl = mem_db.create_table( @@ -1062,20 +1060,6 @@ def test_transform_fn(mem_db): ) permutation = Permutation.identity(tbl) - np_result = list(permutation.with_format("numpy").iter(10, skip_last_batch=False))[ - 0 - ] - assert np_result.shape == (10, 2) - assert np_result.dtype == np.int64 - assert isinstance(np_result, np.ndarray) - - pd_result = list(permutation.with_format("pandas").iter(10, skip_last_batch=False))[ - 0 - ] - assert pd_result.shape == (10, 2) - assert pd_result.dtypes.tolist() == [np.int64, np.int64] - assert isinstance(pd_result, pd.DataFrame) - pl_result = list(permutation.with_format("polars").iter(10, skip_last_batch=False))[ 0 ] @@ -1141,6 +1125,27 @@ def test_transform_fn(mem_db): assert isinstance(arrow_result, pa.RecordBatch) +def test_transform_fn_pandas(mem_db): + pd = pytest.importorskip("pandas") + import numpy as np + + tbl = mem_db.create_table( + "test_table", pa.table({"id": range(10), "value": range(10)}) + ) + permutation = Permutation.identity(tbl) + numpy_result = list( + permutation.with_format("numpy").iter(10, skip_last_batch=False) + )[0] + assert numpy_result.shape == (10, 2) + assert numpy_result.dtype == np.int64 + assert isinstance(numpy_result, np.ndarray) + + result = list(permutation.with_format("pandas").iter(10, skip_last_batch=False))[0] + assert result.shape == (10, 2) + assert result.dtypes.tolist() == [np.int64, np.int64] + assert isinstance(result, pd.DataFrame) + + 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_pydantic.py b/python/python/tests/test_pydantic.py index 09af2f081..93c42e6b7 100644 --- a/python/python/tests/test_pydantic.py +++ b/python/python/tests/test_pydantic.py @@ -2,9 +2,9 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import json -from datetime import date, datetime +from datetime import date, datetime, time, timedelta, timezone from enum import Enum -from typing import List, Optional, Tuple +from typing import List, Literal, Optional, Tuple import pyarrow as pa import pydantic @@ -16,6 +16,7 @@ from lancedb.pydantic import ( Vector, pydantic_to_schema, ) +from packaging.version import Version from pydantic import BaseModel from pydantic import Field @@ -791,6 +792,305 @@ async def test_aliases_in_lance_model_async(mem_db_async): assert model.distance < 0.01 +def test_aliased_lance_model_reads_back_its_own_table(mem_db): + # The schema and add() use field names, so to_pydantic() must accept rows + # keyed by field name even though pydantic validates by alias. + class Item(LanceModel): + user_id: int = Field(alias="userId") + vector: Vector(2) + + tbl = mem_db.create_table("aliased_items", schema=Item) + tbl.add([Item(userId=1, vector=[0.1, 0.2])]) + assert tbl.schema.names == ["user_id", "vector"] + + [item] = tbl.search([0.1, 0.2]).limit(1).to_pydantic(Item) + assert item.user_id == 1 + [item] = tbl.search().to_pydantic(Item) + assert item.user_id == 1 + + +@pytest.mark.parametrize( + "validation_alias", + [ + pydantic.AliasChoices("userId"), + pydantic.AliasPath("userId"), + ], + ids=["alias-choices", "alias-path"], +) +def test_aliased_lance_model_with_complex_validation_alias_reads_back_its_own_table( + mem_db, validation_alias +): + class Item(LanceModel): + user_id: int = Field(validation_alias=validation_alias) + vector: Vector(2) + + tbl = mem_db.create_table("aliased_items", schema=Item) + tbl.add([Item(userId=1, vector=[0.1, 0.2])]) + assert tbl.schema.names == ["user_id", "vector"] + + [item] = tbl.search().to_pydantic(Item) + assert item.user_id == 1 + + +def test_lower_priority_alias_takes_precedence_over_field_name(mem_db): + class Item(LanceModel): + user_id: int = Field( + validation_alias=pydantic.AliasChoices("primaryId", "secondaryId") + ) + + row = {"user_id": 1, "secondaryId": 2} + tbl = mem_db.create_table("aliased_items", data=[row]) + + [arrow_row] = tbl.search().to_arrow().to_pylist() + assert Item(**arrow_row).user_id == 2 + [item] = tbl.search().to_pydantic(Item) + assert item.user_id == 2 + + +@pytest.mark.skipif( + Version(pydantic.VERSION) < Version("2.11"), + reason="validate_by_alias/validate_by_name require pydantic>=2.11", +) +def test_aliased_lance_model_with_name_only_validation(mem_db): + class Item(LanceModel): + model_config = pydantic.ConfigDict( + validate_by_alias=False, validate_by_name=True + ) + user_id: int = Field(default=0, alias="userId") + + tbl = mem_db.create_table("name_only_items", schema=Item) + item = Item(user_id=42) + assert item.user_id == 42 + tbl.add([item]) + [item] = tbl.search().to_pydantic(Item) + assert item.user_id == 42 + + +def test_aliased_lance_model_with_populate_by_name(mem_db): + class Item(LanceModel): + model_config = pydantic.ConfigDict(populate_by_name=True) + user_id: int = Field(default=0, alias="userId") + + tbl = mem_db.create_table("populate_by_name_items", schema=Item) + item = Item(user_id=42) + assert item.user_id == 42 + tbl.add([item]) + [item] = tbl.search().to_pydantic(Item) + assert item.user_id == 42 + + +@pytest.mark.skipif( + Version(pydantic.VERSION) < Version("2.11"), + reason="validate_by_name requires pydantic>=2.11", +) +def test_explicit_validate_by_name_false_overrides_populate_by_name(mem_db): + class Item(LanceModel): + model_config = pydantic.ConfigDict( + populate_by_name=True, + validate_by_name=False, + ) + user_id: int = Field(default=0, alias="userId") + + tbl = mem_db.create_table("validate_by_name_precedence_items", schema=Item) + item = Item(userId=42) + assert item.user_id == 42 + tbl.add([item]) + assert tbl.schema.names == ["user_id"] + assert tbl.search().to_arrow().to_pylist() == [{"user_id": 42}] + + [item] = tbl.search().to_pydantic(Item) + assert item.user_id == 42 + + +def test_field_name_fallback_preserves_populate_by_name_reader(mem_db): + class Item(LanceModel): + model_config = pydantic.ConfigDict(populate_by_name=True) + value: int = Field(default=0, validation_alias="id") + id: int = Field(default=-1, alias="recordId") + + row = {"value": 1} + assert Item(**row).model_dump() == {"value": 1, "id": -1} + tbl = mem_db.create_table("populate_by_name_readers", data=[row]) + + [arrow_row] = tbl.search().to_arrow().to_pylist() + assert arrow_row == row + [item] = tbl.search().to_pydantic(Item) + assert item.model_dump() == {"value": 1, "id": -1} + + +def test_field_name_that_is_another_fields_alias_keeps_its_meaning(mem_db): + class Item(LanceModel): + record_id: int = Field(default=0, alias="id") + id: int = Field(default=-1, alias="legacy_id") + + tbl = mem_db.create_table("alias_collision_items", data=[{"id": 42}]) + [item] = tbl.search().to_pydantic(Item) + assert item.model_dump() == {"record_id": 42, "id": -1} + + +@pytest.mark.parametrize( + "validation_alias", + [ + pydantic.AliasChoices("id", "recordId"), + pydantic.AliasPath("id"), + pydantic.AliasChoices(pydantic.AliasPath("id"), "recordId"), + ], +) +def test_field_name_read_by_another_fields_alias_choices_or_path( + mem_db, validation_alias +): + class Item(LanceModel): + record_id: int = Field(default=0, validation_alias=validation_alias) + id: int = Field(default=-1, alias="legacy_id") + + tbl = mem_db.create_table("alias_choices_items", data=[{"id": 42}]) + [item] = tbl.search().to_pydantic(Item) + assert item.model_dump() == {"record_id": 42, "id": -1} + + +def test_field_name_fallback_does_not_change_another_fields_alias_choice(mem_db): + class Item(LanceModel): + value: int = Field( + default=0, validation_alias=pydantic.AliasChoices("id", "valueId") + ) + record_id: int = Field( + default=-1, validation_alias=pydantic.AliasChoices("id", "recordId") + ) + + row = {"value": 1, "recordId": 42} + assert Item(**row).model_dump() == {"value": 0, "record_id": 42} + tbl = mem_db.create_table("shared_alias_items", data=[row]) + + [arrow_row] = tbl.search().to_arrow().to_pylist() + assert arrow_row == row + [item] = tbl.search().to_pydantic(Item) + assert item.model_dump() == {"value": 0, "record_id": 42} + + +@pytest.mark.asyncio +async def test_aliased_lance_model_reads_back_its_own_table_async(mem_db_async): + class Item(LanceModel): + user_id: int = Field(alias="userId") + vector: Vector(2) + + tbl = await mem_db_async.create_table("aliased_items", schema=Item) + await tbl.add([Item(userId=1, vector=[0.1, 0.2])]) + + [item] = await tbl.vector_search([0.1, 0.2]).limit(1).to_pydantic(Item) + assert item.user_id == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "validation_alias", + [ + pydantic.AliasChoices("userId"), + pydantic.AliasPath("userId"), + ], + ids=["alias-choices", "alias-path"], +) +async def test_aliased_lance_model_with_complex_validation_alias_reads_back_async( + mem_db_async, validation_alias +): + class Item(LanceModel): + user_id: int = Field(validation_alias=validation_alias) + vector: Vector(2) + + tbl = await mem_db_async.create_table("aliased_items", schema=Item) + await tbl.add([Item(userId=1, vector=[0.1, 0.2])]) + assert (await tbl.schema()).names == ["user_id", "vector"] + + [item] = await tbl.vector_search([0.1, 0.2]).limit(1).to_pydantic(Item) + assert item.user_id == 1 + + +@pytest.mark.asyncio +async def test_lower_priority_alias_takes_precedence_over_field_name_async( + mem_db_async, +): + class Item(LanceModel): + user_id: int = Field( + validation_alias=pydantic.AliasChoices("primaryId", "secondaryId") + ) + + row = {"user_id": 1, "secondaryId": 2} + tbl = await mem_db_async.create_table("aliased_items", data=[row]) + + [arrow_row] = (await (await tbl.search()).to_arrow()).to_pylist() + assert Item(**arrow_row).user_id == 2 + [item] = await (await tbl.search()).to_pydantic(Item) + assert item.user_id == 2 + + +@pytest.mark.asyncio +async def test_field_name_fallback_does_not_change_another_fields_alias_choice_async( + mem_db_async, +): + class Item(LanceModel): + value: int = Field( + default=0, validation_alias=pydantic.AliasChoices("id", "valueId") + ) + record_id: int = Field( + default=-1, validation_alias=pydantic.AliasChoices("id", "recordId") + ) + + row = {"value": 1, "recordId": 42} + assert Item(**row).model_dump() == {"value": 0, "record_id": 42} + tbl = await mem_db_async.create_table("shared_alias_items", data=[row]) + + [arrow_row] = (await (await tbl.search()).to_arrow()).to_pylist() + assert arrow_row == row + [item] = await (await tbl.search()).to_pydantic(Item) + assert item.model_dump() == {"value": 0, "record_id": 42} + + +@pytest.mark.asyncio +async def test_field_name_fallback_preserves_populate_by_name_reader_async( + mem_db_async, +): + class Item(LanceModel): + model_config = pydantic.ConfigDict(populate_by_name=True) + value: int = Field(default=0, validation_alias="id") + id: int = Field(default=-1, alias="recordId") + + row = {"value": 1} + assert Item(**row).model_dump() == {"value": 1, "id": -1} + tbl = await mem_db_async.create_table("populate_by_name_readers", data=[row]) + + [arrow_row] = (await (await tbl.search()).to_arrow()).to_pylist() + assert arrow_row == row + [item] = await (await tbl.search()).to_pydantic(Item) + assert item.model_dump() == {"value": 1, "id": -1} + + +@pytest.mark.asyncio +@pytest.mark.skipif( + Version(pydantic.VERSION) < Version("2.11"), + reason="validate_by_name requires pydantic>=2.11", +) +async def test_explicit_validate_by_name_false_overrides_populate_by_name_async( + mem_db_async, +): + class Item(LanceModel): + model_config = pydantic.ConfigDict( + populate_by_name=True, + validate_by_name=False, + ) + user_id: int = Field(default=0, alias="userId") + + tbl = await mem_db_async.create_table( + "validate_by_name_precedence_items", schema=Item + ) + item = Item(userId=42) + assert item.user_id == 42 + await tbl.add([item]) + assert (await tbl.schema()).names == ["user_id"] + assert (await (await tbl.search()).to_arrow()).to_pylist() == [{"user_id": 42}] + + [item] = await (await tbl.search()).to_pydantic(Item) + assert item.user_id == 42 + + def test_enum_types(): """Enum fields should map to the Arrow type of their value (issue #1846).""" @@ -817,6 +1117,36 @@ def test_enum_types(): assert schema.field("opt_status").nullable +@pytest.mark.parametrize("container", ["field", "optional", "list", "nested"]) +@pytest.mark.parametrize("values", [("text", 7), (1, 2.5), (False, "no")]) +def test_mixed_enum_values_are_rejected(container, values): + Mixed = Enum("Mixed", {"FIRST": values[0], "SECOND": values[1]}) + + class Nested(pydantic.BaseModel): + value: Mixed + + annotation = { + "field": Mixed, + "optional": Optional[Mixed], + "list": List[Mixed], + "nested": Nested, + }[container] + model = pydantic.create_model("Model", value=(annotation, ...)) + + with pytest.raises(TypeError, match="Enum.*Mixed.*same type"): + pydantic_to_schema(model) + + +def test_empty_enum_schema_is_unchanged(): + class Empty(Enum): + pass + + class Model(pydantic.BaseModel): + value: Empty + + assert pydantic_to_schema(Model).field("value").type == pa.utf8() + + def test_plain_enum_values_are_written(mem_db): """Members of an Enum without a str/int mixin are written as their values.""" @@ -864,3 +1194,111 @@ def test_plain_enum_values_are_written(mem_db): {"color": "blue", "priority": 1, "opt_color": None}, ] assert tbl.search().to_pydantic(TestModel) == rows + + +def test_literal_time_and_timedelta_types(): + class TestModel(pydantic.BaseModel): + status: Literal["todo", "done"] + priority: Literal[1, 2, 3] + flag: Literal[True] + tags: List[Literal["a", "b"]] + opt_status: Optional[Literal["todo", "done"]] = None + starts: time + starts_list: List[time] + opt_starts: Optional[time] = None + duration: timedelta + durations: List[timedelta] + + schema = pydantic_to_schema(TestModel) + + assert schema.field("status").type == pa.utf8() + assert schema.field("priority").type == pa.int64() + assert schema.field("flag").type == pa.bool_() + assert schema.field("tags").type == pa.list_(pa.utf8()) + assert schema.field("opt_status").type == pa.utf8() + assert schema.field("opt_status").nullable + assert schema.field("starts").type == pa.time64("us") + assert schema.field("starts_list").type == pa.list_(pa.time64("us")) + assert schema.field("opt_starts").type == pa.time64("us") + assert schema.field("opt_starts").nullable + assert schema.field("duration").type == pa.duration("us") + assert schema.field("durations").type == pa.list_(pa.duration("us")) + + +@pytest.mark.parametrize( + "annotation", + [ + Literal["a", 1], + Optional[Literal["a", 1]], + List[Literal["a", 1]], + ], + ids=["field", "optional", "list"], +) +def test_literal_with_mixed_value_types_raises_type_error(annotation): + TestModel = pydantic.create_model("TestModel", value=(annotation, ...)) + + with pytest.raises(TypeError, match="same type"): + pydantic_to_schema(TestModel) + + +def test_literal_time_and_timedelta_round_trip(mem_db): + class TestModel(LanceModel): + status: Literal["todo", "done"] + starts: time + duration: timedelta + vector: Vector(2) + + rows = [ + TestModel( + status="done", + starts=time(9, 30), + duration=timedelta(minutes=45), + vector=[1.0, 2.0], + ), + TestModel( + status="todo", + starts=time(17, 0, 0, 250), + duration=timedelta(days=1, microseconds=5), + vector=[3.0, 4.0], + ), + ] + tbl = mem_db.create_table("test", schema=TestModel) + tbl.add(rows) + + assert tbl.search().to_pydantic(TestModel) == rows + + +@pytest.mark.parametrize("container", ["field", "list", "nested", "enum"]) +def test_tz_aware_time_is_rejected_before_write(mem_db, container): + class Nested(LanceModel): + starts: time + + aware = time(9, 30, tzinfo=timezone(timedelta(hours=5, minutes=30))) + AwareTime = Enum("AwareTime", {"MORNING": aware}) + Model = pydantic.create_model( + "TestModel", + __base__=LanceModel, + **{ + container: { + "field": (time, ...), + "list": (List[time], ...), + "nested": (Nested, ...), + "enum": (AwareTime, ...), + }[container] + }, + ) + row = Model( + **{ + container: { + "field": aware, + "list": [aware], + "nested": Nested(starts=aware), + "enum": AwareTime.MORNING, + }[container] + } + ) + + table_name = f"timezone_aware_{container}" + with pytest.raises(ValueError, match="timezone-naive wall-clock.*tzinfo"): + mem_db.create_table(table_name, data=[row]) + assert table_name not in mem_db.table_names() diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index b898a8888..95148dcf9 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1308,6 +1308,28 @@ async def test_invalid_nprobes_async(table_async: AsyncTable): ) +def test_approx_mode_works_sync(table): + for mode in ["fast", "normal", "accurate"]: + LanceVectorQueryBuilder(table, [0, 0], "vector").approx_mode(mode).to_list() + + +def test_invalid_approx_mode_sync(table): + with pytest.raises(ValueError, match="approx_mode must be one of"): + LanceVectorQueryBuilder(table, [0, 0], "vector").approx_mode("turbo").to_list() + + +@pytest.mark.asyncio +async def test_approx_mode_works_async(table_async: AsyncTable): + for mode in ["fast", "normal", "accurate"]: + await table_async.vector_search([0, 0]).approx_mode(mode).to_list() + + +@pytest.mark.asyncio +async def test_invalid_approx_mode_async(table_async: AsyncTable): + with pytest.raises(ValueError, match="approx_mode must be one of"): + table_async.vector_search([0, 0]).approx_mode("turbo") + + def test_query_builder_with_prefilter(table): df = ( LanceVectorQueryBuilder(table, [0, 0], "vector") @@ -1962,6 +1984,9 @@ def test_query_serialization_sync(table: lancedb.table.Table): q = table.search([5.0, 6.0]).ef(7).to_query_object() check_set_props(q, ef=7, vector_column="vector", vector=[5.0, 6.0]) + q = table.search([5.0, 6.0]).approx_mode("fast").to_query_object() + check_set_props(q, approx_mode="fast", vector_column="vector", vector=[5.0, 6.0]) + q = table.search([5.0, 6.0]).bypass_vector_index().to_query_object() check_set_props( q, bypass_vector_index=True, vector_column="vector", vector=[5.0, 6.0] @@ -2190,6 +2215,19 @@ async def test_query_serialization_async(table_async: AsyncTable): limit=10, ) + q = (await table_async.search([5.0, 6.0])).approx_mode("fast").to_query_object() + check_set_props( + q, + approx_mode="fast", + vector=sample_vector, + postfilter=False, + minimum_nprobes=None, + maximum_nprobes=None, + with_row_id=False, + bypass_vector_index=False, + limit=10, + ) + q = (await table_async.search([5.0, 6.0])).bypass_vector_index().to_query_object() check_set_props( q, @@ -2228,6 +2266,20 @@ async def test_query_serialization_async(table_async: AsyncTable): ) +@pytest.mark.asyncio +async def test_hybrid_query_serialization_async(table_async: AsyncTable): + q = ( + table_async.query() + .nearest_to([5.0, 6.0]) + .nearest_to_text(MatchQuery("dog", "text")) + .ef(7) + .approx_mode("fast") + .to_query_object() + ) + assert q.ef == 7 + assert q.approx_mode == "fast" + + def test_query_schema(tmp_path): db = lancedb.connect(tmp_path) tbl = db.create_table( @@ -2365,13 +2417,36 @@ def test_take_queries(tmp_path): assert sorted(converted["idx"].to_pylist()) == [2, 5, 5, 17] # Take by row id - assert list( - sorted(table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list()) - ) == [ - 2, - 5, - 17, - ] + assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17] + + +@pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}]) +@pytest.mark.parametrize("empty", [False, True]) +def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty): + table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": [0, 1]})) + table.add(pa.table({"idx": [2, 3]})) + rows = table.search().with_row_id(True).to_arrow().to_pylist() + row_ids = {row["idx"]: row["_rowid"] for row in rows} + table.delete("idx = 1") + requested = ( + [] if empty else [row_ids[3], row_ids[1], row_ids[3], 2**64 - 1, row_ids[0]] + ) + take = table.take_row_ids(requested) + if selection is not None: + take = take.select(selection) + actual = take.to_arrow() + assert actual.num_rows == (0 if empty else 3) + if selection == {"_rowid": "100 - idx"}: + assert actual.column_names == ["_rowid"] + assert actual["_rowid"].to_pylist() == ([] if empty else [97, 97, 100]) + elif selection == []: + assert actual.num_columns == 0 + else: + assert actual.column_names == ["idx"] + assert actual["idx"].to_pylist() == ([] if empty else [3, 3, 0]) + query = take.to_query_object() + assert query.take_row_ids == requested + assert table._execute_query(query).read_all() == actual def test_take_queries_with_row_id(tmp_path): @@ -2380,6 +2455,7 @@ def test_take_queries_with_row_id(tmp_path): by_row_id = table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow() assert "_rowid" in by_row_id.column_names + assert by_row_id["_rowid"].to_pylist() == [5, 2, 17] by_offset = table.take_offsets([5, 2, 17], with_row_id=True).to_arrow() assert "_rowid" in by_offset.column_names @@ -2394,6 +2470,7 @@ async def test_take_queries_with_row_id_async(tmp_path): by_row_id = await table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow() assert "_rowid" in by_row_id.column_names + assert by_row_id["_rowid"].to_pylist() == [5, 2, 17] by_offset = await table.take_offsets([5, 2, 17], with_row_id=True).to_arrow() assert "_rowid" in by_offset.column_names @@ -2420,16 +2497,12 @@ def test_take_queries_to_batches(tmp_path): rs = list(table.take_row_ids([5, 2, 17]).to_batches()) assert all(isinstance(b, pa.RecordBatch) for b in rs) assert sum(b.num_rows for b in rs) == 3 - assert sorted(v for b in rs for v in b.column("idx").to_pylist()) == [2, 5, 17] + assert [v for b in rs for v in b.column("idx").to_pylist()] == [5, 2, 17] # Take with select projection → to_batches preserves the projection rs = list(table.take_row_ids([5, 2, 17]).select(["label"]).to_batches()) assert all(b.schema.names == ["label"] for b in rs) - assert sorted(v for b in rs for v in b.column("label").to_pylist()) == [ - "17", - "2", - "5", - ] + assert [v for b in rs for v in b.column("label").to_pylist()] == ["5", "2", "17"] def test_getitems(tmp_path): @@ -2585,17 +2658,24 @@ def test_blob_v2_to_batches_row_id(tmp_db): assert [blobs[i].as_py() for i in range(len(blobs))] == [b"one", b"two"] -@pytest.mark.parametrize("metric", ["l2", "cosine", "dot"]) @pytest.mark.parametrize( - "effort,probes", [(None, 4), (0, 1), (0.25, 2), (0.5, 4), (0.75, 8), (1, 16)] + "metric,probes80,probes90", [("l2", 2, 3), ("cosine", 1, 2), ("dot", 1, 2)] ) -def test_search_effort_probe_budget(tmp_path, monkeypatch, metric, effort, probes): +@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1]) +def test_search_effort_probe_budget( + tmp_path, monkeypatch, metric, effort, probes80, probes90 +): import re from lancedb.index import IvfFlat monkeypatch.setenv("LANCE_AUTO_PROBE_MARGIN", "0") monkeypatch.setenv("LANCE_AUTO_MIN_INITIAL_NPROBES", "4") monkeypatch.setenv("LANCE_AUTO_MAX_INITIAL_NPROBES", "4") + # The lower tiers use metric/k calibration; Auto and the upper tiers retain + # their existing budgets. Keep exact execution counts and precedence checks. + probes = {None: 4, 0: 1, 0.1: probes80, 0.25: probes90, 0.5: 4, 0.75: 8, 1: 16}[ + effort + ] rng = np.random.default_rng(42) vectors = np.repeat(np.eye(16, dtype=np.float32), 32, axis=0) vectors += rng.normal(0, 0.001, vectors.shape).astype(np.float32) @@ -2679,7 +2759,7 @@ def test_search_effort_invalid_sync(table, effort): @pytest.mark.asyncio @pytest.mark.parametrize("hybrid", [False, True]) -@pytest.mark.parametrize("effort", [None, 0, 0.25, 0.5, 0.75, 1]) +@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1]) async def test_search_effort_async_roundtrip(table_async, hybrid, effort): query = table_async.vector_search([0, 0]) if hybrid: diff --git a/python/python/tests/test_read_consistency_interval.py b/python/python/tests/test_read_consistency_interval.py index bc69775ea..a4206fa91 100644 --- a/python/python/tests/test_read_consistency_interval.py +++ b/python/python/tests/test_read_consistency_interval.py @@ -13,6 +13,8 @@ from lancedb.namespace import LanceNamespaceDBConnection @pytest.mark.parametrize("seconds", [-1.0, -0.000001]) @pytest.mark.parametrize("kind", ["sync", "namespace", "namespace_async", "client"]) def test_negative_read_consistency_interval(tmp_path, seconds, kind): + if kind == "client": + pytest.importorskip("lance") interval = timedelta(seconds=seconds) with pytest.raises(ValueError, match="read_consistency_interval"): if kind == "sync": @@ -44,6 +46,8 @@ async def test_negative_async_read_consistency_interval(tmp_path, seconds): async def test_binding_rejects_invalid_read_consistency_interval( tmp_path, seconds, kind ): + if kind == "client": + pytest.importorskip("lance") with pytest.raises(ValueError, match="read_consistency_interval"): if kind == "connect": await _lancedb.connect(str(tmp_path), read_consistency_interval=seconds) @@ -71,12 +75,23 @@ async def test_valid_read_consistency_intervals(tmp_path, interval): assert await db.get_read_consistency_interval() == interval db.close() + +@pytest.mark.parametrize( + "interval", [None, timedelta(0), timedelta(microseconds=1), timedelta(seconds=5)] +) +def test_valid_namespace_read_consistency_intervals(tmp_path, interval): db = lancedb.connect_namespace( "dir", {"root": str(tmp_path / "namespace")}, read_consistency_interval=interval ) assert db.read_consistency_interval == interval db.close() + +@pytest.mark.parametrize( + "interval", [None, timedelta(0), timedelta(microseconds=1), timedelta(seconds=5)] +) +def test_valid_namespace_client_read_consistency_intervals(tmp_path, interval): + pytest.importorskip("lance") client = connect_namespace_client("dir", {"root": str(tmp_path / "client")}) db = LanceNamespaceDBConnection(client, read_consistency_interval=interval) assert db.read_consistency_interval == interval diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 415f8be3c..685bc809d 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2,6 +2,8 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors from concurrent.futures import ThreadPoolExecutor import contextlib +import copy +from dataclasses import replace from datetime import timedelta import http.server import io @@ -10,20 +12,30 @@ import json import multiprocessing as mp import pickle import re +import socket import subprocess import sys import textwrap import threading import time +from urllib.parse import parse_qs, urlparse from unittest.mock import MagicMock, patch import uuid -from urllib.parse import parse_qs, urlparse from packaging.version import Version +from lance_namespace.errors import TableNotFoundError import lancedb import numpy as np from lancedb.conftest import MockNonNormTextEmbeddingFunction, MockTextEmbeddingFunction from lancedb.embeddings import EmbeddingFunctionConfig, EmbeddingFunctionRegistry +from lancedb.graph import ( + AsyncPropertyGraph, + EdgeTable, + Endpoint, + NodeTable, + PropertyGraph, + PropertyGraphDescription, +) from lancedb.query import ( AsyncQuery, ColumnOrdering, @@ -31,7 +43,14 @@ from lancedb.query import ( MatchQuery, ) from lancedb.remote import ClientConfig -from lancedb.remote.errors import HttpError, RetryError +from lancedb.remote.errors import ( + AlreadyExistsError, + ConflictError, + HttpError, + NamespaceNotFoundError, + ResponseInterruptedError, + RetryError, +) import pytest import pyarrow as pa from utils import start_server_thread @@ -45,6 +64,9 @@ def make_mock_http_handler(handler): def do_POST(self): handler(self) + def do_PUT(self): + handler(self) + return MockLanceDBHandler @@ -56,7 +78,7 @@ def test_connect_rejects_invalid_cloud_dns_hostname(db_name): @contextlib.contextmanager def mock_lancedb_connection(handler, **client_config): - with http.server.HTTPServer( + with http.server.ThreadingHTTPServer( ("127.0.0.1", 0), make_mock_http_handler(handler) ) as server: port = server.server_address[1] @@ -110,6 +132,132 @@ async def mock_lancedb_connection_async(handler, **client_config): handle.join() +@pytest.fixture +def missing_table_handler(cached, namespace_path): + request_ids = [] + + def handler(request): + identifier = "$".join(namespace_path + ["missing"]) + assert request.path == f"/v1/table/{identifier}/describe/" + request_ids.append(request.headers["x-request-id"]) + status = 200 if cached and len(request_ids) == 1 else 404 + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b"{}" if status == 200 else b"table does not exist") + + return handler, request_ids + + +@pytest.mark.parametrize( + "namespace_path,name,identifier", + [ + pytest.param(None, "test", "test", id="default-root"), + pytest.param([], "test", "test", id="explicit-root"), + pytest.param(["analytics"], "test", "analytics$test", id="namespace"), + pytest.param( + ["analytics", "features"], + "test", + "analytics$features$test", + id="nested", + ), + pytest.param( + ["Team.Images", "raw-items"], + "frame.info", + "Team.Images$raw-items$frame.info", + id="sql-quoted-names", + ), + ], +) +def test_remote_table_repr_namespace(namespace_path, name, identifier): + requests = [] + path = f"/v1/table/{identifier}/describe/" + + def handler(request): + requests.append(request.path) + assert request.path == path + send_json(request, {}) + + expected = f"RemoteTable(dev.{identifier})" + with mock_lancedb_connection(handler) as db: + table = db.open_table(name, namespace_path=namespace_path) + assert table.name == name + assert repr(table) == expected + restored = pickle.loads(pickle.dumps(table)) + + # A diagnostic repr must work from cached identity without reopening the handle. + assert repr(restored) == expected + assert requests == [path] + + +@pytest.mark.asyncio +async def test_async_remote_table_repr_namespace(): + requests = [] + path = "/v1/table/analytics$features$frame.info/describe/" + + def handler(request): + requests.append(request.path) + assert request.path == path + send_json(request, {}) + + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table( + "frame.info", namespace_path=["analytics", "features"] + ) + assert repr(table) == "RemoteTable(analytics$features$frame.info)" + assert requests == [path] + + +@pytest.mark.parametrize("cached", [False, True]) +@pytest.mark.parametrize("namespace_path", [[], ["ns"]]) +def test_remote_open_missing_table(cached, namespace_path, missing_table_handler): + handler, request_ids = missing_table_handler + with mock_lancedb_connection(handler) as db: + if cached: + db.open_table("missing", namespace_path=namespace_path) + with pytest.raises(TableNotFoundError) as exc_info: + db.open_table("missing", namespace_path=namespace_path) + + error = exc_info.value + assert isinstance(error, ValueError) + assert isinstance(error, HttpError) + assert str(error) == "Table 'missing' was not found" + assert error.status_code == 404 + assert error.request_id == request_ids[-1] + assert error.is_transport_error is False + assert error.request_id + assert isinstance(error.__cause__, HttpError) + assert error.__cause__.request_id == error.request_id + assert error.__cause__.status_code == 404 + assert "table does not exist" in str(error.__cause__) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cached", [False, True]) +@pytest.mark.parametrize("namespace_path", [[], ["ns"]]) +async def test_async_remote_open_missing_table( + cached, namespace_path, missing_table_handler +): + handler, request_ids = missing_table_handler + async with mock_lancedb_connection_async(handler) as db: + if cached: + await db.open_table("missing", namespace_path=namespace_path) + with pytest.raises(TableNotFoundError) as exc_info: + await db.open_table("missing", namespace_path=namespace_path) + + error = exc_info.value + assert isinstance(error, ValueError) + assert isinstance(error, HttpError) + assert str(error) == "Table 'missing' was not found" + assert error.status_code == 404 + assert error.request_id == request_ids[-1] + assert error.request_id + assert isinstance(error.__cause__, HttpError) + assert error.__cause__.request_id == error.request_id + assert error.__cause__.status_code == 404 + assert "table does not exist" in str(error.__cause__) + + @pytest.fixture def existence_handler(method, identifier, status): def handler(request): @@ -178,6 +326,112 @@ async def test_async_remote_exists(method, identifier, status, existence_handler assert exc_info.value.status_code == status +def test_remote_describe_namespace_typed_not_found(): + request_ids = [] + + def handler(request): + assert request.command == "POST" + assert request.path == "/v1/namespace/parent$child/describe" + request_ids.append(request.headers["x-request-id"]) + request.send_response(404) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "code": 5, + "error": "Namespace not found", + "error_code": "not_found", + "resource": { + "kind": "namespace", + "name": "child", + "namespace_path": ["parent"], + }, + } + ).encode() + ) + + with mock_lancedb_connection(handler) as db: + with pytest.raises(NamespaceNotFoundError) as exc_info: + db.describe_namespace(["parent", "child"]) + + error = exc_info.value + assert isinstance(error, HttpError) + assert error.error_code == "not_found" + assert error.resource_kind == "namespace" + assert error.resource_name == "child" + assert error.namespace_path == ("parent",) + assert error.status_code == 404 + assert error.request_id == request_ids[-1] + + +def test_remote_create_namespace_typed_already_exists(): + requests = [] + + def handler(request): + requests.append(request.path) + assert request.command == "POST" + assert request.path == "/v1/namespace/parent$child/create" + request.send_response(409) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "code": 6, + "error": "Namespace already exists", + "error_code": "already_exists", + "resource": { + "kind": "namespace", + "name": "child", + "namespace_path": ["parent"], + }, + } + ).encode() + ) + + with mock_lancedb_connection(handler) as db: + with pytest.raises(AlreadyExistsError) as exc_info: + db.create_namespace(["parent", "child"]) + + error = exc_info.value + assert error.error_code == "already_exists" + assert error.resource_kind == "namespace" + assert error.resource_name == "child" + assert error.namespace_path == ("parent",) + assert error.status_code == 409 + assert error.is_transport_error is False + assert len(requests) == 1 + + +def test_remote_legacy_namespace_error_stays_generic_http_error(): + def handler(request): + assert request.path == "/v1/namespace/parent$child/describe" + request.send_response(404) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "code": 5, + "error": "Namespace not found", + } + ).encode() + ) + + with mock_lancedb_connection(handler) as db: + with pytest.raises(HttpError) as exc_info: + db.describe_namespace(["parent", "child"]) + + error = exc_info.value + assert type(error) is HttpError + assert error.error_code is None + assert error.resource_kind is None + assert error.resource_name is None + assert error.namespace_path is None + assert error.status_code == 404 + + @pytest.mark.parametrize("table_id", [[], ["invalid/name"]]) def test_remote_table_exists_rejects_invalid_identifier(table_id): requests = [] @@ -481,6 +735,43 @@ def test_remote_table_branches_sync(): table.branches.delete("exp") +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("json_response", [False, True]) +async def test_remote_branch_delete_conflict_is_not_retried(use_async, json_response): + request_ids = [] + reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files" + + def handler(request): + if request.path == "/v1/table/test/describe/": + _branch_open_handler(request) + return + + assert request.path == "/v1/table/test/branches/delete/" + content_len = int(request.headers["Content-Length"]) + assert json.loads(request.rfile.read(content_len)) == {"name": "exp"} + request_ids.append(request.headers["x-request-id"]) + request.send_response(409) + request.end_headers() + body = json.dumps({"code": 14, "error": reason}) if json_response else reason + request.wfile.write(body.encode()) + + if use_async: + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test") + with pytest.raises(ConflictError, match=re.escape(reason)) as exc_info: + await table.branches.delete("exp") + else: + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + with pytest.raises(ConflictError, match=re.escape(reason)) as exc_info: + table.branches.delete("exp") + + assert request_ids == [exc_info.value.request_id] + assert exc_info.value.status_code == 409 + assert isinstance(exc_info.value, HttpError) + + def test_remote_table_cherry_pick_defaults_to_execute(): cherry_pick_bodies = [] diff = { @@ -763,7 +1054,8 @@ def test_remote_permutation_is_picklable(): @pytest.mark.parametrize("with_schema", [True, False]) -def test_create_table_embedding_functions(with_schema): +@pytest.mark.parametrize("source_target", ["text", "`text`"]) +def test_create_table_embedding_functions(with_schema, source_target): func = MockNonNormTextEmbeddingFunction.create() config = EmbeddingFunctionConfig( source_column="text", vector_column="vector", function=func @@ -861,6 +1153,11 @@ def test_create_table_embedding_functions(with_schema): func.compute_source_embeddings(["goodbye world"])[0].tolist() ] + with pytest.raises( + ValueError, match="source column 'text'.*vector column 'vector'" + ): + table.update(values={source_target: "updated text"}) + def test_create_table_positional_parameters_match_base_contract(): from lancedb.db import DBConnection @@ -961,6 +1258,7 @@ async def test_http_error(): assert exc_info.value.request_id == request_id_holder["request_id"] assert "Internal Server Error" in str(exc_info.value) + assert exc_info.value.is_transport_error is False @pytest.mark.asyncio @@ -985,6 +1283,24 @@ async def test_retry_error(): assert "Try again later" in str(cause) assert cause.request_id == request_id_holder["request_id"] assert cause.status_code == 429 + assert cause.is_transport_error is False + + +def test_connect_retry_error_preserves_transport_classification(): + # Reserve a port without listening, so connection attempts are refused. + with socket.socket() as port_guard: + port_guard.bind(("127.0.0.1", 0)) + port = port_guard.getsockname()[1] + db = lancedb.connect( + "db://dev", + api_key="fake", + host_override=f"http://127.0.0.1:{port}", + client_config={"retry_config": {"connect_retries": 0}}, + ) + with pytest.raises(RetryError) as exc: + list(db.list_tables()) + assert isinstance(exc.value.__cause__, HttpError) + assert exc.value.__cause__.is_transport_error is True def test_table_unimplemented_functions(): @@ -1006,7 +1322,7 @@ def test_table_unimplemented_functions(): message = str(exc_info.value) assert method in message assert "not" in message and "supported" in message - assert "LanceDB Distributed" in message + assert "LanceDB Enterprise" in message assert "cloud" not in message.lower() assert f"search().{method}()" in message @@ -1030,7 +1346,7 @@ def test_remote_conversion_blob_mode_errors(method, blob_mode): async def test_remote_to_lance_rejection( tmp_path, version, expose_location, monkeypatch ): - import lance + lance = pytest.importorskip("lance") location = tmp_path / "test.lance" lance.write_dataset(pa.table({"id": [1]}), location) @@ -1073,43 +1389,56 @@ async def test_remote_to_lance_rejection( await table.to_lance(**options) assert requests == opened_requests - assert "to_lance() is not supported in LanceDB Distributed" in str(sync_error.value) + assert "to_lance() is not supported in LanceDB Enterprise" in str(sync_error.value) assert "query the server" in str(sync_error.value) assert str(sync_error.value) == str(async_error.value) @pytest.mark.asyncio @pytest.mark.parametrize( - "method, kwargs", + "method, kwargs, list_path, table_prefix", [ - ("drop_all_tables", {}), - ("drop_all_tables", {"namespace_path": []}), - ("drop_all_tables", {"namespace_path": ["team"]}), - ("drop_database", {}), + ("drop_all_tables", {}, "/v1/table/", ""), + ("drop_all_tables", {"namespace_path": []}, "/v1/table/", ""), + ( + "drop_all_tables", + {"namespace_path": ["team"]}, + "/v1/namespace/team/table/list", + "team$", + ), + ("drop_database", {}, "/v1/table/", ""), ], ) -async def test_remote_drop_all_tables_not_supported(method, kwargs): +async def test_remote_drop_all_tables(method, kwargs, list_path, table_prefix): requests = [] + drop_paths = { + f"/v1/table/{table_prefix}table1/drop/", + f"/v1/table/{table_prefix}table2/drop/", + } def handler(request): - requests.append(request.path) - request.send_response(500) - request.end_headers() + requests.append((request.command, request.path)) + if request.command == "GET": + assert request.path == list_path + send_json(request, {"tables": ["table1", "table2"]}) + return + + assert request.command == "POST" + assert request.path in drop_paths + send_json(request, {}) with mock_lancedb_connection(handler) as db: - with pytest.raises(NotImplementedError) as sync_error: - getattr(db, method)(**kwargs) + getattr(db, method)(**kwargs) async with mock_lancedb_connection_async(handler) as db: - with pytest.raises(NotImplementedError) as async_error: - await getattr(db, method)(**kwargs) + await getattr(db, method)(**kwargs) - assert "Dropping all tables is not currently supported in the remote API" in str( - sync_error.value - ) - assert "drop_table" in str(sync_error.value) - assert str(sync_error.value) == str(async_error.value) - assert requests == [] + expected_requests = [ + ("GET", list_path), + ("POST", f"/v1/table/{table_prefix}table1/drop/"), + ("POST", f"/v1/table/{table_prefix}table2/drop/"), + ] + assert requests == expected_requests * 2 def test_table_to_pandas_not_supported(): @@ -1132,7 +1461,26 @@ def test_table_to_pandas_not_supported(): def test_table_add_in_threadpool(): + received = [] + def handler(request): + # Consume uploads before responding: closing with unread bytes can reset + # the connection while the client is still reading the response. + if request.headers.get("Transfer-Encoding") == "chunked": + body = bytearray() + while size := int(request.rfile.readline().split(b";")[0], 16): + body.extend(request.rfile.read(size)) + assert request.rfile.read(2) == b"\r\n" + assert request.rfile.read(2) == b"\r\n" + else: + body = request.rfile.read(int(request.headers.get("Content-Length", 0))) + if request.path in ( + "/v1/table/test/create/?mode=create", + "/v1/table/test/insert/", + ): + received.append( + (request.path, pa.ipc.open_stream(body).read_all().to_pylist()) + ) if request.path == "/v1/table/test/insert/": request.send_response(200) request.end_headers() @@ -1171,6 +1519,9 @@ def test_table_add_in_threadpool(): for future in futures: future.result() + assert [rows for path, rows in received if "/create/" in path] == [[{"id": 1}]] + assert [rows for path, rows in received if "/insert/" in path] == [[{"id": 1}]] * 10 + def test_table_create_indices(): # Track received index creation requests to validate name parameter @@ -1448,12 +1799,16 @@ def test_remote_create_index_async_returns_job(): assert json.loads(body)["job_id"] == "job-1" describe_calls.append(1) state = "IN_PROGRESS" if len(describe_calls) == 1 else "DONE" + response = dict(job_id="job-1", job_state=state) + if len(describe_calls) == 1: + response.update( + progress=dict(rows_planned=10, rows_computed=3), + phase="building", + ) 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_state=state)).encode() - ) + request.wfile.write(json.dumps(response).encode()) elif request.path == "/v1/jobs/cancel": assert json.loads(body)["job_id"] == "job-1" request.send_response(200) @@ -1489,12 +1844,46 @@ def test_remote_create_index_async_returns_job(): table = db.create_table("test", [{"id": 1}]) job = table.create_index_async("id", config=BTree()) assert job.id == "job-1" - assert job.wait(timeout=timedelta(seconds=30)) is None + observed = [] + assert job.wait(timeout=timedelta(seconds=30), progress=observed.append) is None assert len(describe_calls) == 2 + assert observed[0]["state"] == "running" + assert observed[0]["rows_planned"] == 10 + assert observed[0]["rows_computed"] == 3 + assert observed[-1]["state"] == "finished" job.cancel() -def test_remote_refresh_async_returns_typed_terminal_result(): +@pytest.mark.asyncio +@pytest.mark.parametrize("async_table", [False, True]) +@pytest.mark.parametrize( + "refresh_kwargs", + [ + {}, + {"batch_size": None}, + {"batch_size": 1}, + {"batch_size": 8}, + {"gpu_class": "a10g", "gpu_count": 2}, + { + "retry_policy": {"transient": True, "max_attempts": 3}, + "error_policy": "skip", + }, + {"retry_policy": {"max_attempts": 1}, "error_policy": "fail"}, + { + "where": "id % 2 = 0", + "error_policy": "skip", + "max_failed_fraction": 0.01, + "max_failed_rows": 50, + "row_timeout_seconds": 30, + "init_timeout_seconds": 120, + "num_workers": 4, + "max_executor_processes_per_worker": 2, + }, + ], +) +async def test_remote_refresh_async_returns_typed_terminal_result( + async_table, refresh_kwargs +): terminal_result = { "rows_assigned": 12, "rows_failed": 0, @@ -1507,7 +1896,31 @@ def test_remote_refresh_async_returns_typed_terminal_result(): content_len = int(request.headers.get("Content-Length", 0)) body = request.rfile.read(content_len) if content_len > 0 else b"" if request.path == "/v1/table/test/backfill_column": - assert json.loads(body)["column"] == "derived" + expected = {"column": "derived"} + if refresh_kwargs.get("batch_size") is not None: + 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("retry_policy") is not None: + expected["retry_policy"] = lancedb.FunctionRetryPolicy.model_validate( + refresh_kwargs["retry_policy"] + ).model_dump(mode="json") + if refresh_kwargs.get("error_policy") is not None: + expected["error_policy"] = refresh_kwargs["error_policy"] + for key in ( + "where", + "max_failed_fraction", + "max_failed_rows", + "row_timeout_seconds", + "init_timeout_seconds", + "num_workers", + "max_executor_processes_per_worker", + ): + if refresh_kwargs.get(key) is not None: + expected[key] = refresh_kwargs[key] + assert json.loads(body) == expected request.send_response(202) request.send_header("Content-Type", "application/json") request.end_headers() @@ -1556,11 +1969,18 @@ def test_remote_refresh_async_returns_typed_terminal_result(): request.send_response(404) request.end_headers() - with mock_lancedb_connection(handler) as db: - table = db.create_table("test", [{"id": 1}]) - job = table.refresh_column_async("derived") - assert job.id == "refresh-1" - result = job.wait(timeout=timedelta(seconds=30)) + if async_table: + 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" + 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" + result = job.wait(timeout=timedelta(seconds=30)) assert isinstance(result, lancedb.RefreshColumnResult) assert result.model_dump() == terminal_result @@ -1568,19 +1988,183 @@ def test_remote_refresh_async_returns_typed_terminal_result(): assert result.version == 8 -def test_remote_function_errors_lists_the_rows_a_refresh_skipped(): +def test_remote_refresh_async_forwards_progress_from_submitted_handle(): + terminal_result = { + "rows_assigned": 12, + "rows_failed": 0, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + } + describe_calls = [] + + def handler(request): + content_len = int(request.headers.get("Content-Length", 0)) + body = request.rfile.read(content_len) if content_len > 0 else b"" + if request.path == "/v1/table/test/backfill_column": + assert json.loads(body) == {"column": "derived"} + request.send_response(202) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b'{"job_id": "refresh-progress"}') + elif request.path == "/v1/jobs/describe": + assert json.loads(body)["job_id"] == "refresh-progress" + describe_calls.append(1) + if len(describe_calls) == 1: + response = { + "job_id": "refresh-progress", + "job_type": "function_refresh", + "job_state": "IN_PROGRESS", + "progress": {"rows_planned": 12, "rows_computed": 4}, + "phase": "running", + } + else: + response = { + "job_id": "refresh-progress", + "job_type": "function_refresh", + "job_state": "DONE", + "result": terminal_result, + } + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + elif request.path == "/v1/table/test/create/?mode=create": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b"{}") + elif request.path == "/v1/table/test/describe/": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "version": 1, + "schema": { + "fields": [ + { + "name": "id", + "type": {"type": "int64"}, + "nullable": False, + } + ] + }, + } + ).encode() + ) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + table = db.create_table("test", [{"id": 1}]) + job = table.refresh_column_async("derived") + observed = [] + result = job.wait(timeout=timedelta(seconds=30), progress=observed.append) + + assert result.rows_filled == 12 + assert result.version == 8 + assert len(describe_calls) == 2 + assert observed[0]["state"] == "running" + assert observed[0]["rows_planned"] == 12 + assert observed[0]["rows_computed"] == 4 + assert observed[-1]["state"] == "finished" + + +@pytest.mark.parametrize( + "refresh_kwargs,message", + [ + ({"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"), + ({"retry_policy": {"transient": True, "max_attempts": 0}}, "retry_policy"), + ({"error_policy": "retry"}, "error_policy"), + ({"where": " "}, "where"), + ({"max_failed_fraction": 1.5}, "max_failed_fraction"), + ({"max_failed_rows": -1}, "max_failed_rows"), + ({"row_timeout_seconds": 0}, "row_timeout_seconds"), + ({"init_timeout_seconds": -5}, "init_timeout_seconds"), + ({"num_workers": 0}, "num_workers"), + ( + {"max_executor_processes_per_worker": -2}, + "max_executor_processes_per_worker", + ), + ], +) +@pytest.mark.asyncio +async def test_remote_refresh_rejects_invalid_options_before_request( + refresh_kwargs, message +): + backfill_requests = [] + + def handler(request): + if request.path == "/v1/table/test/describe/": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "version": 1, + "schema": { + "fields": [ + { + "name": "id", + "type": {"type": "int64"}, + "nullable": False, + } + ] + }, + } + ).encode() + ) + elif request.path == "/v1/table/test/backfill_column": + backfill_requests.append(request.path) + request.send_response(202) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b'{"job_id": "unexpected"}') + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + with pytest.raises(ValueError, match=message): + table.refresh_column_async("derived", **refresh_kwargs) + + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test") + with pytest.raises(ValueError, match=message): + await table.refresh_column_async("derived", **refresh_kwargs) + + assert backfill_requests == [] + + +@pytest.mark.parametrize("attempts", [None, 3]) +def test_remote_function_errors_lists_the_rows_a_refresh_skipped(attempts): listing = { "records": [ { "job_id": "j-7", "fragment_id": 3, "row_offset": 9, + "row_id": 42, + "row_address": 12884901897, "column": "embedding", "function": "embed", "function_version": "2", "table_version": 11, "error_type": "ValueError", "error_message": "bad input 'x'", + "attempts": attempts, + "traceback": ( + "Traceback (most recent call last):\nValueError: bad input 'x'" + ), "created_at_millis": 1700000000000, } ], @@ -1625,7 +2209,18 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(): assert errors.truncated is True assert [r.error_message for r in errors.records] == ["bad input 'x'"] assert errors.records[0].row_offset == 9 + assert errors.records[0].row_id == 42 + assert errors.records[0].row_address == 12884901897 assert errors.records[0].function_version == "2" + assert errors.records[0].attempts == attempts + assert errors.records[0].traceback == ( + "Traceback (most recent call last):\nValueError: bad input 'x'" + ) + assert repr(errors.records[0]) == ( + 'FunctionErrorRecord(job_id="j-7", fragment_id=3, row_offset=9, ' + 'row_address=12884901897, column="embedding", ' + 'error_type="ValueError", error_message="bad input \'x\'")' + ) assert (errors.fragments[0].rows_skipped, errors.fragments[0].rows_recorded) == ( 500, 100, @@ -1633,6 +2228,114 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(): assert everything.truncated is True +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("failure", ["send", "read"]) +async def test_remote_job_wait_recovers_from_disconnection(sync, failure): + polls = 0 + + def handler(request): + nonlocal polls + assert request.path == "/v1/jobs/describe" + body = request.rfile.read(int(request.headers["Content-Length"])) + assert json.loads(body)["job_id"] == "job-1" + polls += 1 + if polls in (2, 3): + # Fail both the initial wait and its first recovery probe, after + # open_job has successfully fetched the still-running job. + if failure == "read": + request.send_response(200) + request.send_header("Content-Length", "1000") + request.end_headers() + request.wfile.write(b'{"job_id":') + request.wfile.flush() + request.connection.shutdown(socket.SHUT_RDWR) + request.close_connection = True + return + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + state = "DONE" if polls >= 5 else "IN_PROGRESS" + request.wfile.write(json.dumps(dict(job_id="job-1", job_state=state)).encode()) + + config = {"retry_config": {"retries": 0, "connect_retries": 0, "read_retries": 0}} + if sync: + 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" + 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 polls == 5 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_remote_job_wait_disconnection_timeout_can_be_resumed(sync): + polls = 0 + finished = False + + def handler(request): + nonlocal polls + assert request.path == "/v1/jobs/describe" + request.rfile.read(int(request.headers["Content-Length"])) + polls += 1 + if polls > 1 and not finished: + request.connection.shutdown(socket.SHUT_RDWR) + request.close_connection = True + return + request.send_response(200) + request.end_headers() + state = "DONE" if finished else "IN_PROGRESS" + request.wfile.write(json.dumps(dict(job_id="job-1", job_state=state)).encode()) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("job-1") + with pytest.raises(ConnectionError) as exc: + job.wait(timeout=timedelta(seconds=0.5)) + finished = True + assert db.open_job("job-1").wait() is None + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("job-1") + with pytest.raises(ConnectionError) as exc: + await job.wait(timeout=timedelta(seconds=0.5)) + finished = True + resumed = await db.open_job("job-1") + assert await resumed.wait() is None + assert "job 'job-1' may still be running" in str(exc.value) + assert "db.open_job('job-1')" in str(exc.value) + assert isinstance(exc.value.__cause__, HttpError) + assert exc.value.__cause__.is_transport_error is True + + +@pytest.mark.parametrize("payload", [b"{", b"{}"]) +def test_remote_job_wait_does_not_retry_malformed_description(payload): + polls = 0 + + def handler(request): + nonlocal polls + assert request.path == "/v1/jobs/describe" + request.rfile.read(int(request.headers["Content-Length"])) + polls += 1 + request.send_response(200) + request.end_headers() + request.wfile.write( + b'{"job_id":"job-1","job_state":"IN_PROGRESS"}' if polls == 1 else payload + ) + + with mock_lancedb_connection(handler) as db: + job = db.open_job("job-1") + with pytest.raises(HttpError, match="failed to parse job description") as exc: + job.wait(timeout=timedelta(seconds=5)) + assert exc.value.is_transport_error is False + assert polls == 2 + + def test_remote_job_wait_raises_on_failure(): from lancedb.exceptions import JobFailedError from lancedb.index import BTree @@ -1681,8 +2384,10 @@ def test_remote_job_wait_raises_on_failure(): with mock_lancedb_connection(handler) as db: table = db.create_table("test", [{"id": 1}]) job = table.create_index_async("id", config=BTree()) - with pytest.raises(JobFailedError, match="job-2"): + with pytest.raises(JobFailedError, match="job-2") as exc_info: job.wait() + assert exc_info.value.job_id == "job-2" + assert exc_info.value.sql_job_id is None @pytest.mark.parametrize("server_version", ["0.2.0", "0.6.0"]) @@ -1860,7 +2565,7 @@ def test_remote_create_index_new_api(caplog, rq_kwargs): assert received_requests[5]["replace"] is False assert "replace is not supported" not in caplog.text assert caplog.messages == [ - "GPU accelerator is not supported in LanceDB Distributed " + "GPU accelerator is not supported in LanceDB Enterprise " "and will be ignored." ] @@ -1905,7 +2610,6 @@ def remote_unsupported_operations(): return [ ("uses_v2_manifest_paths", (), {}, "uses_v2_manifest_paths"), ("migrate_v2_manifest_paths", (), {}, "migrate_manifest_paths_v2"), - ("optimize", (), {}, "optimize"), ("create_index", ("vector",), {"config": HnswPq()}, "IVF_HNSW_PQ"), ] @@ -1919,7 +2623,7 @@ def test_remote_unsupported_operations_sync(method, args, kwargs, operation): with pytest.raises(NotImplementedError) as error: getattr(table, method)(*args, **kwargs) expected = f"LanceDBError: not supported: {operation} is not supported " - expected += "in LanceDB Distributed." + expected += "in LanceDB Enterprise." if operation == "IVF_HNSW_PQ": expected += " Please use IVF_HNSW_SQ instead." assert str(error.value) == expected @@ -1937,7 +2641,7 @@ async def test_remote_unsupported_operations_async(method, args, kwargs, operati with pytest.raises(NotImplementedError) as error: await getattr(table, method)(*args, **kwargs) expected = f"LanceDBError: not supported: {operation} is not supported " - expected += "in LanceDB Distributed." + expected += "in LanceDB Enterprise." if operation == "IVF_HNSW_PQ": expected += " Please use IVF_HNSW_SQ instead." assert str(error.value) == expected @@ -1949,7 +2653,7 @@ def test_remote_unsupported_legacy_hnsw_pq(): with pytest.warns(DeprecationWarning, match="create_index"): with pytest.raises( NotImplementedError, - match="IVF_HNSW_PQ is not supported in LanceDB Distributed. " + match="IVF_HNSW_PQ is not supported in LanceDB Enterprise. " "Please use IVF_HNSW_SQ instead.", ): table.create_index( @@ -1967,7 +2671,7 @@ def test_remote_python_only_messages(): with pytest.raises(NotImplementedError) as error: getattr(table, method)() assert str(error.value) == ( - f"{method}() is not supported in LanceDB Distributed. " + f"{method}() is not supported in LanceDB Enterprise. " f"Use table.search().{method}() instead." ) for method in ["compact_files", "cleanup_old_versions"]: @@ -1975,7 +2679,7 @@ def test_remote_python_only_messages(): getattr(table, method)() assert ( str(warning[0].message) - == f"{method}() is a no-op in LanceDB Distributed." + == f"{method}() is a no-op in LanceDB Enterprise." ) @@ -2323,6 +3027,118 @@ def test_checkpoint_rte_sync(): assert called == ["flush_rte", "get_rte_stats"] +@contextlib.contextmanager +def table_overrides_test_table(overrides_handler): + def handler(request): + parsed = urlparse(request.path) + if parsed.path in ( + "/admin/table/overrides", + "/admin/table/overrides/reset", + ): + overrides_handler(request, parsed) + elif parsed.path == "/v1/table/test/describe/": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b'{"version": 1, "schema": {"fields": []}}') + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + yield db.open_table("test") + + +def assert_table_overrides_query(parsed): + query = parse_qs(parsed.query) + assert query == {"db": ["dev"], "table": ["test"]} + + +def test_remote_table_exposes_table_overrides_methods(): + from lancedb.remote.table import RemoteTable + + for name in ( + "get_table_overrides", + "update_table_overrides", + "reset_table_overrides", + ): + assert hasattr(RemoteTable, name) + + +def test_get_table_overrides_sync_remote_table(): + def overrides_handler(request, parsed): + assert request.command == "GET" + assert parsed.path == "/admin/table/overrides" + assert_table_overrides_query(parsed) + send_json(request, {"job_types": {"cleanup": {"enabled": False}}}) + + with table_overrides_test_table(overrides_handler) as table: + assert table.get_table_overrides() == { + "job_types": {"cleanup": {"enabled": False}} + } + + +def test_update_table_overrides_sync_remote_table_merges_existing_fields(): + calls = [] + + def overrides_handler(request, parsed): + calls.append(request.command) + assert parsed.path == "/admin/table/overrides" + if request.command == "GET": + assert_table_overrides_query(parsed) + send_json( + request, + { + "job_types": { + "compaction": {"enabled": True}, + "reindex_vector": {"table": {"num_workers": 3}}, + }, + "unknown": {"keep": True}, + }, + ) + elif request.command == "PUT": + body = read_json_body(request) + assert body["db"] == "dev" + assert body["namespace"] == [] + assert body["table"] == "test" + assert body["overrides"] == { + "job_types": { + "compaction": {"enabled": True}, + "cleanup": {"enabled": False}, + "reindex_vector": {"table": {"num_workers": 3}}, + }, + "unknown": {"keep": True}, + } + send_json(request, body["overrides"]) + else: + raise AssertionError(f"unexpected method: {request.command}") + + with table_overrides_test_table(overrides_handler) as table: + assert table.update_table_overrides( + job_types={"cleanup": {"enabled": False}} + ) == { + "job_types": { + "compaction": {"enabled": True}, + "cleanup": {"enabled": False}, + "reindex_vector": {"table": {"num_workers": 3}}, + }, + "unknown": {"keep": True}, + } + + assert calls == ["GET", "PUT"] + + +def test_reset_table_overrides_sync_remote_table(): + def overrides_handler(request, parsed): + assert request.command == "POST" + assert parsed.path == "/admin/table/overrides/reset" + assert_table_overrides_query(parsed) + send_json(request, {}) + + with table_overrides_test_table(overrides_handler) as table: + assert table.reset_table_overrides() == {} + + @contextlib.contextmanager def query_test_table( query_handler, @@ -2524,8 +3340,41 @@ def test_remote_take_row_ids_with_row_id(): assert bodies[-1]["with_row_id"] is True with query_test_table(handler) as table: - table.take_row_ids([0, 1]).to_arrow() - assert "with_row_id" not in bodies[-1] + result = table.take_row_ids([0, 1]).to_arrow() + assert result.column_names == ["id"] + assert bodies[-1]["with_row_id"] is True + + +@pytest.mark.parametrize("with_row_id", [False, True]) +@pytest.mark.parametrize("selection", [None, [], ["id"], ["_rowid", "id"]]) +def test_remote_take_row_ids_order_and_roundtrip(with_row_id, selection): + def handler(body): + assert body["with_row_id"] is True + assert "_rowid IN" in body["filter"] + assert "take_row_ids" not in body + assert "_rowid" not in body.get("columns", []) + data = pa.table( + { + "id": pa.chunked_array([[1, 5], [17]]), + "_rowid": pa.chunked_array([[1, 5], [17]], type=pa.uint64()), + } + ) + return data.select(body.get("columns", ["id"]) + ["_rowid"]) + + with query_test_table(handler) as table: + take = table.take_row_ids([17, 5, 2**64 - 1, 17, 1], with_row_id=with_row_id) + if selection is not None: + take = take.select(selection) + result = take.to_batches(max_batch_length=1).read_all() + assert result.num_rows == 4 + expected_columns = ["id"] if selection is None else list(selection) + if with_row_id: + expected_columns = [name for name in expected_columns if name != "_rowid"] + expected_columns.append("_rowid") + assert result.column_names == expected_columns + for column in expected_columns: + assert result[column].to_pylist() == [17, 5, 17, 1] + assert table._execute_query(take.to_query_object()).read_all() == result def test_query_sync_minimal(): @@ -2550,6 +3399,100 @@ def test_query_sync_minimal(): assert data == expected +def _arrow_stream(batches): + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, batches[0].schema) as writer: + for batch in batches: + writer.write_batch(batch) + return sink.getvalue().to_pybytes() + + +@contextlib.contextmanager +def streamed_query_table(write_body): + """Yield a remote table and the headers of each query request it sends. + + Queries get a 200 response with stream framing, whose body ``write_body`` + writes after the other headers. + """ + queries = [] + + def handler(request): + if request.path == "/v1/table/test/describe/": + id_field = {"name": "id", "type": {"type": "int32"}, "nullable": True} + schema = {"fields": [id_field]} + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps({"version": 7, "schema": schema}).encode()) + elif request.path == "/v1/table/test/query/": + queries.append(request.headers) + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", "7") + write_body(request) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + yield db.open_table("test"), queries + + +def test_query_sync_to_batches_yields_before_the_body_is_complete(): + batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)] + body = _arrow_stream(batches) + # The schema and first batch, without the 8-byte end-of-stream marker. + head = _arrow_stream(batches[:1])[:-8] + first_batch_read = threading.Event() + waited_for_client = [] + + def write_body(request): + request.end_headers() + request.wfile.write(head) + waited_for_client.append(first_batch_read.wait(10)) + request.wfile.write(body[len(head) :]) + + with streamed_query_table(write_body) as (table, queries): + reader = table.search().to_batches() + assert reader.read_next_batch()["id"].to_pylist() == [0] + first_batch_read.set() + assert reader.read_all()["id"].to_pylist() == [1, 2] + + # The wait times out if the client needs the whole body for the first batch. + assert waited_for_client == [True] + assert queries[0]["Accept"] == ( + "application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9" + ) + + +@pytest.mark.parametrize("abort", [False, True], ids=["clean_end", "abort"]) +def test_query_sync_interrupted_response_raises(abort): + batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)] + head = _arrow_stream(batches[:1])[:-8] + + def write_body(request): + if abort: + # Closing before the promised length is a transport error. Otherwise + # the body ends cleanly, but without the end-of-stream marker. + request.send_header("Content-Length", str(len(head) + 100)) + request.end_headers() + request.wfile.write(head) + + with streamed_query_table(write_body) as (table, queries): + reader = table.search().to_batches() + assert reader.read_next_batch()["id"].to_pylist() == [0] + with pytest.raises(ResponseInterruptedError) as exc_info: + reader.read_next_batch() + + error = exc_info.value + assert isinstance(error, HttpError) + assert (error.batches, error.rows, error.table_version) == (1, 1, 7) + assert error.request_id == queries[0]["x-request-id"] + assert error.is_transport_error is abort + assert len(queries) == 1 + + @pytest.mark.parametrize("query_type", ["auto", "vector", "hybrid"]) @pytest.mark.parametrize("vector_column_name", [None, "embedding"]) def test_query_sync_text_embedding(query_type, vector_column_name): @@ -3992,7 +4935,8 @@ def test_remote_blob_columns_and_fetch(): def test_sync_remote_blob_pandas_avoids_storage_access( tmp_path, monkeypatch, blob_mode ): - import lance + pytest.importorskip("pandas") + lance = pytest.importorskip("lance") location = tmp_path / "remote.lance" lance.write_dataset(pa.table({"id": [7], "image": [b"server-owned"]}), location) @@ -4059,12 +5003,13 @@ async def test_async_remote_to_lance_rejects_storage_access(monkeypatch): raise AssertionError("remote table URI must not be requested") monkeypatch.setattr(table, "uri", fail_uri) - with pytest.raises(NotImplementedError, match="LanceDB Distributed"): + with pytest.raises(NotImplementedError, match="LanceDB Enterprise"): await table.to_lance() @pytest.mark.asyncio async def test_async_remote_blob_descriptions_to_pandas_uses_server(monkeypatch): + pytest.importorskip("pandas") with blob_remote_table() as remote_table: table = remote_table._table @@ -4160,6 +5105,7 @@ async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch): @pytest.mark.asyncio @pytest.mark.parametrize("blob_mode", ["bytes", "lazy"]) async def test_async_remote_nonblob_projection_to_pandas(blob_mode): + pytest.importorskip("pandas") with blob_remote_table() as remote_table: df = await ( remote_table._table.query().select(["id"]).to_pandas(blob_mode=blob_mode) @@ -4234,6 +5180,7 @@ def test_remote_blob_query_stashes_row_ids_for_fetch(): def test_remote_blob_query_to_pandas(): + pytest.importorskip("pandas") with blob_remote_table() as table: query = table.search().select(["id", "image"]).limit(3) df = query.to_pandas(blob_mode="descriptions", split_blocks=True) @@ -4260,6 +5207,7 @@ def test_remote_blob_query_to_pandas_rejects_unpinned_fetch(monkeypatch, blob_mo @pytest.mark.parametrize("blob_mode", ["lazy", "bytes"]) def test_remote_nonblob_projection_to_pandas(blob_mode): + pytest.importorskip("pandas") with blob_remote_table() as table: df = table.search().select(["id"]).to_pandas(blob_mode=blob_mode) @@ -4269,6 +5217,7 @@ def test_remote_nonblob_projection_to_pandas(blob_mode): @pytest.mark.asyncio async def test_async_remote_blob_query_to_pandas_flatten(): + pytest.importorskip("pandas") with blob_remote_table() as table: df = ( await table._table.query() @@ -4356,6 +5305,9 @@ def test_remote_connection_jobs_surface(): job_type="create_index", state="in_progress", created_at_millis=1000, + progress=dict(rows_planned=10, rows_computed=4), + phase="running", + paused=True, ) ], page_token="next", @@ -4409,8 +5361,20 @@ def test_remote_connection_jobs_surface(): job_state="FAILED", creation_ms=1000, spec=dict(column="vec"), + progress=dict(rows_planned=10, rows_computed=4), + phase="initializing", + queue_reason="waiting for capacity", + waiting_for_job_id="job-maintenance", + paused_at_millis=1200, failure=dict( - phase="execute", message="worker died", retryable=True + phase="execute", + message="worker died", + traceback=( + "Traceback (most recent call last):\n" + "RuntimeError: worker died" + ), + retryable=True, + sql_job_id="sql-job-1", ), ) ).encode() @@ -4459,6 +5423,16 @@ def test_remote_connection_jobs_surface(): assert [job.job_id for job in jobs] == ["job-1", "job-2"] assert jobs[0].state == "running" assert jobs[0].table == "t1" + assert jobs[0].progress == { + "job_type": "create_index", + "state": "running", + "creation_ms": 1000, + "paused": True, + "phase": "running", + "rows_planned": 10, + "rows_computed": 4, + } + assert jobs[0].paused is True assert jobs[1].state == "finished" assert db.cancel_job("job-1") is True @@ -4479,10 +5453,32 @@ def test_remote_connection_jobs_surface(): # Opening already populated the handle. assert job.state == "failed" assert job.spec == {"column": "vec"} + progress = job.progress() + assert progress["state"] == "failed" + assert progress["rows_computed"] == 4 + assert progress["paused"] is True + assert progress["phase"] == "initializing" + 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 == ( + "Traceback (most recent call last):\nRuntimeError: worker died" + ) + assert job.failure.sql_job_id == "sql-job-1" + assert repr(job.failure) == ( + 'JobFailureInfo(phase="execute", message="worker died", retryable=True, ' + 'sql_job_id="sql-job-1")' + ) assert job.status() == "failed" - with pytest.raises(JobFailedError, match="worker died"): - job.wait(timeout=timedelta(seconds=5)) + observed = [] + with pytest.raises(JobFailedError, match="worker died") as exc_info: + job.wait(timeout=timedelta(seconds=5), progress=observed.append) + assert exc_info.value.job_id == "job-1" + assert exc_info.value.sql_job_id == "sql-job-1" + assert observed[0]["state"] == "failed" + assert observed[0]["rows_computed"] == 4 + assert finished.progress()["paused"] is False def test_remote_job_handle_reports_its_own_detail(): @@ -4572,55 +5568,570 @@ def test_remote_job_handle_reports_its_own_detail(): } -def test_view_crud_addresses_its_own_routes(): - # The view verbs are their own routes, and the schema comes back in the - # namespace spec's JSON encoding, decoded into a pyarrow schema. - paths = [] +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.asyncio +async def test_remote_list_gpu_classes(is_async): + requests = [] def handler(request): - paths.append((request.command, request.path)) - if request.path.endswith("/view/list"): - body = {"views": ["adults"]} - elif request.path.endswith("/drop"): - body = {} - else: - body = { - "name": "adults", - "namespace": ["analytics"], - "query": "SELECT name FROM people", - "default_database": "dev", - "default_namespace": ["analytics"], - "schema": { - "fields": [ - {"name": "name", "nullable": True, "type": {"type": "utf8"}} - ] - }, - } + requests.append((request.command, request.path)) request.send_response(200) request.send_header("Content-Type", "application/json") request.end_headers() - request.wfile.write(json.dumps(body).encode()) + request.wfile.write( + json.dumps( + { + "gpu_classes": [ + { + "name": "default", + "resource_name": "nvidia.com/gpu", + "gpu_model": "NVIDIA A10G", + "gpu_memory_bytes": 25769803776, + "max_gpu_count_per_worker": 1, + "cpu_millis": 4000, + "memory_bytes": 25769803776, + "ephemeral_storage_bytes": 1073741824, + }, + { + "name": "h100", + "resource_name": "nvidia.com/gpu", + "gpu_model": "NVIDIA H100", + "gpu_memory_bytes": 85899345920, + "max_gpu_count_per_worker": 8, + "cpu_millis": None, + "memory_bytes": None, + "ephemeral_storage_bytes": None, + }, + ] + } + ).encode() + ) + + if is_async: + async with mock_lancedb_connection_async(handler) as db: + classes = await db.list_gpu_classes() + else: + with mock_lancedb_connection(handler) as db: + classes = db.list_gpu_classes() + + assert requests == [("GET", "/v1/gpu/classes")] + assert len(classes) == 2 + assert isinstance(classes[0], lancedb.GpuClass) + assert classes[0].name == "default" + assert classes[0].gpu_model == "NVIDIA A10G" + assert classes[0].gpu_memory_bytes == 25769803776 + assert classes[1].max_gpu_count_per_worker == 8 + assert classes[1].cpu_millis is None + + +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.asyncio +async def test_remote_list_gpu_classes_older_server(is_async): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(404) + request.end_headers() + + with pytest.raises(NotImplementedError, match="/v1/gpu/classes"): + if is_async: + async with mock_lancedb_connection_async(handler) as db: + await db.list_gpu_classes() + else: + with mock_lancedb_connection(handler) as db: + db.list_gpu_classes() + + assert requests == ["/v1/gpu/classes"] + + +def _property_graph_handler(calls, respond): + """A mock route handler recording ``(method, path, body)`` and answering + with the ``(status, body)`` that ``respond(path, body)`` returns, as JSON.""" + + def handler(request): + length = int(request.headers.get("Content-Length") or 0) + raw = request.rfile.read(length) if length else b"" + body = json.loads(raw) if raw else None + calls.append((request.command, request.path, body)) + status, payload = respond(request.path, body) + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(payload).encode()) + + return handler + + +SOCIAL_NODES = [ + NodeTable("person", key="person_id", label="Person", properties=["name"]) +] +SOCIAL_EDGES = [ + EdgeTable( + "knows", + label="KNOWS", + source=Endpoint("src_id", references=("person", "person_id")), + destination=Endpoint("dst_id", references=("person", "person_id")), + ) +] +# The create body for the tables above. The edge table leaves its properties +# out, which means every column. +SOCIAL_DEFINITION = { + "nodes": [ + { + "table": "person", + "key": "person_id", + "label": "Person", + "properties": ["name"], + } + ], + "edges": [ + { + "table": "knows", + "label": "KNOWS", + "source": { + "column": "src_id", + "references": {"table": "person", "column": "person_id"}, + }, + "destination": { + "column": "dst_id", + "references": {"table": "person", "column": "person_id"}, + }, + } + ], +} +# Create resolves each table's properties, the key and endpoint columns always +# among them. +RESOLVED_NODES = [replace(SOCIAL_NODES[0], properties=["person_id", "name"])] +RESOLVED_EDGES = [replace(SOCIAL_EDGES[0], properties=["src_id", "dst_id", "since"])] + + +def _social_description(namespace): + described = copy.deepcopy(SOCIAL_DEFINITION) + described["nodes"][0]["properties"] = RESOLVED_NODES[0].properties + described["edges"][0]["properties"] = RESOLVED_EDGES[0].properties + return {"name": "social", "namespace": namespace, **described} + + +def test_property_graph_crud_addresses_its_own_routes(): + # The definition is the create body and describe posts an empty object. + # An accepted drop hands back its cleanup job, which drop waits on. + calls = [] + + def respond(path, body): + if path.startswith("/v1/namespace/analytics/property_graph/list"): + if "page_token=p2" in path: + return 200, {"property_graphs": ["payments"]} + return 200, {"property_graphs": ["social"], "page_token": "p2"} + if path.endswith("/drop"): + return 202, {"job_id": "j1-pg-drop"} + if path == "/v1/jobs/describe": + return 200, {"job_id": body["job_id"], "job_state": "DONE"} + return 200, _social_description(["analytics"]) + + with mock_lancedb_connection(_property_graph_handler(calls, respond)) as db: + graph = db.create_property_graph( + "social", SOCIAL_NODES, SOCIAL_EDGES, namespace_path=["analytics"] + ) + assert isinstance(graph, PropertyGraph) + assert (graph.name, graph.namespace_path) == ("social", ["analytics"]) + assert graph.describe() == PropertyGraphDescription( + name="social", + namespace_path=["analytics"], + nodes=RESOLVED_NODES, + edges=RESOLVED_EDGES, + ) + + opened = db.open_property_graph("social", namespace_path=["analytics"]) + assert (opened.name, opened.namespace_path) == ("social", ["analytics"]) + + graphs = db.list_property_graphs(namespace_path=["analytics"], page_limit=1) + assert list(graphs) == ["social", "payments"] + + db.drop_property_graph("social", namespace_path=["analytics"]) + + assert calls == [ + ("POST", "/v1/property_graph/analytics$social/create", SOCIAL_DEFINITION), + ("POST", "/v1/property_graph/analytics$social/describe", {}), + ("POST", "/v1/property_graph/analytics$social/describe", {}), + ("GET", "/v1/namespace/analytics/property_graph/list?limit=1", None), + ( + "GET", + "/v1/namespace/analytics/property_graph/list?page_token=p2&limit=1", + None, + ), + ("POST", "/v1/property_graph/analytics$social/drop", None), + ("POST", "/v1/jobs/describe", {"job_id": "j1-pg-drop"}), + ] + + +def test_remote_add_columns_reader_not_supported(): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b'{"version": 1, "schema": {"fields": []}}') with mock_lancedb_connection(handler) as db: - view = db.create_view( - "adults", "SELECT name FROM people", namespace_path=["analytics"] - ) - assert view.name == "adults" - assert view.namespace_path == ["analytics"] - assert view.query == "SELECT name FROM people" - assert view.default_database == "dev" - assert view.default_namespace_path == ["analytics"] - assert view.schema == pa.schema([pa.field("name", pa.utf8(), nullable=True)]) + table = db.open_table("test") + requests.clear() + with pytest.raises(NotImplementedError, match="Only SQL expressions"): + table.add_columns(pa.table({"score": [10]}).to_reader()) + assert all("/add_columns/" not in path for path in requests) - described = db.describe_view("adults", namespace_path=["analytics"]) - assert described.schema == view.schema - assert list(db.list_views(namespace_path=["analytics"])) == ["adults"] - db.drop_view("adults", namespace_path=["analytics"]) +@pytest.mark.asyncio +async def test_async_property_graph_handles(): + calls = [] - assert paths == [ - ("POST", "/v1/view/analytics$adults/create"), - ("POST", "/v1/view/analytics$adults/describe"), - ("GET", "/v1/namespace/analytics/view/list"), - ("POST", "/v1/view/analytics$adults/drop"), + def respond(path, body): + if path.endswith("/property_graph/list"): + return 200, {"property_graphs": ["social"]} + if path.endswith("/drop"): + return 200, {} + return 200, _social_description([]) + + async with mock_lancedb_connection_async( + _property_graph_handler(calls, respond) + ) as db: + graph = await db.create_property_graph("social", SOCIAL_NODES) + assert isinstance(graph, AsyncPropertyGraph) + described = await graph.describe() + assert (described.namespace_path, described.nodes) == ([], RESOLVED_NODES) + + opened = await db.open_property_graph("social") + assert isinstance(opened, AsyncPropertyGraph) + assert [name async for name in db.list_property_graphs()] == ["social"] + await db.drop_property_graph("social") + + assert calls == [ + ( + "POST", + "/v1/property_graph/social/create", + {"nodes": SOCIAL_DEFINITION["nodes"], "edges": []}, + ), + ("POST", "/v1/property_graph/social/describe", {}), + ("POST", "/v1/property_graph/social/describe", {}), + ("GET", "/v1/namespace/$/property_graph/list", None), + ("POST", "/v1/property_graph/social/drop", None), ] + + +def test_a_missing_property_graph_is_not_found(): + # Opening describes the graph, so a name no graph holds fails there. + calls = [] + + def respond(path, body): + return 404, {"error": "property graph 'social' not found"} + + with mock_lancedb_connection(_property_graph_handler(calls, respond)) as db: + with pytest.raises(HttpError) as missing: + db.open_property_graph("social") + assert missing.value.status_code == 404 + with pytest.raises(HttpError) as missing: + db.drop_property_graph("social") + assert missing.value.status_code == 404 + + assert calls == [ + ("POST", "/v1/property_graph/social/describe", {}), + ("POST", "/v1/property_graph/social/drop", None), + ] + + +def test_a_property_graph_takes_node_and_edge_tables(): + # A definition of the wrong shape is refused before any request is made. + calls = [] + with mock_lancedb_connection( + _property_graph_handler(calls, lambda path, body: (200, {})) + ) as db: + with pytest.raises(TypeError, match="nodes are NodeTable"): + db.create_property_graph("social", SOCIAL_EDGES) + with pytest.raises(TypeError, match="not NodeTable"): + db.create_property_graph("social", SOCIAL_NODES, SOCIAL_NODES) + with pytest.raises(TypeError, match="are Endpoint, not tuple"): + db.create_property_graph( + "social", + SOCIAL_NODES, + [replace(SOCIAL_EDGES[0], source=("person", "person_id"))], + ) + with pytest.raises(TypeError, match="not a string"): + db.create_property_graph( + "social", [replace(SOCIAL_NODES[0], properties="name")] + ) + assert calls == [] + + +def test_local_connections_refuse_property_graphs(tmp_path): + db = lancedb.connect(tmp_path) + refused = "Property graph operations are not supported" + with pytest.raises(NotImplementedError, match=refused): + db.create_property_graph("social", SOCIAL_NODES, SOCIAL_EDGES) + with pytest.raises(NotImplementedError, match=refused): + db.open_property_graph("social") + with pytest.raises(NotImplementedError, match=refused): + list(db.list_property_graphs()) + with pytest.raises(NotImplementedError, match=refused): + db.drop_property_graph("social") + + +@pytest.mark.parametrize( + "status,category,type_name", + [ + (400, "column_not_found", "ColumnNotFoundError"), + (400, "schema_mismatch", "SchemaMismatchError"), + (404, "table_not_found", "TableNotFoundError"), + (404, "reference_not_found", "ReferenceNotFoundError"), + ], +) +@pytest.mark.parametrize("operation", ["describe_namespace", "open_table"]) +def test_remote_input_error_metadata_crosses_native_boundary( + status, category, type_name, operation +): + from lancedb.remote import errors + + request_ids = [] + + def handler(request): + request_ids.append(request.headers["x-request-id"]) + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.send_header("x-lancedb-error-code", category) + request.send_header("x-lancedb-sql-job-id", "sql-job-1") + request.send_header("x-job-request-id", "worker-request") + request.end_headers() + request.wfile.write(json.dumps({"error": "original diagnostic"}).encode()) + + with mock_lancedb_connection(handler) as db: + with pytest.raises(getattr(errors, type_name)) as exc_info: + if operation == "open_table": + db.open_table("analytics") + else: + db.describe_namespace(["analytics"]) + error = exc_info.value + assert isinstance(error, HttpError) + assert error.request_id == request_ids[-1] + assert error.status_code == status + assert error.error_code == category + assert error.job_id == "sql-job-1" + assert error.job_request_id == "worker-request" + assert str(error) == "original diagnostic" + + +def _create_table_handler(request): + if 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"{}") + else: + request.send_response(404) + request.end_headers() + + +@contextlib.contextmanager +def _mock_remote_sql_connection(flight_server): + """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) + ) as rest_server: + rest_port = rest_server.server_address[1] + handle = start_server_thread(rest_server) + try: + with flight_server: + yield { + "uri": "db://dev", + "api_key": "fake", + "host_override": f"http://127.0.0.1:{rest_port}", + "sql_host_override": f"grpc://127.0.0.1:{flight_server.port}", + } + finally: + rest_server.shutdown() + handle.join() + + +@contextlib.contextmanager +def _mock_remote_table_with_sql(flight_server): + with _mock_remote_sql_connection(flight_server) as kwargs: + yield lancedb.connect(**kwargs).create_table("test", [{"id": 1}]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "options,sql_options", + [ + ({"target_rows_per_fragment": 100}, [b"target_rows_per_fragment = 100"]), + ( + {"target_rows_per_fragment": 1_048_576}, + [b"target_rows_per_fragment = 1048576"], + ), + ({"max_source_rows": 500}, [b"max_source_rows = 500"]), + ({"io_buffer_size": 0}, [b"io_buffer_size = 0"]), + ({"batch_size": 16}, [b"batch_size = 16"]), + ( + { + "target_rows_per_fragment": 100, + "max_source_rows": 500, + "io_buffer_size": 65536, + "batch_size": 16, + }, + [ + b"target_rows_per_fragment = 100", + b"max_source_rows = 500", + b"io_buffer_size = 65536", + b"batch_size = 16", + ], + ), + ({}, []), + ], +) +async def test_remote_optimize_forwards_per_job_compaction_options( + asynchronous, options, sql_options +): + flight = pytest.importorskip("pyarrow.flight") + + class AckServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream( + pa.table({"ok": pa.array([], type=pa.bool_())}) + ) + + server = AckServer() + with _mock_remote_sql_connection(server) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + stats = await table.optimize(compaction_options=options) + else: + table = lancedb.connect(**kwargs).create_table("test", [{"id": 1}]) + stats = table.optimize(compaction_options=options) + assert len(server.tickets) == 1 + assert b"OPTIMIZE" in server.tickets[0] + assert all(option in server.tickets[0] for option in sql_options) + if not sql_options: + assert b"WITH (" not in server.tickets[0] + assert stats.prune.bytes_removed == 0 + + +def test_remote_optimize_does_not_drop_options_after_server_rejection(): + flight = pytest.importorskip("pyarrow.flight") + + class OldServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + raise flight.FlightServerError("Unknown OPTIMIZE option 'max_source_rows'") + + server = OldServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(Exception, match="max_source_rows"): + table.optimize(compaction_options={"max_source_rows": 500}) + assert server.tickets + assert all(b"max_source_rows = 500" in ticket for ticket in server.tickets) + + +def test_remote_optimize_skips_prune_and_index(): + """Regression test: a remote table's `optimize()` used to submit a + compaction job and then raise `NotImplementedError` once it went on to + request pruning, which is not supported remotely. Retrying that failure + resubmitted another compaction job. It should instead succeed, with + zeroed pruning statistics, once compaction is submitted. + + The SQL job submission for a query without parameters (like + `OPTIMIZE ... REWRITE DATA`) goes over plain Flight `do_get`, not + `do_exchange`: the client sends a ticket wrapping the statement and reads + back whatever the server returns as the job's result stream. + """ + flight = pytest.importorskip("pyarrow.flight") + + class AckServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream( + pa.table({"ok": pa.array([], type=pa.bool_())}) + ) + + server = AckServer() + with _mock_remote_table_with_sql(server) as table: + stats = table.optimize() + + assert len(server.tickets) == 1 + assert b"OPTIMIZE" in server.tickets[0] + assert stats.prune.bytes_removed == 0 + assert stats.prune.old_versions_removed == 0 + + +def test_remote_optimize_rejects_unsupported_compaction_options_before_submitting(): + """Regression test: `RemoteTable.optimize()` used to drop + `compaction_options` instead of forwarding it to the Rust layer, so a + non-default value was silently ignored -- the server-side guard against + unsupported options never saw it. It should now reach that guard and + raise before any SQL statement is submitted.""" + from lancedb.table import CompactionOptions + + flight = pytest.importorskip("pyarrow.flight") + + class UnreachableServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream( + pa.table({"ok": pa.array([], type=pa.bool_())}) + ) + + server = UnreachableServer() + options: CompactionOptions = {"max_source_bytes": 1024} + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(NotImplementedError, match="CompactionOptions"): + table.optimize(compaction_options=options) + + assert server.tickets == [] + + +def test_remote_optimize_rejects_explicit_pruning_before_submitting(): + """Regression test: a remote table's `optimize()` used to silently drop + an explicit pruning request (`cleanup_older_than`), returning success + with zero bytes removed even though nothing was pruned. It should now + raise before any SQL statement is submitted, the same way a non-default + `compaction_options` does.""" + from datetime import timedelta + + flight = pytest.importorskip("pyarrow.flight") + + class UnreachableServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream( + pa.table({"ok": pa.array([], type=pa.bool_())}) + ) + + server = UnreachableServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(NotImplementedError, match="pruning"): + table.optimize(cleanup_older_than=timedelta(days=1)) + with pytest.raises(NotImplementedError, match="pruning"): + table.optimize(delete_unverified=True) + + assert server.tickets == [] diff --git a/python/python/tests/test_remote_options.py b/python/python/tests/test_remote_options.py index 0dbc21029..404bfed43 100644 --- a/python/python/tests/test_remote_options.py +++ b/python/python/tests/test_remote_options.py @@ -87,7 +87,7 @@ async def test_remote_create_rejects_write_options(storage_options, empty): kwargs["data"] = [{"value": 1}] async with mock_lancedb_connection_async(handler) as db: with pytest.raises( - NotImplementedError, match="write_options.*LanceDB Distributed" + NotImplementedError, match="write_options.*LanceDB Enterprise" ): await db.create_table("t", storage_options=storage_options, **kwargs) assert requests == [] @@ -110,7 +110,7 @@ def test_sync_remote_create_rejects_write_options(options): request.end_headers() with mock_lancedb_connection(handler) as db: - with pytest.raises(NotImplementedError, match="LanceDB Distributed"): + with pytest.raises(NotImplementedError, match="LanceDB Enterprise"): db.create_table("t", [{"value": 1}], **options) assert requests == [] @@ -131,11 +131,11 @@ async def test_remote_open_rejects_local_options(options, asynchronous): if asynchronous: async with mock_lancedb_connection_async(handler) as db: - with pytest.raises(NotImplementedError, match="LanceDB Distributed"): + with pytest.raises(NotImplementedError, match="LanceDB Enterprise"): await db.open_table("t", **options) else: with mock_lancedb_connection(handler) as db: - with pytest.raises(NotImplementedError, match="LanceDB Distributed"): + with pytest.raises(NotImplementedError, match="LanceDB Enterprise"): db.open_table("t", **options) assert requests == [] @@ -151,6 +151,6 @@ async def test_remote_open_rejects_location(): request.wfile.write(b'{"version": 1, "schema": {"fields": []}}') async with mock_lancedb_connection_async(handler) as db: - with pytest.raises(NotImplementedError, match="location.*LanceDB Distributed"): + with pytest.raises(NotImplementedError, match="location.*LanceDB Enterprise"): await db.open_table("t", location="/tmp/zzz") assert requests == [] diff --git a/python/python/tests/test_rerankers.py b/python/python/tests/test_rerankers.py index 78b64613e..76088946a 100644 --- a/python/python/tests/test_rerankers.py +++ b/python/python/tests/test_rerankers.py @@ -28,6 +28,7 @@ from lancedb.rerankers import ( WatsonxReranker, ) from lancedb.table import LanceTable +from lancedb.rerankers.base import Reranker def get_test_table(tmp_path): @@ -126,7 +127,7 @@ def _run_test_reranker( if deterministic: assert result1 == result2 - query_vector = table.to_pandas()["vector"][0] + query_vector = table.to_arrow()["vector"][0].as_py() result = ( table.search(query_type="hybrid", vector_column_name="vector") .vector(query_vector) @@ -249,7 +250,7 @@ def _run_test_hybrid_reranker(reranker, tmp_path): assert result1 == result3 # 2 & 3 should be the same as they use score as score query = "Our father who art in heaven" - query_vector = table.to_pandas()["vector"][0] + query_vector = table.to_arrow()["vector"][0].as_py() result = ( table.search(query_type="hybrid", vector_column_name="vector") .vector(query_vector) @@ -358,6 +359,19 @@ def test_mrr_reranker(tmp_path): assert len(result_deduped) == len(result) +@pytest.mark.parametrize("deduplicate", [False, True]) +def test_base_reranker_multivector_empty_input(deduplicate): + class VectorReranker(Reranker): + def rerank_hybrid(self, query, vector_results, fts_results): + raise AssertionError("should not rerank") + + def rerank_vector(self, query, vector_results): + raise AssertionError("should not rerank") + + with pytest.raises(ValueError, match="vector_results must not be empty"): + VectorReranker().rerank_multivector([], None, deduplicate=deduplicate) + + def test_mrr_reranker_empty_input(): reranker = MRRReranker() with pytest.raises(ValueError, match="must not be empty"): @@ -836,6 +850,56 @@ def test_empty_hybrid_result_reranker(): assert "_rowid" in result.column_names +@pytest.mark.parametrize("reranker_cls", [LinearCombinationReranker, RRFReranker]) +@pytest.mark.parametrize("return_score", ["relevance", "all"]) +def test_empty_hybrid_result_keeps_reranker_columns( + tmp_path, reranker_cls, return_score +): + # A filter that matches nothing must not change which columns come back. + db = lancedb.connect(tmp_path) + table = db.create_table( + "t", + pa.table( + { + "text": ["red fox", "blue fox"], + "vector": pa.array([[1.0, 2.0], [3.0, 4.0]], pa.list_(pa.float32(), 2)), + } + ), + ) + table.create_fts_index("text") + reranker = reranker_cls(return_score=return_score) + + def columns(where): + query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("fox") + query = query.where(where, prefilter=True).rerank(reranker) + return query.to_arrow().column_names + + assert columns("text = 'none'") == columns("text != 'none'") + + +def test_empty_hybrid_result_skips_keep_relevance_score_override(tmp_path): + # An override written for non-empty results must not run on the empty path. + class FirstRowReranker(LinearCombinationReranker): + def _keep_relevance_score(self, combined_results): + combined_results["_relevance_score"][0] + return super()._keep_relevance_score(combined_results) + + db = lancedb.connect(tmp_path) + table = db.create_table( + "t", + pa.table( + { + "text": ["red fox", "blue fox"], + "vector": pa.array([[1.0, 2.0], [3.0, 4.0]], pa.list_(pa.float32(), 2)), + } + ), + ) + table.create_fts_index("text") + query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("fox") + query = query.where("text = 'none'", prefilter=True).rerank(FirstRowReranker()) + assert query.to_arrow().num_rows == 0 + + @pytest.mark.parametrize("norm", ["score", "rank"]) def test_hybrid_return_all_restores_original_scores(norm): from lancedb.query import LanceHybridQueryBuilder @@ -1100,6 +1164,52 @@ def test_linear_combination_missing_fts_is_penalised(): ) +@pytest.mark.parametrize("empty_side", ["vector", "fts"]) +def test_linear_combination_empty_side_scores_are_null(empty_side): + """With return_score="all", the missing side's score column is null, not NaN.""" + from lancedb.query import LanceHybridQueryBuilder + + vector_results = pa.table( + { + "_rowid": pa.array([1, 2], pa.uint64()), + "_distance": pa.array([0.1, 0.2], pa.float32()), + } + ) + fts_results = pa.table( + { + "_rowid": pa.array([1, 2], pa.uint64()), + "_score": pa.array([5.0, 4.0], pa.float32()), + } + ) + if empty_side == "vector": + expected_present = fts_results["_score"].to_pylist() + vector_results = vector_results.slice(0, 0) + missing = "_distance" + present = "_score" + else: + expected_present = vector_results["_distance"].to_pylist() + fts_results = fts_results.slice(0, 0) + missing = "_score" + present = "_distance" + + result = LanceHybridQueryBuilder._combine_hybrid_results( + fts_results=fts_results, + vector_results=vector_results, + norm="score", + fts_query="query", + reranker=LinearCombinationReranker(return_score="all"), + limit=10, + with_row_ids=True, + ) + + assert result[missing].type == pa.float32() + assert result[missing].null_count == len(result) == 2 + assert result[present].to_pylist() == expected_present + assert result["_relevance_score"].to_pylist() == sorted( + result["_relevance_score"].to_pylist(), reverse=True + ) + + @pytest.mark.skipif( os.environ.get("WATSONX_API_KEY") is None or ( diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py index 539b88647..0ed382d93 100644 --- a/python/python/tests/test_sql.py +++ b/python/python/tests/test_sql.py @@ -281,3 +281,63 @@ def test_parameters_reach_the_server_as_the_values_that_were_sent(): received = echoed.column("vector").combine_chunks().flatten().to_numpy() assert received.view(np.uint32).tolist() == vector.view(np.uint32).tolist() assert echoed.column("k").to_pylist() == [10] + + +@pytest.mark.parametrize("job_id", [None, "sql-job-1"]) +def test_sql_input_error_metadata_crosses_native_boundary(job_id): + flight = pytest.importorskip("pyarrow.flight") + from lancedb.exceptions import JobFailedError, ColumnNotFoundError + from lancedb.remote.errors import SqlColumnNotFoundError + + request_ids = [] + + class Metadata(flight.ServerMiddleware): + def sending_headers(self): + headers = { + "x-lancedb-error-code": "column_not_found", + "x-job-request-id": "worker-request", + } + if job_id is not None: + headers["x-lancedb-sql-job-id"] = job_id + return headers + + class Factory(flight.ServerMiddlewareFactory): + def start_call(self, info, headers): + request_ids.append(headers["x-request-id"][0]) + return Metadata() + + class RejectingServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0", middleware={"metadata": Factory()}) + + def do_get(self, context, ticket): + context.add_trailer("x-lancedb-error-code", "column_not_found") + context.add_trailer("x-job-request-id", "worker-request") + if job_id is not None: + context.add_trailer("x-lancedb-sql-job-id", job_id) + raise pa.ArrowInvalid("No column 'missing' in table events") + + with RejectingServer() as server: + db = lancedb.connect( + "db://analytics", + api_key="test-key", + host_override="http://localhost:10024", + sql_host_override=f"grpc://127.0.0.1:{server.port}", + ) + expected = JobFailedError if job_id is not None else SqlColumnNotFoundError + with pytest.raises(expected) as exc_info: + db.execute_query("SELECT missing FROM events").read_all() + error = exc_info.value + if job_id is not None: + assert error.job_id == job_id + assert error.request_id == request_ids[-1] + assert error.job_request_id == "worker-request" + error = error.__cause__ + assert isinstance(error, SqlColumnNotFoundError) + assert isinstance(error, ColumnNotFoundError) + assert error.request_id == request_ids[-1] + assert error.job_id == job_id + assert error.job_request_id == "worker-request" + assert error.grpc_code == 3 + assert str(error).startswith("No column 'missing' in table events") + assert not str(error).startswith("SQL error") diff --git a/python/python/tests/test_storage_integration.py b/python/python/tests/test_storage_integration.py new file mode 100644 index 000000000..ff7995ab3 --- /dev/null +++ b/python/python/tests/test_storage_integration.py @@ -0,0 +1,529 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import contextlib +import json +from pathlib import Path + +import pytest +import pyarrow as pa +import pyarrow.flight as flight + +import lancedb +from lancedb.authz import Object, Privilege +from lancedb.db import AsyncConnection, DBConnection +from lancedb.catalog import Catalog, AsyncCatalog +from lancedb.storage_integration import SecretReference, StorageIntegrationInfo + + +INFO = json.loads( + ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/storage_integration.json" + ).read_text() +) +NAME = "raw" +ROLE = "arn:aws:iam::123456789012:role/access" + + +@contextlib.contextmanager +def remote_server(text_type=pa.string()): + calls = [] + info = dict(INFO) + + class Server(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + + def do_get(self, context, ticket): + command = ticket.ticket + calls.append(command) + if b"SHOW STORAGE INTEGRATIONS" in command: + result = pa.table({"name": pa.array(["zeta", NAME], type=text_type)}) + elif b"DROP STORAGE INTEGRATION" in command: + result = pa.table({"dropped": [True]}) + else: + if b"STORAGE_PROVIDER = 'HUGGINGFACE'" in command: + info.update( + storage_provider="HUGGINGFACE", + storage_prefix="hf://datasets/acme/private/raw/", + aws_role_arn=None, + aws_region=None, + aws_account_id="", + aws_iam_principal_arn="", + trust_policy=None, + permissions_policy=None, + configuration_instructions=( + "Grant the referenced identity access to the prefix." + ), + huggingface_token_secret=( + dict( + database="shared", + namespace_path=["credentials"], + name="hf_token", + ) + if b"HUGGINGFACE_TOKEN_SECRET" in command + else None + ), + ) + if b"GCP_CREDENTIALS_JSON_SECRET" in command: + info.update( + storage_provider="GCP", + storage_prefix="gs://customer-data/raw/", + aws_role_arn=None, + aws_region=None, + aws_account_id="", + aws_iam_principal_arn="", + trust_policy=None, + permissions_policy=None, + configuration_instructions=( + "Grant the referenced identity access to the prefix." + ), + gcp_credentials_json_secret=dict( + database="shared", + namespace_path=["credentials"], + name="gcp", + ), + ) + if b"STORAGE_AZURE_STORAGE_ACCOUNT" in command: + info.update( + storage_provider="AZURE", + storage_prefix="az://customer-data@customeraccount.blob.core.windows.net/raw/", + azure_storage_account="customeraccount", + aws_role_arn=None, + trust_policy=None, + permissions_policy=None, + ) + for field, name in ( + ("azure_tenant_id_secret", "tenant"), + ("azure_client_id_secret", "client"), + ("azure_client_secret_secret", "credential"), + ): + info[field] = dict( + database="shared", namespace_path=["credentials"], name=name + ) + if b"STORAGE_AWS_ACCESS_KEY_ID_SECRET" in command: + info["aws_role_arn"] = None + info["trust_policy"] = None + info["aws_access_key_id_secret"] = { + "database": "shared", + "namespace_path": ["credentials"], + "name": "access_key", + } + info["aws_secret_access_key_secret"] = { + "database": "shared", + "namespace_path": ["credentials"], + "name": "secret_key", + } + row = dict(info) + for field in [ + "namespace_path", + "trust_policy", + "permissions_policy", + "aws_access_key_id_secret", + "aws_secret_access_key_secret", + "azure_tenant_id_secret", + "azure_client_id_secret", + "azure_client_secret_secret", + "gcp_credentials_json_secret", + "huggingface_token_secret", + ]: + if field in row and row[field] is not None: + row[field] = json.dumps(row[field]) + row.setdefault("aws_access_key_id_secret", None) + row.setdefault("aws_secret_access_key_secret", None) + result = pa.table( + { + field: pa.array( + [value], + type=( + pa.bool_() + if field == "access_verified" + else pa.int64() + if field == "created_at_millis" + else text_type + ), + ) + for field, value in row.items() + } + ) + return flight.RecordBatchStream(result) + + with Server() as server: + yield f"grpc://127.0.0.1:{server.port}", calls + + +def connect(host): + return lancedb.connect( + "db://default", + api_key="fake", + sql_host_override=host, + host_override="http://127.0.0.1:1", + ) + + +def test_storage_integration_methods_belong_to_databases(): + assert hasattr(DBConnection, "create_storage_integration") + assert hasattr(AsyncConnection, "create_storage_integration") + assert not hasattr(Catalog, "create_storage_integration") + assert not hasattr(AsyncCatalog, "create_storage_integration") + + +@pytest.mark.parametrize( + "text_type", [pa.string(), pa.large_string(), pa.string_view()] +) +def test_sync_storage_integration_lifecycle_and_aws_information(text_type): + with remote_server(text_type) as (host, calls): + db = connect(host) + info = db.create_storage_integration( + NAME, INFO["storage_prefix"], aws_role_arn=ROLE + ) + assert isinstance(info, lancedb.StorageIntegrationInfo) + assert info.aws_account_id == "001122334455" + assert not info.access_verified + assert ( + info.trust_policy["Statement"][0]["Condition"]["StringEquals"][ + "sts:ExternalId" + ] + == info.aws_external_id + ) + assert db.describe_storage_integration(NAME) == info + listing = db.list_storage_integrations(page_limit=1) + assert len(calls) == 2 + assert list(listing) == ["raw", "zeta"] + assert db.drop_storage_integration(NAME) is None + assert b'CREATE STORAGE INTEGRATION "raw"' in calls[0] + assert b"STORAGE_AWS_ROLE_ARN = '" + ROLE.encode() + b"'" in calls[0] + assert b'DROP STORAGE INTEGRATION "raw"' in calls[-1] + + +@pytest.mark.asyncio +async def test_async_storage_integration_lifecycle(): + with remote_server() as (host, _calls): + db = await lancedb.connect_async( + "db://default", + api_key="fake", + sql_host_override=host, + host_override="http://127.0.0.1:1", + ) + info = await db.create_storage_integration( + NAME, INFO["storage_prefix"], aws_role_arn=ROLE + ) + assert await db.describe_storage_integration(NAME) == info + assert [name async for name in db.list_storage_integrations()] == [ + "raw", + "zeta", + ] + await db.drop_storage_integration(NAME) + with pytest.raises(ValueError): + await db.describe_storage_integration("a//b") + + +def test_integration_authorization_object_and_creation_privilege(): + value = Object.storage_integration(database="default", name=NAME) + assert str(value) == "storage_integration:default:public$raw" + assert Privilege.CREATE_STORAGE_INTEGRATION.value == "CREATE_STORAGE_INTEGRATION" + + +@pytest.mark.parametrize( + "text_type", [pa.string(), pa.large_string(), pa.string_view()] +) +def test_static_credentials_use_explicit_cross_database_secret_references(text_type): + with remote_server(text_type) as (host, calls): + db = connect(host) + info = db.create_storage_integration( + "raw", + INFO["storage_prefix"], + aws_access_key_id_secret=SecretReference( + "access_key", database="shared", namespace_path=("credentials",) + ), + aws_secret_access_key_secret=SecretReference( + "secret_key", database="shared", namespace_path=("credentials",) + ), + ) + assert info.aws_role_arn is None + assert db.describe_storage_integration("raw") == info + assert info.aws_access_key_id_secret.database == "shared" + assert b"STORAGE_AWS_ROLE_ARN" not in calls[0] + assert ( + b'STORAGE_AWS_ACCESS_KEY_ID_SECRET = "shared"."credentials"."access_key"' + in calls[0] + ) + with pytest.raises(ValueError): + db.create_storage_integration( + "bad", + INFO["storage_prefix"], + aws_role_arn=ROLE, + aws_access_key_id_secret="key", + ) + assert len(calls) == 2 + + +def test_metadata_defaults_an_omitted_role_to_none(): + data = dict(INFO) + data.pop("aws_role_arn") + assert StorageIntegrationInfo(**data).aws_role_arn is None + + +def test_namespace_connections_keep_existing_apis_available(tmp_path): + db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) + with pytest.raises(NotImplementedError): + db.create_storage_integration("raw", "s3://customer/raw/", aws_role_arn=ROLE) + + +@pytest.mark.parametrize( + "text_type", [pa.string(), pa.large_string(), pa.string_view()] +) +def test_azure_lifecycle_uses_three_qualified_secret_references(text_type): + with remote_server(text_type) as (host, calls): + db = connect(host) + refs = [ + SecretReference(name, database="shared", namespace_path=("credentials",)) + for name in ("tenant", "client", "credential") + ] + info = db.create_storage_integration( + "blobs", + "az://customer-data/raw/", + storage_provider="AZURE", + azure_storage_account="customeraccount", + azure_tenant_id_secret=refs[0], + azure_client_id_secret=refs[1], + azure_client_secret_secret=refs[2], + ) + assert info.storage_provider == "AZURE" + assert info.azure_storage_account == "customeraccount" + assert info.azure_tenant_id_secret.name == "tenant" + assert info.azure_client_id_secret.database == "shared" + assert info.azure_client_secret_secret.name == "credential" + assert info.trust_policy is None + assert info.permissions_policy is None + assert not info.access_verified + assert db.describe_storage_integration("blobs") == info + assert list(db.list_storage_integrations()) == ["raw", "zeta"] + db.drop_storage_integration("blobs") + sql = calls[0] + assert b"STORAGE_PROVIDER = 'AZURE'" in sql + assert b"STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount'" in sql + assert ( + b'STORAGE_AZURE_CLIENT_SECRET_SECRET = "shared"."credentials"."credential"' + in sql + ) + assert b"STORAGE_AWS" not in sql + + +@pytest.mark.asyncio +async def test_async_azure_requires_account_and_all_three_secret_references(): + with remote_server() as (host, calls): + db = await lancedb.connect_async( + "db://default", + api_key="fake", + sql_host_override=host, + host_override="http://127.0.0.1:1", + ) + config = dict( + storage_provider="AZURE", + azure_storage_account="customeraccount", + azure_tenant_id_secret="tenant", + azure_client_id_secret="client", + azure_client_secret_secret="credential", + ) + for missing in ( + "azure_storage_account", + "azure_tenant_id_secret", + "azure_client_id_secret", + "azure_client_secret_secret", + ): + partial = dict(config) + partial.pop(missing) + with pytest.raises(ValueError): + await db.create_storage_integration( + "blobs", "az://customer-data/raw/", **partial + ) + with pytest.raises(ValueError): + await db.create_storage_integration( + "blobs", "az://customer-data/raw/", aws_role_arn=ROLE, **config + ) + assert calls == [] + info = await db.create_storage_integration( + "blobs", "az://customer-data/raw/", **config + ) + assert info.storage_provider == "AZURE" + assert b'STORAGE_AZURE_TENANT_ID_SECRET = "public"."tenant"' in calls[0] + + +@pytest.mark.parametrize( + "text_type", [pa.string(), pa.large_string(), pa.string_view()] +) +def test_gcp_lifecycle_uses_one_qualified_json_secret(text_type): + with remote_server(text_type) as (host, calls): + db = connect(host) + info = db.create_storage_integration( + "gcs", + "gs://customer-data/raw/", + storage_provider="GCP", + gcp_credentials_json_secret=SecretReference( + "gcp", database="shared", namespace_path=("credentials",) + ), + ) + assert info.storage_provider == "GCP" + assert info.gcp_credentials_json_secret.name == "gcp" + assert info.gcp_credentials_json_secret.database == "shared" + assert info.aws_role_arn is None + assert info.azure_storage_account is None + assert info.aws_iam_principal_arn == "" + assert info.trust_policy is None + assert not info.access_verified + assert db.describe_storage_integration("gcs") == info + assert list(db.list_storage_integrations()) == ["raw", "zeta"] + db.drop_storage_integration("gcs") + assert b"STORAGE_PROVIDER = 'GCP'" in calls[0] + assert b'GCP_CREDENTIALS_JSON_SECRET = "shared"."credentials"."gcp"' in calls[0] + assert b"STORAGE_AWS" not in calls[0] + assert b"STORAGE_AZURE" not in calls[0] + + +@pytest.mark.asyncio +async def test_async_gcp_requires_one_secret_and_rejects_other_cloud_options(): + with remote_server() as (host, calls): + db = await lancedb.connect_async( + "db://default", + api_key="fake", + sql_host_override=host, + host_override="http://127.0.0.1:1", + ) + for invalid in ( + {}, + {"gcp_credentials_json_secret": "gcp", "aws_role_arn": ROLE}, + {"gcp_credentials_json_secret": "gcp", "azure_storage_account": "account"}, + ): + with pytest.raises(ValueError): + await db.create_storage_integration( + "gcs", "gs://customer-data/raw/", storage_provider="GCP", **invalid + ) + with pytest.raises(ValueError): + await db.create_storage_integration( + "gcs", + "gs://customer-data/raw/", + aws_role_arn=ROLE, + gcp_credentials_json_secret="gcp", + ) + assert calls == [] + info = await db.create_storage_integration( + "gcs", + "gs://customer-data/raw/", + storage_provider="GCP", + gcp_credentials_json_secret="gcp", + ) + assert info.storage_provider == "GCP" + assert b'GCP_CREDENTIALS_JSON_SECRET = "public"."gcp"' in calls[0] + + +@pytest.mark.parametrize( + "text_type", [pa.string(), pa.large_string(), pa.string_view()] +) +def test_huggingface_lifecycle_uses_one_qualified_token_secret(text_type): + with remote_server(text_type) as (host, calls): + db = connect(host) + info = db.create_storage_integration( + "hub", + "hf://datasets/acme/private/raw/", + storage_provider="HUGGINGFACE", + huggingface_token_secret=SecretReference( + "hf_token", database="shared", namespace_path=("credentials",) + ), + ) + assert info.storage_provider == "HUGGINGFACE" + assert info.huggingface_token_secret.name == "hf_token" + assert info.huggingface_token_secret.database == "shared" + assert info.aws_role_arn is None + assert info.azure_storage_account is None + assert info.aws_iam_principal_arn == "" + assert info.trust_policy is None + assert not info.access_verified + assert db.describe_storage_integration("hub") == info + assert list(db.list_storage_integrations()) == ["raw", "zeta"] + db.drop_storage_integration("hub") + assert b"STORAGE_PROVIDER = 'HUGGINGFACE'" in calls[0] + assert ( + b'HUGGINGFACE_TOKEN_SECRET = "shared"."credentials"."hf_token"' in calls[0] + ) + assert b"STORAGE_AWS" not in calls[0] + assert b"STORAGE_AZURE" not in calls[0] + + +@pytest.mark.asyncio +async def test_async_huggingface_rejects_other_cloud_options(): + with remote_server() as (host, calls): + db = await lancedb.connect_async( + "db://default", + api_key="fake", + sql_host_override=host, + host_override="http://127.0.0.1:1", + ) + for invalid in ( + {"huggingface_token_secret": "hf_token", "aws_role_arn": ROLE}, + { + "huggingface_token_secret": "hf_token", + "azure_storage_account": "account", + }, + ): + with pytest.raises(ValueError): + await db.create_storage_integration( + "hub", + "hf://datasets/acme/private/raw/", + storage_provider="HUGGINGFACE", + **invalid, + ) + with pytest.raises(ValueError): + await db.create_storage_integration( + "hub", + "hf://datasets/acme/private/raw/", + aws_role_arn=ROLE, + huggingface_token_secret="hf_token", + ) + assert calls == [] + info = await db.create_storage_integration( + "hub", + "hf://datasets/acme/private/raw/", + storage_provider="HUGGINGFACE", + huggingface_token_secret="hf_token", + ) + assert info.storage_provider == "HUGGINGFACE" + assert b'HUGGINGFACE_TOKEN_SECRET = "public"."hf_token"' in calls[0] + + +@pytest.mark.parametrize( + "text_type", [pa.string(), pa.large_string(), pa.string_view()] +) +def test_anonymous_huggingface_lifecycle_omits_token_secret(text_type): + with remote_server(text_type) as (host, calls): + db = connect(host) + info = db.create_storage_integration( + "public_hub", + "hf://datasets/acme/public/raw/", + storage_provider="HUGGINGFACE", + ) + assert info.storage_provider == "HUGGINGFACE" + assert info.huggingface_token_secret is None + assert db.describe_storage_integration("public_hub") == info + assert list(db.list_storage_integrations()) == ["raw", "zeta"] + db.drop_storage_integration("public_hub") + assert b"HUGGINGFACE_TOKEN_SECRET" not in calls[0] + + +@pytest.mark.asyncio +async def test_async_huggingface_allows_anonymous_access(): + with remote_server() as (host, calls): + db = await lancedb.connect_async( + "db://default", + api_key="fake", + sql_host_override=host, + host_override="http://127.0.0.1:1", + ) + info = await db.create_storage_integration( + "public_hub", + "hf://datasets/acme/public/raw/", + storage_provider="HUGGINGFACE", + ) + assert info.huggingface_token_secret is None + assert b"HUGGINGFACE_TOKEN_SECRET" not in calls[0] diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index f4efb1787..2a502fe62 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -10,10 +10,12 @@ import sys import threading import warnings import weakref +from collections import UserDict from concurrent.futures import ThreadPoolExecutor from datetime import date, datetime, timedelta from decimal import Decimal, localcontext from time import sleep +from types import MappingProxyType from typing import Any, List from unittest.mock import MagicMock, patch @@ -300,6 +302,7 @@ def test_table_to_pandas_invalid_blob_mode_non_blob_table(tmp_db: DBConnection): @pytest.mark.parametrize("blob_mode", ["lazy", "bytes", "descriptions"]) def test_table_to_pandas_blob_modes(tmp_db: DBConnection, blob_mode): + pytest.importorskip("pandas") pytest.importorskip("lance") table = tmp_db.create_table( f"test_to_pandas_blob_{blob_mode}", @@ -322,6 +325,7 @@ def test_table_to_pandas_blob_modes(tmp_db: DBConnection, blob_mode): @pytest.mark.parametrize("blob_schema", ["v1", "v2"]) def test_table_to_pandas_blob_bytes(tmp_db: DBConnection, blob_schema): + pytest.importorskip("pandas") pytest.importorskip("lance") table = _blob_table(tmp_db, f"test_to_pandas_blob_{blob_schema}_bytes", blob_schema) @@ -347,6 +351,7 @@ def test_table_to_pandas_kwargs(tmp_db: DBConnection): async def test_async_table_to_pandas_blob_bytes( tmp_db_async: AsyncConnection, blob_schema ): + pytest.importorskip("pandas") pytest.importorskip("lance") table = await _blob_table_async( tmp_db_async, f"test_async_to_pandas_blob_{blob_schema}_bytes", blob_schema @@ -930,8 +935,8 @@ def test_add_nullability(mem_db: DBConnection): assert table.to_arrow() == expected -def test_add_pydantic_model(mem_db: DBConnection): - pytest.importorskip("pandas") +@pytest.fixture +def pydantic_model_table(mem_db: DBConnection): # https://github.com/lancedb/lancedb/issues/562 class Metadata(BaseModel): @@ -949,9 +954,6 @@ def test_add_pydantic_model(mem_db: DBConnection): payload: Document tbl = mem_db.create_table("mytable", schema=LanceSchema, mode="overwrite") - assert tbl.schema == LanceSchema.to_arrow_schema() - - # add works expected = LanceSchema( id="id", vector=[0.0, 0.0], @@ -961,11 +963,21 @@ def test_add_pydantic_model(mem_db: DBConnection): ), ) add_res = tbl.add([expected]) + return tbl, LanceSchema, expected, add_res + + +def test_add_pydantic_model(pydantic_model_table): + tbl, LanceSchema, expected, add_res = pydantic_model_table + assert tbl.schema == LanceSchema.to_arrow_schema() assert add_res.version == 2 result = tbl.search([0.0, 0.0]).limit(1).to_pydantic(LanceSchema)[0] assert result == expected + +def test_add_pydantic_model_pandas(pydantic_model_table): + pytest.importorskip("pandas") + tbl, _, _, _ = pydantic_model_table flattened = tbl.search([0.0, 0.0]).limit(1).to_pandas(flatten=1) assert len(flattened.columns) == 6 # _distance is automatically added @@ -1933,6 +1945,66 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): ) +@patch("lancedb.table.AsyncTable.get_table_overrides") +def test_get_table_overrides_method(mock_get_table_overrides, mem_db: DBConnection): + expected = {"job_types": {"cleanup": {"enabled": False}}} + mock_get_table_overrides.return_value = expected + table = mem_db.create_table("test", data=[{"id": 1}]) + + assert table.get_table_overrides() == expected + mock_get_table_overrides.assert_called_once_with() + + +@patch("lancedb.table.AsyncTable.update_table_overrides") +def test_update_table_overrides_method( + mock_update_table_overrides, mem_db: DBConnection +): + overrides = { + "job_types": { + "cleanup": {"enabled": False}, + "index": { + "scalar": { + "reindex": { + "row_threshold": 1000, + "ttl_millis": 300000, + } + } + }, + } + } + mock_update_table_overrides.return_value = overrides + table = mem_db.create_table("test", data=[{"id": 1}]) + + assert table.update_table_overrides(**overrides) == overrides + mock_update_table_overrides.assert_called_once_with(**overrides) + + +@patch("lancedb.table.AsyncTable.reset_table_overrides") +def test_reset_table_overrides_method(mock_reset_table_overrides, mem_db: DBConnection): + expected = {} + mock_reset_table_overrides.return_value = expected + table = mem_db.create_table("test", data=[{"id": 1}]) + + assert table.reset_table_overrides() == expected + mock_reset_table_overrides.assert_called_once_with() + + +@pytest.mark.asyncio +async def test_async_update_table_overrides_encodes_json(): + class MockInner: + async def update_table_overrides(self, encoded_overrides): + assert json.loads(encoded_overrides) == { + "job_types": {"cleanup": {"enabled": False}} + } + return json.dumps({"job_types": {"cleanup": {"enabled": False}}}) + + table = lancedb.table.AsyncTable(MockInner()) + + assert await table.update_table_overrides( + job_types={"cleanup": {"enabled": False}} + ) == {"job_types": {"cleanup": {"enabled": False}}} + + @pytest.mark.parametrize("api", ["legacy", "unified"]) @pytest.mark.parametrize("cuda_failure", ["unavailable", "init_error"]) def test_create_index_cuda_failure_suggests_cpu( @@ -2774,6 +2846,260 @@ def test_update(mem_db: DBConnection): assert np.allclose(v, np.array([[1.2, 1.9], [1.1, 1.1]])) +@pytest.mark.asyncio +@pytest.mark.parametrize("async_api", [False, True]) +@pytest.mark.parametrize("use_sql", [False, True]) +@pytest.mark.parametrize("where", [None, "id = 1", col("id") == 1]) +@pytest.mark.parametrize("source_target", ["text", "`text`"]) +async def test_update_embedding_source_requires_vector( + tmp_path, async_api, use_sql, where, source_target +): + func = MockTextEmbeddingFunction.create() + + class Doc(LanceModel): + id: int + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + data = [{"id": 1, "text": "hello world"}, {"id": 2, "text": "goodbye world"}] + if async_api: + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("docs", data, schema=Doc) + before = await table.to_arrow() + version = await table.version() + else: + db = lancedb.connect(tmp_path) + table = db.create_table("docs", data, schema=Doc) + before = table.to_arrow() + version = table.version + + # Rejection must happen before any rows or the table version change. + updates = {source_target: "text || ' updated'" if use_sql else "updated text"} + with pytest.raises( + ValueError, match="source column 'text'.*vector column 'vector'" + ): + if async_api: + if use_sql: + await table.update(where=where, updates_sql=updates) + else: + await table.update(updates, where=where) + elif use_sql: + table.update(where=where, values_sql=updates) + else: + table.update(where=where, values=updates) + + if async_api: + assert (await table.to_arrow()).equals(before) + assert await table.version() == version + else: + assert table.to_arrow().equals(before) + assert table.version == version + + +@pytest.mark.asyncio +@pytest.mark.parametrize("async_api", [False, True]) +@pytest.mark.parametrize("use_sql", [False, True]) +@pytest.mark.parametrize( + "source_target,vector_target,other_vector_target", + [ + ("text", "vector", "other_vector"), + ("`text`", "vector", "`other_vector`"), + ("text", "`vector`", "other_vector"), + ("`text`", "`vector`", "`other_vector`"), + ], +) +async def test_update_embedding_source_with_multiple_vectors( + tmp_path, + monkeypatch, + async_api, + use_sql, + source_target, + vector_target, + other_vector_target, +): + func = MockTextEmbeddingFunction.create() + + class Doc(LanceModel): + id: int + text: str + vector: Vector(func.ndims()) + other_vector: Vector(func.ndims()) + + configs = [ + EmbeddingFunctionConfig( + source_column="text", vector_column=column, function=func + ) + for column in ["vector", "other_vector"] + ] + data = [{"id": 1, "text": "hello world"}, {"id": 2, "text": "goodbye world"}] + if async_api: + db = await lancedb.connect_async(tmp_path) + table = await db.create_table( + "docs", data, schema=Doc, embedding_functions=configs + ) + else: + db = lancedb.connect(tmp_path) + table = db.create_table("docs", data, schema=Doc, embedding_functions=configs) + + async def update(values): + if async_api: + if use_sql: + return await table.update(updates_sql=values, where=col("id") == 1) + return await table.update(values, where=col("id") == 1) + if use_sql: + return table.update(values_sql=values, where=col("id") == 1) + return table.update(values=values, where=col("id") == 1) + + vector = func.compute_source_embeddings(["updated text"])[0] + updates = {source_target: "updated text", vector_target: vector} + if use_sql: + updates = { + key: table_module.value_to_sql(value) for key, value in updates.items() + } + + # Checking column dependencies must not require loading an embedding model. + monkeypatch.delitem(EmbeddingFunctionRegistry.get_instance()._functions, "test") + with pytest.raises(ValueError, match="vector column 'other_vector'"): + await update(updates) + + updates[other_vector_target] = updates[vector_target] + result = await update(updates) + assert result.rows_updated == 1 + actual = await table.to_arrow() if async_api else table.to_arrow() + rows = actual.sort_by("id").to_pylist() + assert rows[0]["text"] == "updated text" + assert np.allclose(rows[0]["vector"], vector) + assert np.allclose(rows[0]["other_vector"], vector) + assert rows[1]["text"] == "goodbye world" + + # Vector-only and unrelated updates are still allowed on embedding tables. + assert (await update({vector_target: updates[vector_target]})).rows_updated == 1 + assert (await update({"id": "3" if use_sql else 3})).rows_updated == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("async_api", [False, True]) +@pytest.mark.parametrize("source_target", ["text", "`text`"]) +async def test_update_embedding_source_requires_native_vector_metadata( + tmp_path, async_api, source_target +): + vector_type = pa.list_(pa.float32(), 2) + column_definitions = [ + {"kind": "Physical"}, + {"kind": "Physical"}, + { + "kind": { + "Embedding": { + "source_column": "text", + "dest_column": "vector", + "embedding_name": "native-explicit", + } + } + }, + { + "kind": { + "Embedding": { + "source_column": "text", + "dest_column": None, + "embedding_name": "native-default", + } + } + }, + ] + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("text", pa.string()), + pa.field("vector", vector_type), + pa.field("text_embedding", vector_type), + ], + metadata={ + b"lancedb::column_definitions": json.dumps(column_definitions).encode() + }, + ) + data = pa.Table.from_pylist( + [ + { + "id": 1, + "text": "hello world", + "vector": [1.0, 0.0], + "text_embedding": [0.0, 1.0], + }, + { + "id": 2, + "text": "goodbye world", + "vector": [0.5, 0.5], + "text_embedding": [0.25, 0.75], + }, + ], + schema=schema, + ) + + if async_api: + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("docs", data) + table_schema = await table.schema() + before = await table.to_arrow() + version = await table.version() + else: + db = lancedb.connect(tmp_path) + table = db.create_table("docs", data) + table_schema = table.schema + before = table.to_arrow() + version = table.version + + metadata = table_schema.metadata or {} + assert b"lancedb::column_definitions" in metadata + assert b"embedding_functions" not in metadata + + async def update(values): + if async_api: + return await table.update(values, where="id = 1") + return table.update(values=values, where="id = 1") + + with pytest.raises( + ValueError, match="source column 'text'.*vector column 'vector'" + ): + await update({source_target: "updated text"}) + + if async_api: + assert (await table.to_arrow()).equals(before) + assert await table.version() == version + else: + assert table.to_arrow().equals(before) + assert table.version == version + + with pytest.raises( + ValueError, match="source column 'text'.*vector column 'text_embedding'" + ): + await update({source_target: "updated text", "vector": [2.0, 3.0]}) + + if async_api: + assert (await table.to_arrow()).equals(before) + assert await table.version() == version + else: + assert table.to_arrow().equals(before) + assert table.version == version + + result = await update( + { + source_target: "updated text", + "vector": [2.0, 3.0], + "text_embedding": [4.0, 5.0], + } + ) + assert result.rows_updated == 1 + assert (await update({"vector": [6.0, 7.0]})).rows_updated == 1 + assert (await update({"id": 99})).rows_updated == 1 + + actual = await table.to_arrow() if async_api else table.to_arrow() + rows = {row["id"]: row for row in actual.to_pylist()} + assert rows[99]["text"] == "updated text" + assert np.allclose(rows[99]["vector"], [6.0, 7.0]) + assert np.allclose(rows[99]["text_embedding"], [4.0, 5.0]) + assert rows[2]["text"] == "goodbye world" + + def test_update_expr_filter_literals(mem_db: DBConnection): values = ["5", "4.66e-84", "it's"] table = mem_db.create_table( @@ -3193,6 +3519,40 @@ def test_merge_insert(mem_db: DBConnection): ) +def test_merge_insert_with_schema_metadata(mem_db: DBConnection): + schema = pa.schema( + [pa.field("id", pa.int64()), pa.field("value", pa.string())], + metadata={b"schema_key": b"schema_value"}, + ) + table = mem_db.create_table("my_table", schema=schema) + new_data = pa.table({"id": [1, 2], "value": ["one", "two"]}) + assert new_data.schema.metadata is None + + async def do_merge_insert(): + return await table._inner.execute_merge_insert( + new_data.to_reader(), + { + "on": ["id"], + "when_matched_update_all": True, + "when_matched_update_all_condition": None, + "when_not_matched_insert_all": True, + "when_not_matched_by_source_delete": False, + "when_not_matched_by_source_condition": None, + "when_not_matched_by_source_condition_expr": None, + "timeout": None, + "use_index": True, + "use_rte": None, + "validate_single_shard": None, + }, + ) + + result = table_module.LOOP.run(do_merge_insert()) + + assert result.num_inserted_rows == 2 + assert table.to_arrow() == new_data + assert table.schema.metadata == schema.metadata + + def test_merge_insert_composite_key(mem_db: DBConnection): table = mem_db.create_table( "my_table", @@ -4674,6 +5034,69 @@ def test_restore_consistency(tmp_path): # Schema evolution +@pytest.mark.parametrize("mapping_type", [dict, UserDict, MappingProxyType]) +def test_add_columns_sql_mapping(mem_db, mapping_type): + table = mem_db.create_table("mapping_columns", pa.table({"id": [0, 1]})) + result = table.add_columns(mapping_type({"score": "id + 10"})) + assert result.version == 2 + assert table.to_arrow().to_pydict() == {"id": [0, 1], "score": [10, 11]} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mapping_type", [dict, UserDict, MappingProxyType]) +async def test_add_columns_sql_mapping_async(mem_db_async, mapping_type): + table = await mem_db_async.create_table("mapping_columns", pa.table({"id": [0, 1]})) + result = await table.add_columns(mapping_type({"score": "id + 10"})) + assert result.version == 2 + assert (await table.to_arrow()).to_pydict() == {"id": [0, 1], "score": [10, 11]} + + +def test_add_columns_tuple_batches(mem_db): + table = mem_db.create_table("tuple_columns", pa.table({"id": [0, 1]})) + result = table.add_columns( + (pa.record_batch({"score": [10]}), pa.record_batch({"score": [20]})) + ) + assert result.version == 2 + assert table.to_arrow().to_pydict() == {"id": [0, 1], "score": [10, 20]} + + +def _add_columns_input(kind): + values = pa.table({"score": [10, None, 30]}) + if kind == "pandas": + pd = pytest.importorskip("pandas") + return pd.DataFrame( + {"score": pd.array([10, None, 30], dtype="Int64")}, + index=pd.Index([9, 7, 5], name="source_index"), + ) + if kind == "polars": + return pl.from_arrow(values) + if kind == "batch": + return values.to_batches()[0] + if kind == "reader": + return values.to_reader(max_chunksize=1) + return values + + +@pytest.mark.parametrize("kind", ["pandas", "polars", "table", "batch", "reader"]) +def test_add_columns_data(mem_db, kind): + table = mem_db.create_table("columns_data", pa.table({"id": [2, 0, 1]})) + result = table.add_columns(_add_columns_input(kind)) + assert result.version == 2 + assert table.to_arrow().to_pydict() == {"id": [2, 0, 1], "score": [10, None, 30]} + assert table.schema.field("score").type == pa.int64() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["pandas", "polars", "table", "batch", "reader"]) +async def test_add_columns_data_async(mem_db_async, kind): + table = await mem_db_async.create_table("columns_data", pa.table({"id": [2, 0, 1]})) + result = await table.add_columns(_add_columns_input(kind)) + assert result.version == 2 + data = await table.to_arrow() + assert data.to_pydict() == {"id": [2, 0, 1], "score": [10, None, 30]} + assert data.schema.field("score").type == pa.int64() + + def test_add_columns(mem_db: DBConnection): data = pa.table({"id": [0, 1]}) table = LanceTable.create(mem_db, "my_table", data=data) @@ -5491,14 +5914,15 @@ async def test_async_search_runs_embedding_on_dedicated_executor( @pytest.mark.experimental_functions -def test_computed_column_declare_and_refresh(tmp_path): +@pytest.mark.parametrize("batch_size", [None, 8]) +def test_computed_column_declare_and_refresh(tmp_path, batch_size): db = lancedb.connect(tmp_path) table = db.create_table("computed", [{"x": 1}, {"x": 2}]) table.add_columns(computed={"doubled": "x * 2"}) assert table.to_arrow()["doubled"].to_pylist() == [None, None] - result = table.refresh_column("doubled") + result = table.refresh_column("doubled", batch_size=batch_size) assert result.rows_filled == 2 assert sorted(table.to_arrow()["doubled"].to_pylist()) == [2, 4] @@ -5540,32 +5964,80 @@ def test_computed_column_blob_projection_inherits_semantics(tmp_path): @pytest.mark.experimental_functions @pytest.mark.asyncio -async def test_computed_column_async(tmp_path): +@pytest.mark.parametrize("batch_size", [None, 8]) +async def test_computed_column_async(tmp_path, batch_size): db = await lancedb.connect_async(tmp_path) table = await db.create_table("computed_async", [{"x": 3}]) await table.add_columns(computed={"tripled": "x * 3"}) - await table.refresh_column("tripled") + await table.refresh_column("tripled", batch_size=batch_size) assert (await table.to_arrow())["tripled"].to_pylist() == [9] +@pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"]) +@pytest.mark.parametrize("batch_size", [0, -1]) +def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size): + db = lancedb.connect(tmp_path) + table = db.create_table("invalid_refresh_batch", [{"x": 1}]) + with pytest.raises(ValueError, match="batch_size must be greater than zero"): + getattr(table, method)("x", batch_size=batch_size) + + +@pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"]) +@pytest.mark.parametrize( + "refresh_kwargs,option", + [ + ({"retry_policy": lancedb.FunctionRetryPolicy(transient=True)}, "retry_policy"), + ({"where": "x > 0"}, "where"), + ({"error_policy": "skip"}, "error_policy"), + ({"max_failed_fraction": 0.5}, "max_failed_fraction"), + ({"max_failed_rows": 10}, "max_failed_rows"), + ({"row_timeout_seconds": 30}, "row_timeout_seconds"), + ({"init_timeout_seconds": 60}, "init_timeout_seconds"), + ({"num_workers": 2}, "num_workers"), + ({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"), + ], +) +def test_local_refresh_rejects_enterprise_options( + tmp_path, method, refresh_kwargs, option +): + table = lancedb.connect(tmp_path).create_table("rows", [{"x": 1}]) + with pytest.raises( + NotImplementedError, match=f"{option} requires a LanceDB Enterprise refresh" + ): + getattr(table, method)("x", **refresh_kwargs) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"]) +@pytest.mark.parametrize("batch_size", [0, -1]) +async def test_async_refresh_column_rejects_invalid_batch_size( + tmp_path, method, batch_size +): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("invalid_refresh_batch", [{"x": 1}]) + with pytest.raises(ValueError, match="batch_size must be greater than zero"): + await getattr(table, method)("x", batch_size=batch_size) + + def test_function_errors_are_remote_only(tmp_path): db = lancedb.connect(tmp_path) table = db.create_table("t", [{"x": 1}]) with pytest.raises( - NotImplementedError, match="recorded only in LanceDB Distributed" + NotImplementedError, match="recorded only in LanceDB Enterprise" ): table.function_errors() @pytest.mark.experimental_functions -def test_refresh_column_async_returns_job(tmp_path): +@pytest.mark.parametrize("batch_size", [None, 8]) +def test_refresh_column_async_returns_job(tmp_path, batch_size): db = lancedb.connect(tmp_path) table = db.create_table("computed_job", [{"x": 1}, {"x": 2}]) table.add_columns(computed={"doubled": "x * 2"}) - job = table.refresh_column_async("doubled") + job = table.refresh_column_async("doubled", batch_size=batch_size) assert job.id is None # in-process jobs have no server id result = job.wait() assert isinstance(result, lancedb.RefreshColumnResult) @@ -5590,12 +6062,13 @@ def test_refresh_column_async_returns_job(tmp_path): @pytest.mark.experimental_functions @pytest.mark.asyncio -async def test_refresh_column_async_job_async_table(tmp_path): +@pytest.mark.parametrize("batch_size", [None, 8]) +async def test_refresh_column_async_job_async_table(tmp_path, batch_size): db = await lancedb.connect_async(tmp_path) table = await db.create_table("computed_job_async", [{"x": 3}]) await table.add_columns(computed={"tripled": "x * 3"}) - job = await table.refresh_column_async("tripled") + job = await table.refresh_column_async("tripled", batch_size=batch_size) result = await job.wait() assert isinstance(result, lancedb.RefreshColumnResult) assert result.rows_assigned == 1 @@ -5605,6 +6078,139 @@ async def test_refresh_column_async_job_async_table(tmp_path): assert (await table.to_arrow())["tripled"].to_pylist() == [9] +def test_add_columns_reader_deleted_rows_and_fragments(mem_db): + table = mem_db.create_table("column_fragments", pa.table({"id": [9, 3]})) + table.add(pa.table({"id": [7, 1, 5]})) + table.delete("id = 3") + before = table.to_arrow() + values = pa.table({"score": [90, 70, 10, 50]}) + reader = values.to_reader(max_chunksize=3) + version = table.version + result = table.add_columns(reader) + assert result.version == version + 1 + assert table.to_arrow().to_pydict() == { + "id": before["id"].to_pylist(), + "score": [90, 70, 10, 50], + } + assert before["id"].to_pylist() == [9, 7, 1, 5] + + +@pytest.mark.parametrize("count", [0, 1, 3]) +def test_add_columns_reader_wrong_count_is_atomic(mem_db, count): + table = mem_db.create_table("column_counts", pa.table({"id": [0, 1]})) + before, version = table.to_arrow(), table.version + reader = pa.table({"score": pa.array(range(count), type=pa.int64())}).to_reader() + with pytest.raises(ValueError, match="Stream"): + table.add_columns(reader) + assert table.version == version + assert table.to_arrow().equals(before) + + +def test_add_columns_reader_empty_table(mem_db): + table = mem_db.create_table("empty_columns", schema=pa.schema([("id", pa.int64())])) + schema = pa.schema([("score", pa.float32())]) + result = table.add_columns(pa.RecordBatchReader.from_batches(schema, [])) + assert result.version == 2 + assert table.schema.names == ["id", "score"] + assert table.schema.field("score").type == pa.float32() + assert table.count_rows() == 0 + + +def test_add_columns_reader_error_is_atomic(mem_db): + table = mem_db.create_table("column_error", pa.table({"id": [0, 1]})) + before, version = table.to_arrow(), table.version + + def batches(): + yield pa.record_batch({"score": [10]}) + raise RuntimeError("reader failed deliberately") + + reader = pa.RecordBatchReader.from_batches( + pa.schema([("score", pa.int64())]), batches() + ) + with pytest.raises((RuntimeError, OSError), match="reader failed deliberately"): + table.add_columns(reader) + assert table.version == version + assert table.to_arrow().equals(before) + + +def test_add_columns_reader_collision_is_atomic(mem_db): + table = mem_db.create_table("column_collision", pa.table({"id": [0, 1]})) + before, version = table.to_arrow(), table.version + with pytest.raises(ValueError, match="id"): + table.add_columns(pa.table({"id": [4, 5]}).to_reader()) + assert table.version == version + assert table.to_arrow().equals(before) + + +def test_add_columns_preserves_arrow_types(mem_db): + table = mem_db.create_table("column_types", pa.table({"id": [0, 1]})) + vectors = pa.array([[1.0, 2.0], [3.0, 4.0]], type=pa.list_(pa.float64(), 2)) + values = pa.table({"vector": vectors, "score": pa.array([None, 2.5], pa.float32())}) + table.add_columns(values) + assert table.schema.field("vector").type == pa.list_(pa.float64(), 2) + assert table.schema.field("score").type == pa.float32() + assert table.to_arrow().select(values.column_names).equals(values) + + +def test_add_columns_dataframe_computed_conflict(mem_db): + table = mem_db.create_table("column_conflict", pa.table({"id": [0, 1, 2]})) + before, version = table.to_arrow(), table.version + with pytest.raises(ValueError, match="cannot take both transforms and computed"): + table.add_columns(_add_columns_input("pandas"), computed={"x": "id + 1"}) + assert table.version == version + assert table.to_arrow().equals(before) + + +@pytest.mark.experimental_functions +@pytest.mark.parametrize( + "transforms", [{}, pa.schema([]), UserDict(), MappingProxyType({})] +) +def test_add_columns_computed_with_empty_transforms(mem_db, transforms): + table = mem_db.create_table("empty_transforms", pa.table({"id": [0, 1]})) + result = table.add_columns(transforms, computed={"x": "id + 1"}) + assert result.version == 2 + table.refresh_column("x") + assert table.to_arrow()["x"].to_pylist() == [1, 2] + + +@pytest.mark.parametrize("kind", ["batch", "reader", "leading_and_trailing"]) +def test_add_columns_empty_batches(mem_db, kind): + ids = [0] if kind == "leading_and_trailing" else [] + table = mem_db.create_table( + "empty_batches", pa.table({"id": pa.array(ids, pa.int64())}) + ) + schema = pa.schema([("score", pa.int64())]) + empty = pa.RecordBatch.from_arrays([pa.array([], pa.int64())], schema=schema) + if kind == "batch": + data = empty + elif kind == "reader": + data = pa.RecordBatchReader.from_batches(schema, [empty]) + else: + values = pa.RecordBatch.from_arrays([pa.array([10])], schema=schema) + data = pa.RecordBatchReader.from_batches(schema, [empty, values, empty]) + result = table.add_columns(data) + assert result.version == 2 + assert table.to_arrow().to_pydict() == {"id": ids, "score": [10] if ids else []} + + +@pytest.mark.parametrize("kind", ["table", "reader"]) +def test_add_columns_data_rejects_computed_metadata(mem_db, kind): + table = mem_db.create_table("foreign_metadata", pa.table({"id": [0]})) + before, version = table.to_arrow(), table.version + schema = pa.schema( + [pa.field("score", pa.int64(), metadata={b"computed_column": b"true"})] + ) + data = pa.Table.from_arrays([pa.array([10])], schema=schema) + if kind == "reader": + data = data.to_reader() + with pytest.raises(ValueError, match="computed"): + table.add_columns(data) + assert table.version == version + assert table.to_arrow().equals(before) + table.add(pa.table({"id": [1]})) + assert table.count_rows() == 2 + + @pytest.mark.experimental_functions @pytest.mark.parametrize("interval", [None, 300]) def test_computed_auto_refresh_options(tmp_path, interval): diff --git a/python/python/tests/test_table_signatures.py b/python/python/tests/test_table_signatures.py index 346935b2b..387a89f31 100644 --- a/python/python/tests/test_table_signatures.py +++ b/python/python/tests/test_table_signatures.py @@ -192,7 +192,10 @@ def test_remote_optimize_options(): with pytest.raises(NotImplementedError, match="remote optimize"): table.optimize(cleanup_older_than=age, delete_unverified=True, retrain=True) handle.optimize.assert_awaited_once_with( - cleanup_older_than=age, delete_unverified=True, retrain=True + cleanup_older_than=age, + delete_unverified=True, + retrain=True, + compaction_options=None, ) diff --git a/python/python/tests/test_util.py b/python/python/tests/test_util.py index 1e470e3be..5f444ac44 100644 --- a/python/python/tests/test_util.py +++ b/python/python/tests/test_util.py @@ -4,12 +4,11 @@ import os import pathlib +import sys from datetime import time, timedelta, timezone from decimal import Decimal, localcontext from typing import Optional -import lance -from lance.blob import BlobType as LanceBlobType from lancedb.conftest import MockTextEmbeddingFunction from lancedb.embeddings.base import EmbeddingFunctionConfig from lancedb.embeddings.registry import EmbeddingFunctionRegistry @@ -26,7 +25,6 @@ from lancedb.table import ( sanitize_create_table, ) import pyarrow as pa -import pandas as pd import polars as pl import pytest import lancedb @@ -180,7 +178,8 @@ def test_value_to_sql_string(tmp_path): ) for value in values: table.update(where=f"search = {value_to_sql(value)}", values={"replace": value}) - assert table.to_pandas().query("search == @value")["replace"].item() == value + rows = table.to_arrow().to_pylist() + assert next(row["replace"] for row in rows if row["search"] == value) == value @pytest.mark.parametrize( @@ -275,10 +274,15 @@ def test_value_to_sql_time_and_timedelta(tmp_path): def test_value_to_sql_keeps_nanoseconds(tmp_path): # Arrow scalars and pandas.Timedelta values can hold nanoseconds, which a # Python timedelta or time would round to microseconds. - assert ( - value_to_sql(pd.Timedelta(1001, "ns")) - == "arrow_cast(1001, 'Duration(Nanosecond)')" - ) + try: + import pandas as pd + except ImportError: + pd = None + if pd is not None: + assert ( + value_to_sql(pd.Timedelta(1001, "ns")) + == "arrow_cast(1001, 'Duration(Nanosecond)')" + ) assert value_to_sql(pa.scalar(None, pa.duration("ns"))) == "NULL" db = lancedb.connect(tmp_path) @@ -780,15 +784,20 @@ class TestModel(lancedb.pydantic.LanceModel): lambda: pa.table({"a": [1], "b": [2]}), lambda: pa.table({"a": [1], "b": [2]}).to_reader(), lambda: iter(pa.table({"a": [1], "b": [2]}).to_batches()), - lambda: lance.write_dataset( + lambda: tuple(pa.table({"a": [1], "b": [2]}).to_batches()), + lambda: pytest.importorskip("lance").write_dataset( pa.table({"a": [1], "b": [2]}), "memory://test", ), - lambda: lance.write_dataset( - pa.table({"a": [1], "b": [2]}), - "memory://test", - ).scanner(), - lambda: pd.DataFrame({"a": [1], "b": [2]}), + lambda: ( + pytest.importorskip("lance") + .write_dataset( + pa.table({"a": [1], "b": [2]}), + "memory://test", + ) + .scanner() + ), + lambda: pytest.importorskip("pandas").DataFrame({"a": [1], "b": [2]}), lambda: pl.DataFrame({"a": [1], "b": [2]}), lambda: pl.LazyFrame({"a": [1], "b": [2]}), lambda: [TestModel(a=1, b=2)], @@ -799,6 +808,7 @@ class TestModel(lancedb.pydantic.LanceModel): "pa.Table", "pa.RecordBatchReader", "batch_iter", + "batch_tuple", "lance.LanceDataset", "lance.LanceScanner", "pd.DataFrame", @@ -813,6 +823,12 @@ def test_into_pyarrow_table(data): assert output == expected +@pytest.mark.parametrize("data", ["score", ""]) +def test_into_pyarrow_reader_rejects_text(data): + with pytest.raises(TypeError, match="Unknown data type"): + _into_pyarrow_reader(data) + + def test_infer_target_schema(): example = pa.schema( { @@ -958,10 +974,10 @@ def test_infer_target_schema_with_vector_embedding_names(): @pytest.mark.parametrize( "data", [ - [{"id": 1, "text": "hello"}], - pa.RecordBatch.from_pylist([{"id": 1, "text": "hello"}]), - pd.DataFrame({"id": [1], "text": ["hello"]}), - pl.DataFrame({"id": [1], "text": ["hello"]}), + lambda: [{"id": 1, "text": "hello"}], + lambda: pa.RecordBatch.from_pylist([{"id": 1, "text": "hello"}]), + lambda: pytest.importorskip("pandas").DataFrame({"id": [1], "text": ["hello"]}), + lambda: pl.DataFrame({"id": [1], "text": ["hello"]}), ], ids=["rows", "pa.RecordBatch", "pd.DataFrame", "pl.DataFrame"], ) @@ -993,6 +1009,7 @@ def test_sanitize_data( schema: Optional[pa.Schema], with_embedding: bool, ): + data = data() if with_embedding: registry = EmbeddingFunctionRegistry.get_instance() registry.register("test")(MockTextEmbeddingFunction) @@ -1017,7 +1034,9 @@ def test_sanitize_data( # polars uses large_string, pandas 3.0+ uses large_string, others use string if isinstance(data, pl.DataFrame): text_type = pa.large_utf8() - elif isinstance(data, pd.DataFrame): + elif (pd := sys.modules.get("pandas")) is not None and isinstance( + data, pd.DataFrame + ): text_type = pandas_string_type() else: text_type = pa.string() @@ -1352,6 +1371,8 @@ def test_fixed_size_list_blob_coercion_keeps_null_rows(): def test_cast_to_target_schema_accepts_pylance_blob_v2(): + lance = pytest.importorskip("lance") + LanceBlobType = pytest.importorskip("lance.blob").BlobType target_type = lancedb.BlobType() source = lance.blob_array([b"hello", None]) assert type(source.type) is LanceBlobType @@ -1371,6 +1392,8 @@ def test_cast_to_target_schema_accepts_pylance_blob_v2(): def test_cast_to_target_schema_rejects_different_blob_v2_class(): + lance = pytest.importorskip("lance") + class OtherBlobType(pa.ExtensionType): def __init__(self): super().__init__(lancedb.BlobType().storage_type, "lance.blob.v2") diff --git a/python/src/authz.rs b/python/src/authz.rs index 6ad3e69b1..8e5ae5b7c 100644 --- a/python/src/authz.rs +++ b/python/src/authz.rs @@ -262,6 +262,19 @@ impl AuthzObject { })) } + #[staticmethod] + fn storage_integration( + database: &str, + namespace: &Bound<'_, PyAny>, + name: &str, + ) -> PyResult { + Self::validated(Object::StorageIntegration(StorageIntegrationObject { + database: database.into(), + namespace: namespace_path(namespace)?, + storage_integration: name.into(), + })) + } + #[staticmethod] fn function(database: &str, namespace: &Bound<'_, PyAny>, name: &str) -> PyResult { Self::validated(Object::Function(FunctionObject { diff --git a/python/src/connection.rs b/python/src/connection.rs index 54ea615de..bffa167d8 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -24,6 +24,8 @@ use lancedb::{ connection::NamespaceClientPushdownOperation, database::namespace::LanceNamespaceDatabase, database::{CreateTableMode, Database, ReadConsistency}, + function::GpuClass as LanceGpuClass, + graph::PropertyGraphDefinition, }; use pyo3::{ Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, @@ -37,6 +39,62 @@ pub struct Connection { inner: Option, } +/// Configured hardware and worker limits of a Function GPU class. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct GpuClass { + pub name: String, + pub resource_name: String, + pub gpu_model: Option, + pub gpu_memory_bytes: Option, + pub max_gpu_count_per_worker: Option, + pub cpu_millis: Option, + pub memory_bytes: Option, + pub ephemeral_storage_bytes: Option, +} + +impl From for GpuClass { + fn from(class: LanceGpuClass) -> Self { + Self { + name: class.name, + resource_name: class.resource_name, + gpu_model: class.gpu_model, + gpu_memory_bytes: class.gpu_memory_bytes, + max_gpu_count_per_worker: class.max_gpu_count_per_worker, + cpu_millis: class.cpu_millis, + memory_bytes: class.memory_bytes, + ephemeral_storage_bytes: class.ephemeral_storage_bytes, + } + } +} + +#[pymethods] +impl GpuClass { + fn __repr__(&self) -> String { + let gpu_model = self + .gpu_model + .as_ref() + .map_or_else(|| "None".to_string(), |value| format!("{value:?}")); + let optional = |value: Option| { + value.map_or_else(|| "None".to_string(), |value| value.to_string()) + }; + let max_gpu_count = self + .max_gpu_count_per_worker + .map_or_else(|| "None".to_string(), |value| value.to_string()); + format!( + "GpuClass(name={:?}, resource_name={:?}, gpu_model={gpu_model}, \ + gpu_memory_bytes={}, max_gpu_count_per_worker={max_gpu_count}, \ + cpu_millis={}, memory_bytes={}, ephemeral_storage_bytes={})", + self.name, + self.resource_name, + optional(self.gpu_memory_bytes), + optional(self.cpu_millis), + optional(self.memory_bytes), + optional(self.ephemeral_storage_bytes), + ) + } +} + impl Connection { pub(crate) fn new(inner: LanceConnection) -> Self { Self { inner: Some(inner) } @@ -870,6 +928,23 @@ impl Connection { }) } + #[pyo3(signature = (name, version, namespace_path=None))] + pub fn _drop_function_with_warnings( + self_: PyRef<'_, Self>, + name: String, + version: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let namespace_path = namespace_path.unwrap_or_default(); + future_into_py(self_.py(), async move { + inner + .drop_function_with_warnings(name, version, &namespace_path) + .await + .infer_error() + }) + } + #[pyo3(signature = (name, version, namespace_path=None))] pub fn drop_function_async( self_: PyRef<'_, Self>, @@ -888,6 +963,72 @@ impl Connection { }) } + #[pyo3(signature = (name, request, namespace_path=None))] + pub fn create_storage_integration<'py>( + &self, + py: Python<'py>, + name: String, + request: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self.get_inner()?.clone(); + let request: lancedb::storage_integration::CreateStorageIntegrationRequest = + serde_json::from_str(&request) + .map_err(|error| PyValueError::new_err(error.to_string()))?; + future_into_py(py, async move { + let info = inner + .create_storage_integration(name, request, &namespace_path.unwrap_or_default()) + .await + .infer_error()?; + serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string())) + }) + } + #[pyo3(signature = (name, namespace_path=None))] + pub fn describe_storage_integration<'py>( + &self, + py: Python<'py>, + name: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self.get_inner()?.clone(); + future_into_py(py, async move { + let info = inner + .describe_storage_integration(name, &namespace_path.unwrap_or_default()) + .await + .infer_error()?; + serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string())) + }) + } + #[pyo3(signature = (*, namespace_path=None, page_token=None, page_limit=None))] + pub fn list_storage_integrations( + &self, + namespace_path: Option>, + page_token: Option, + page_limit: Option, + ) -> PyResult { + Ok(crate::listing::NameListing::new( + self.get_inner()?.list_storage_integrations( + &namespace_path.unwrap_or_default(), + crate::listing::options(page_token, page_limit), + ), + )) + } + #[pyo3(signature = (name, namespace_path=None))] + pub fn drop_storage_integration<'py>( + &self, + py: Python<'py>, + name: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self.get_inner()?.clone(); + future_into_py(py, async move { + inner + .drop_storage_integration(name, &namespace_path.unwrap_or_default()) + .await + .infer_error() + }) + } + #[pyo3(signature = (name, value, namespace_path=None))] pub fn create_secret( self_: PyRef<'_, Self>, @@ -1050,6 +1191,79 @@ impl Connection { )) } + /// Create a property graph from its definition's JSON, and return its + /// description's JSON. The Python layer names the fields; the JSON keeps + /// the binding free of classes kept in step with the Rust structs. + #[pyo3(signature = (name, definition_json, namespace_path=None))] + pub fn create_property_graph( + self_: PyRef<'_, Self>, + name: String, + definition_json: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let namespace_path = namespace_path.unwrap_or_default(); + future_into_py(self_.py(), async move { + let definition = PropertyGraphDefinition::from_json(&definition_json).infer_error()?; + inner + .create_property_graph(name, &definition, &namespace_path) + .await + .infer_error()? + .to_json() + .infer_error() + }) + } + + /// The JSON description of the property graph named `name`. + #[pyo3(signature = (name, namespace_path=None))] + pub fn describe_property_graph( + self_: PyRef<'_, Self>, + name: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let namespace_path = namespace_path.unwrap_or_default(); + future_into_py(self_.py(), async move { + inner + .describe_property_graph(name, &namespace_path) + .await + .infer_error()? + .to_json() + .infer_error() + }) + } + + #[pyo3(signature = (name, namespace_path=None))] + pub fn drop_property_graph( + self_: PyRef<'_, Self>, + name: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let namespace_path = namespace_path.unwrap_or_default(); + future_into_py(self_.py(), async move { + inner + .drop_property_graph(name, &namespace_path) + .await + .infer_error() + }) + } + + #[pyo3(signature = (namespace_path=None, *, page_token=None, page_limit=None))] + pub fn list_property_graphs( + &self, + namespace_path: Option>, + page_token: Option, + page_limit: Option, + ) -> PyResult { + Ok(crate::listing::NameListing::new( + self.get_inner()?.list_property_graphs( + &namespace_path.unwrap_or_default(), + crate::listing::options(page_token, page_limit), + ), + )) + } + #[pyo3(signature = (*, page_token=None, page_limit=None))] pub fn list_jobs( &self, @@ -1062,6 +1276,14 @@ impl Connection { )) } + pub fn list_gpu_classes(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let classes = inner.list_gpu_classes().await.infer_error()?; + Ok(classes.into_iter().map(GpuClass::from).collect::>()) + }) + } + pub fn cancel_job(self_: PyRef<'_, Self>, job_id: String) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { diff --git a/python/src/error.rs b/python/src/error.rs index 869a5a247..1ac9f7ac3 100644 --- a/python/src/error.rs +++ b/python/src/error.rs @@ -2,13 +2,13 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use pyo3::{ - PyErr, PyResult, Python, + Bound, PyAny, PyErr, PyResult, Python, exceptions::{PyIOError, PyNotImplementedError, PyOSError, PyRuntimeError, PyValueError}, intern, types::{PyAnyMethods, PyNone}, }; -use lancedb::error::Error as LanceError; +use lancedb::error::{Error as LanceError, HttpErrorDetails, RemoteErrorMetadata}; pub trait PythonErrorExt { /// Convert to a python error based on the Lance error type @@ -28,12 +28,67 @@ impl PythonErrorExt for std::result::Result { Err(err) => match err { LanceError::InvalidInput { .. } | LanceError::InvalidTableName { .. } - | LanceError::TableNotFound { .. } | LanceError::NotAMaterializedView { .. } | LanceError::Schema { .. } | LanceError::DatabaseNotFound { .. } | LanceError::DatabaseAlreadyExists { .. } | LanceError::TableAlreadyExists { .. } => self.value_error(), + LanceError::TableNotFound { source, .. } => { + let Some( + request_error @ LanceError::Http { + request_id, + status_code, + source: http_source, + }, + ) = source.downcast_ref::() + else { + return self.value_error(); + }; + Python::attach(|py| { + let status_code = status_code.map(|s| s.as_u16()); + let metadata = request_error.remote_error_metadata(); + let details = request_error.http_error_details(); + let py_err = if details.is_some() + || metadata.is_some_and(|metadata| metadata.error_code.is_some()) + { + new_py_http_error( + py, + http_source.to_string(), + request_id, + status_code, + details, + metadata, + false, + )? + } else { + let cls = py + .import(intern!(py, "lancedb.remote.errors"))? + .getattr(intern!(py, "TableNotFoundError"))?; + let error = cls.call1((err.to_string(), request_id, status_code))?; + error.setattr( + "job_id", + metadata.and_then(|value| value.job_id.as_deref()), + )?; + error.setattr( + "job_request_id", + metadata.and_then(|value| value.job_request_id.as_deref()), + )?; + error + }; + let cause = + http_from_rust_error(py, source.as_ref(), request_id, status_code)?; + py_err.setattr(intern!(py, "__cause__"), cause)?; + Err(PyErr::from_value(py_err)) + }) + } + LanceError::ColumnNotFound { .. } | LanceError::FieldNotFound { .. } => { + Python::attach(|py| { + let cls = py + .import(intern!(py, "lancedb.exceptions"))? + .getattr(intern!(py, "ColumnNotFoundError"))?; + Err(PyErr::from_value(cls.call1((err.to_string(),))?)) + }) + } LanceError::CreateDir { .. } => self.os_error(), LanceError::ObjectStore { .. } => Err(PyIOError::new_err(err.to_string())), LanceError::NotSupported { .. } => { @@ -44,15 +99,23 @@ impl PythonErrorExt for std::result::Result { source, status_code, } => Python::attach(|py| { - let message = err.to_string(); - let http_err_cls = py - .import(intern!(py, "lancedb.remote.errors"))? - .getattr(intern!(py, "HttpError"))?; - let err = http_err_cls.call1(( + let message = if err + .remote_error_metadata() + .is_some_and(|metadata| metadata.error_code.is_some()) + { + source.to_string() + } else { + err.to_string() + }; + let err = new_py_http_error( + py, message, request_id, status_code.map(|s| s.as_u16()), - ))?; + err.http_error_details(), + err.remote_error_metadata(), + is_transport_error(source.as_ref()), + )?; if let Some(cause) = source.source() { // The HTTP error already includes the first cause. But @@ -105,11 +168,68 @@ impl PythonErrorExt for std::result::Result { err.setattr(intern!(py, "__cause__"), cause_err)?; Err(PyErr::from_value(err)) }), - LanceError::JobFailed { .. } => Python::attach(|py| { + LanceError::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } => Python::attach(|py| { + let error = py + .import(intern!(py, "lancedb.remote.errors"))? + .getattr(intern!(py, "ResponseInterruptedError"))? + .call1(( + err.to_string(), + request_id, + *batches, + *rows, + *table_version, + is_transport_error(&**source), + ))?; + let cause = http_from_rust_error(py, &**source, request_id, None)?; + error.setattr(intern!(py, "__cause__"), cause)?; + Err(PyErr::from_value(error)) + }), + LanceError::Sql { + message, + request_id, + grpc_code, + metadata, + } => Python::attach(|py| { + Err(PyErr::from_value(new_py_sql_error( + py, message, request_id, *grpc_code, metadata, + )?)) + }), + LanceError::JobFailed { job_id, failure } => Python::attach(|py| { let cls = py .import(intern!(py, "lancedb.exceptions"))? .getattr(intern!(py, "JobFailedError"))?; - Err(PyErr::from_value(cls.call1((err.to_string(),))?)) + let sql_source = match failure.source.as_deref() { + Some(LanceError::Sql { + message, + request_id, + grpc_code, + metadata, + }) => Some(( + new_py_sql_error(py, message, request_id, *grpc_code, metadata)?, + request_id.as_str(), + metadata.job_request_id.as_deref(), + )), + _ => None, + }; + let error = cls.call1(( + err.to_string(), + job_id.clone(), + failure.sql_job_id.clone(), + sql_source.as_ref().map(|(_, request_id, _)| *request_id), + sql_source + .as_ref() + .and_then(|(_, _, request_id)| *request_id), + ))?; + if let Some((cause, _, _)) = sql_source { + error.setattr(intern!(py, "__cause__"), cause)?; + } + Err(PyErr::from_value(error)) }), LanceError::JobCancelled { .. } => Python::attach(|py| { let cls = py @@ -143,13 +263,24 @@ impl PythonErrorExt for std::result::Result { fn http_from_rust_error( py: Python<'_>, - err: &dyn std::error::Error, + err: &(dyn std::error::Error + 'static), request_id: &str, status_code: Option, ) -> PyResult { let message = err.to_string(); - let http_err_cls = py.import("lancedb.remote.errors")?.getattr("HttpError")?; - let py_err = http_err_cls.call1((message, request_id, status_code))?; + let details = err + .downcast_ref::() + .and_then(LanceError::http_error_details); + let py_err = new_py_http_error( + py, + message, + request_id, + status_code, + details, + err.downcast_ref::() + .and_then(LanceError::remote_error_metadata), + is_transport_error(err), + )?; // Reset the traceback since it doesn't provide additional information. let py_err = py_err.call_method1(intern!(py, "with_traceback"), (PyNone::get(py),))?; @@ -161,3 +292,356 @@ fn http_from_rust_error( Ok(PyErr::from_value(py_err)) } + +fn new_py_http_error<'py>( + py: Python<'py>, + message: String, + request_id: &str, + status_code: Option, + details: Option<&HttpErrorDetails>, + metadata: Option<&RemoteErrorMetadata>, + is_transport_error: bool, +) -> PyResult> { + let error_code = metadata + .and_then(|metadata| metadata.error_code.as_deref()) + .or_else(|| details.map(|details| details.error_code.as_str())); + let resource_kind = details.map(|details| details.resource_kind.as_str()); + let resource_name = details.map(|details| details.resource_name.as_str()); + let namespace_path = details.map(|details| details.namespace_path.clone()); + + py.import("lancedb.remote.errors")? + .getattr("HttpError")? + .call1(( + message, + request_id, + status_code, + error_code, + resource_kind, + resource_name, + namespace_path, + is_transport_error, + metadata.and_then(|metadata| metadata.job_id.as_deref()), + metadata.and_then(|metadata| metadata.job_request_id.as_deref()), + )) +} + +fn new_py_sql_error<'py>( + py: Python<'py>, + message: &str, + request_id: &str, + grpc_code: i32, + metadata: &RemoteErrorMetadata, +) -> PyResult> { + if sql_has_resource_error(metadata, grpc_code) { + return new_py_sql_resource_error(py, message, request_id, grpc_code, metadata); + } + py.import("lancedb.remote.errors")? + .getattr("SqlError")? + .call1(( + message, + request_id, + grpc_code, + metadata.error_code.as_deref(), + metadata.job_id.as_deref(), + metadata.job_request_id.as_deref(), + )) +} + +fn new_py_sql_resource_error<'py>( + py: Python<'py>, + message: &str, + request_id: &str, + grpc_code: i32, + metadata: &RemoteErrorMetadata, +) -> PyResult> { + let resource = metadata.resource.as_ref().unwrap(); + py.import("lancedb.remote.errors")? + .getattr("HttpError")? + .call1(( + message, + request_id, + grpc_code_to_http_status(grpc_code), + metadata.error_code.as_deref(), + resource.kind.as_str(), + resource.name.as_str(), + resource.namespace_path.clone(), + false, + metadata.job_id.as_deref(), + metadata.job_request_id.as_deref(), + )) +} + +fn sql_has_resource_error(metadata: &RemoteErrorMetadata, grpc_code: i32) -> bool { + metadata.resource.is_some() + && matches!( + (metadata.error_code.as_deref(), grpc_code), + // These are gRPC status codes, not HTTP status codes. + (Some("not_found"), 5) | (Some("already_exists"), 6) + ) +} + +fn grpc_code_to_http_status(grpc_code: i32) -> Option { + match grpc_code { + 3 => Some(400), + 5 => Some(404), + 6 => Some(409), + 7 => Some(403), + 9 => Some(400), + 12 => Some(501), + _ => None, + } +} + +// Preserve the typed transport classification across the Python boundary. +// A missing status code alone also covers malformed job responses, which +// waiting longer cannot repair. +fn is_transport_error(err: &(dyn std::error::Error + 'static)) -> bool { + if let Some(error) = err.downcast_ref::() { + return error.is_connect() + || error.is_timeout() + || error.is_request() + || error.is_body() + || error.is_decode(); + } + err.source().is_some_and(is_transport_error) +} + +#[cfg(test)] +mod tests { + use std::ffi::CString; + use std::sync::{Arc, Once}; + + use lancedb::error::{JobFailure, RemoteResourceIdentity}; + use pyo3::types::{PyAnyMethods, PyModule}; + + use super::*; + + static INSTALL_PYTHON_ERROR_MODULES: Once = Once::new(); + + fn install_python_error_modules(py: Python<'_>) -> PyResult<()> { + // Load the checked-in error classes without requiring an installed wheel. + // The namespace exception is only a base for an unrelated remote class. + PyModule::from_code( + py, + c"import sys\n\nimport types\n\n\ + lancedb = types.ModuleType('lancedb')\n\ + lancedb.__path__ = []\n\ + lancedb_remote = types.ModuleType('lancedb.remote')\n\ + lancedb_remote.__path__ = []\n\ + lancedb.remote = lancedb_remote\n\ + namespace = types.ModuleType('lance_namespace')\n\ + namespace_errors = types.ModuleType('lance_namespace.errors')\n\ + namespace_errors.TableNotFoundError = RuntimeError\n\ + namespace.errors = namespace_errors\n\ + sys.modules['lancedb'] = lancedb\n\ + sys.modules['lancedb.remote'] = lancedb_remote\n\ + sys.modules['lance_namespace'] = namespace\n\ + sys.modules['lance_namespace.errors'] = namespace_errors", + c"error_test_bootstrap.py", + c"lancedb_error_test_bootstrap", + )?; + + let exceptions_code = + CString::new(include_str!("../../python/python/lancedb/exceptions.py")).unwrap(); + let exceptions = PyModule::from_code( + py, + &exceptions_code, + c"exceptions.py", + c"lancedb.exceptions", + )?; + let lancedb = py.import("lancedb")?; + lancedb.setattr("exceptions", &exceptions)?; + py.import("sys")? + .getattr("modules")? + .set_item("lancedb.exceptions", &exceptions)?; + + let remote_errors_code = + CString::new(include_str!("../../python/python/lancedb/remote/errors.py")).unwrap(); + let remote_errors = PyModule::from_code( + py, + &remote_errors_code, + c"remote/errors.py", + c"lancedb.remote.errors", + )?; + lancedb + .getattr("remote")? + .setattr("errors", &remote_errors)?; + py.import("sys")? + .getattr("modules")? + .set_item("lancedb.remote.errors", &remote_errors)?; + Ok(()) + } + + fn ensure_python_error_modules() { + Python::initialize(); + // Once waits without holding the GIL; only its one-time closure attaches. + INSTALL_PYTHON_ERROR_MODULES.call_once(|| { + Python::attach(install_python_error_modules).unwrap(); + }); + } + + #[test] + fn generic_job_failure_retains_the_named_resource_as_its_cause() { + ensure_python_error_modules(); + let source = LanceError::Sql { + message: "Function 'missing' was not found".into(), + request_id: "current-request".into(), + grpc_code: 5, + metadata: Box::new({ + let mut metadata = RemoteErrorMetadata::default(); + metadata.error_code = Some("not_found".into()); + metadata.job_id = Some("outer-job".into()); + metadata.job_request_id = Some("worker-request".into()); + metadata.resource = Some(RemoteResourceIdentity::new( + "function", + "missing", + vec!["ns".into()], + )); + metadata + }), + }; + let error = LanceError::JobFailed { + job_id: Some("outer-job".into()), + failure: Box::new(JobFailure { + message: Some("Function 'missing' was not found".into()), + traceback: None, + sql_job_id: Some("outer-job".into()), + source: Some(Arc::new(source)), + ..Default::default() + }), + }; + + let py_err = Python::attach(|_| { + let result: std::result::Result<(), LanceError> = Err(error); + result.infer_error().unwrap_err() + }); + Python::attach(|py| { + let value = py_err.value(py); + let job_failed = py + .import("lancedb.exceptions") + .unwrap() + .getattr("JobFailedError") + .unwrap(); + assert!(value.is_instance(&job_failed).unwrap(), "{py_err:?}"); + let cause = value.getattr("__cause__").unwrap(); + let function_not_found = py + .import("lancedb.remote.errors") + .unwrap() + .getattr("FunctionNotFoundError") + .unwrap(); + assert!( + cause.is_instance(&function_not_found).unwrap(), + "{py_err:?}" + ); + assert_eq!( + cause + .getattr("error_code") + .unwrap() + .extract::() + .unwrap(), + "not_found" + ); + assert_eq!( + cause + .getattr("resource_kind") + .unwrap() + .extract::() + .unwrap(), + "function" + ); + assert_eq!( + cause + .getattr("resource_name") + .unwrap() + .extract::() + .unwrap(), + "missing" + ); + assert_eq!( + cause + .getattr("namespace_path") + .unwrap() + .extract::>() + .unwrap(), + ["ns"] + ); + assert_eq!( + cause + .getattr("status_code") + .unwrap() + .extract::() + .unwrap(), + 404 + ); + assert_eq!( + cause + .getattr("request_id") + .unwrap() + .extract::() + .unwrap(), + "current-request" + ); + assert_eq!( + cause + .getattr("job_id") + .unwrap() + .extract::() + .unwrap(), + "outer-job" + ); + assert_eq!( + cause + .getattr("job_request_id") + .unwrap() + .extract::() + .unwrap(), + "worker-request" + ); + }); + } + + #[test] + fn direct_catalog_lookup_is_raised_as_the_named_resource_error() { + ensure_python_error_modules(); + for (kind, name, namespace_path, exception) in [ + ( + "function", + "missing", + vec!["ns".into()], + "FunctionNotFoundError", + ), + ("namespace", "ns", Vec::new(), "NamespaceNotFoundError"), + ] { + let mut metadata = RemoteErrorMetadata::default(); + metadata.error_code = Some("not_found".into()); + metadata.resource = Some(RemoteResourceIdentity::new(kind, name, namespace_path)); + let error = LanceError::Sql { + message: format!("{kind} '{name}' was not found"), + request_id: "current-request".into(), + grpc_code: 5, + metadata: Box::new(metadata), + }; + let py_err = Python::attach(|_| { + let result: std::result::Result<(), LanceError> = Err(error); + result.infer_error().unwrap_err() + }); + Python::attach(|py| { + let value = py_err.value(py); + let class = py + .import("lancedb.remote.errors") + .unwrap() + .getattr(exception) + .unwrap(); + assert!(value.is_instance(&class).unwrap(), "{py_err:?}"); + assert_eq!( + value + .getattr("resource_name") + .unwrap() + .extract::() + .unwrap(), + name + ); + }); + } + } +} diff --git a/python/src/index.rs b/python/src/index.rs index c6c3fe17d..3ec03b6fd 100644 --- a/python/src/index.rs +++ b/python/src/index.rs @@ -8,7 +8,9 @@ use lancedb::index::vector::{ }; use lancedb::index::{ Index as LanceDbIndex, - scalar::{BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder}, + scalar::{ + BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder, + }, }; use pyo3::IntoPyObject; use pyo3::types::PyStringMethods; @@ -33,6 +35,80 @@ pub fn class_name(ob: &'_ Bound<'_, PyAny>) -> PyResult { } } +/// Code-analyzer options shared by `FTS` and `tokenize`. +#[derive(Default)] +pub struct CodeAnalyzerOptions { + pub analyzer: Option, + pub split_identifiers: Option, + pub split_on_numerics: Option, + pub preserve_original: Option, + pub index_operators: Option, +} + +impl CodeAnalyzerOptions { + /// Check the options against the requested base tokenizer and return the + /// base tokenizer to use. `analyzer="code"` selects the code tokenizer when + /// `base_tokenizer` is left at its default of `"simple"`. + pub fn resolve_base_tokenizer(&self, base_tokenizer: String) -> PyResult { + let uses_code = match self.analyzer.as_deref() { + None | Some("text") => base_tokenizer == "code", + Some("code") => true, + Some(other) => { + return Err(PyValueError::new_err(format!( + "analyzer must be 'text' or 'code', got '{other}'" + ))); + } + }; + match self.analyzer.as_deref() { + Some("text") if base_tokenizer == "code" => { + return Err(PyValueError::new_err( + "base_tokenizer='code' requires analyzer='code'", + )); + } + Some("code") if base_tokenizer != "code" && base_tokenizer != "simple" => { + return Err(PyValueError::new_err(format!( + "analyzer='code' requires base_tokenizer='code', got '{base_tokenizer}'" + ))); + } + _ => {} + } + let flags = [ + self.split_identifiers, + self.split_on_numerics, + self.preserve_original, + self.index_operators, + ]; + if !uses_code && flags.into_iter().flatten().any(|value| value) { + return Err(PyValueError::new_err( + "split_identifiers, split_on_numerics, preserve_original and \ + index_operators require analyzer='code'", + )); + } + Ok(if uses_code { + "code".to_string() + } else { + base_tokenizer + }) + } + + /// Apply the explicit flags on top of the tokenizer defaults. + pub fn apply(&self, mut params: FtsIndexBuilder) -> FtsIndexBuilder { + if let Some(value) = self.split_identifiers { + params = params.split_identifiers(value); + } + if let Some(value) = self.split_on_numerics { + params = params.split_on_numerics(value); + } + if let Some(value) = self.preserve_original { + params = params.preserve_original(value); + } + if let Some(value) = self.index_operators { + params = params.index_operators(value); + } + params + } +} + pub fn extract_index_params(source: &Option>) -> PyResult { if let Some(source) = source { match class_name(source)?.as_str() { @@ -40,10 +116,19 @@ pub fn extract_index_params(source: &Option>) -> PyResult Ok(LanceDbIndex::Bitmap(Default::default())), "LabelList" => Ok(LanceDbIndex::LabelList(Default::default())), "Fm" => Ok(LanceDbIndex::Fm(FmIndexBuilder::default())), + "NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())), "FTS" => { let params = source.extract::()?; + let code_options = CodeAnalyzerOptions { + analyzer: params.analyzer, + split_identifiers: params.split_identifiers, + split_on_numerics: params.split_on_numerics, + preserve_original: params.preserve_original, + index_operators: params.index_operators, + }; + let base_tokenizer = code_options.resolve_base_tokenizer(params.base_tokenizer)?; let mut inner_opts = FtsIndexBuilder::default() - .base_tokenizer(params.base_tokenizer) + .base_tokenizer(base_tokenizer) .language(¶ms.language) .map_err(|_| { PyValueError::new_err(format!( @@ -75,6 +160,7 @@ pub fn extract_index_params(source: &Option>) -> PyResult>) -> PyResult Err(PyValueError::new_err(format!( - "Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat", + "Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat", not_supported ))), } @@ -232,6 +318,11 @@ struct FtsParams { memory_limit: Option, num_workers: Option, document_granularity: String, + analyzer: Option, + split_identifiers: Option, + split_on_numerics: Option, + preserve_original: Option, + index_operators: Option, } #[derive(FromPyObject)] @@ -493,6 +584,11 @@ mod tests { memory_limit = 2048 num_workers = 7 document_granularity = 'row' + analyzer = None + split_identifiers = None + split_on_numerics = None + preserve_original = None + index_operators = None config = FTS()", None, diff --git a/python/src/job.rs b/python/src/job.rs index 1740b3e00..79a9cd524 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -10,7 +10,7 @@ use arrow::{ }; use lancedb::job::JobEventsRequest; use pyo3::{ - Bound, PyAny, PyRef, PyResult, Python, + Bound, Py, PyAny, PyRef, PyResult, Python, exceptions::PyValueError, pyclass, pymethods, types::{PyAnyMethods, PyDict, PyDictMethods}, @@ -94,10 +94,30 @@ impl Job { ) } - pub fn wait(self_: PyRef<'_, Self>) -> PyResult> { + #[pyo3(signature = (progress=None))] + pub fn wait(self_: PyRef<'_, Self>, progress: Option>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - let result = inner.wait().await.infer_error()?; + let result = if let Some(progress) = progress { + let observer = move |description: &lancedb::database::JobDescription| { + Python::attach(|py| { + let snapshot = description.progress_snapshot(); + let callback_result: PyResult<()> = (|| { + let raw = snapshot.to_string(); + let parsed = parse_json_payload(py, Some(&raw))? + .ok_or_else(|| PyValueError::new_err("missing progress"))?; + progress.bind(py).call1((parsed,))?; + Ok(()) + })(); + if let Err(error) = callback_result { + log::warn!("job progress callback error: {error}"); + } + }); + }; + inner.wait_with_progress(observer).await.infer_error()? + } else { + inner.wait().await.infer_error()? + }; result .map_err(|message| lancedb::Error::Runtime { message }) .infer_error() @@ -164,6 +184,8 @@ pub struct JobInfo { job_type: String, state: String, created_at_millis: i64, + _progress_json: Option, + paused: bool, } #[pymethods] @@ -174,16 +196,32 @@ impl JobInfo { self.job_id, self.table, self.job_type, self.state, self.created_at_millis ) } + + /// Structured progress for job types that report it. Missing fields are + /// unknown, not zero. + #[getter] + fn progress<'py>(&self, py: Python<'py>) -> PyResult>> { + parse_json_payload(py, self._progress_json.as_deref()) + } + + /// Whether an operator has parked this job. + #[getter] + fn paused(&self) -> bool { + self.paused + } } impl From for JobInfo { fn from(info: lancedb::database::JobInfo) -> Self { + let progress = info.progress_snapshot().to_string(); Self { job_id: info.job_id, table: info.table, job_type: info.job_type, state: info.state, created_at_millis: info.created_at_millis, + _progress_json: Some(progress), + paused: info.paused, } } } @@ -194,15 +232,35 @@ impl From for JobInfo { pub struct JobFailureInfo { phase: Option, message: Option, + /// User-code traceback, possibly truncated by the server. + traceback: Option, retryable: Option, + sql_job_id: Option, } #[pymethods] impl JobFailureInfo { fn __repr__(&self) -> String { + let phase = self + .phase + .as_ref() + .map_or_else(|| "None".to_string(), |value| format!("{value:?}")); + let message = self + .message + .as_ref() + .map_or_else(|| "None".to_string(), |value| format!("{value:?}")); + let retryable = match self.retryable { + Some(true) => "True", + Some(false) => "False", + None => "None", + }; + let sql_job_id = self + .sql_job_id + .as_ref() + .map_or_else(|| "None".to_string(), |value| format!("{value:?}")); format!( - "JobFailureInfo(phase={:?}, message={:?}, retryable={:?})", - self.phase, self.message, self.retryable + "JobFailureInfo(phase={phase}, message={message}, retryable={retryable}, \ + sql_job_id={sql_job_id})" ) } } @@ -219,6 +277,7 @@ pub struct JobDescription { _spec_json: Option, /// Internal: the wire form behind the `result` property. _result_json: Option, + _progress_json: Option, failure: Option, } @@ -236,6 +295,13 @@ impl JobDescription { parse_json_payload(py, self._result_json.as_deref()) } + /// Structured progress snapshot. Lifecycle and queue fields are present + /// even when a job type or older server supplies no counters. + #[getter] + fn progress<'py>(&self, py: Python<'py>) -> PyResult>> { + parse_json_payload(py, self._progress_json.as_deref()) + } + fn __repr__(&self, py: Python<'_>) -> PyResult { let mut fields = vec![ format!("job_id={:?}", self.job_id), @@ -263,6 +329,7 @@ impl JobDescription { impl From for JobDescription { fn from(description: lancedb::database::JobDescription) -> Self { + let progress_json = description.progress_snapshot().to_string(); Self { job_id: description.job_id, job_type: description.job_type, @@ -273,10 +340,13 @@ impl From for JobDescription { .result .filter(|result| !result.is_null()) .map(|result| result.to_string()), + _progress_json: Some(progress_json), failure: description.failure.map(|failure| JobFailureInfo { phase: failure.phase, message: failure.message, + traceback: failure.traceback, retryable: failure.retryable, + sql_job_id: failure.sql_job_id, }), } } diff --git a/python/src/lib.rs b/python/src/lib.rs index 71662add1..27ff4cb01 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -58,13 +58,31 @@ fn shutdown_runtime(py: Python<'_>) { py.detach(|| runtime::shutdown(std::time::Duration::from_secs(5))); } +#[pyfunction] +fn _doc_url(campaign: &str) -> PyResult { + let link = lancedb::docs::DocLink::from_campaign(campaign).ok_or_else(|| { + pyo3::exceptions::PyValueError::new_err(format!("unknown doc link campaign: {campaign}")) + })?; + Ok(link.url()) +} + +#[pyfunction] +fn _append_doc_url(message: &str, campaign: &str) -> PyResult { + let link = lancedb::docs::DocLink::from_campaign(campaign).ok_or_else(|| { + pyo3::exceptions::PyValueError::new_err(format!("unknown doc link campaign: {campaign}")) + })?; + Ok(link.append_to(message)) +} + #[pymodule] pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { + lancedb::docs::set_sdk_ident("python", env!("CARGO_PKG_VERSION")); let env = Env::new() .filter_or("LANCEDB_LOG", "warn") .write_style("LANCEDB_LOG_STYLE"); env_logger::init_from_env(env); m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; @@ -127,10 +145,14 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(table::tokenize, m)?)?; m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?; m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?; + m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?; + m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?; m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?; m.add_function(wrap_pyfunction!(expr_col, m)?)?; m.add_function(wrap_pyfunction!(expr_lit, m)?)?; m.add_function(wrap_pyfunction!(expr_func, m)?)?; + m.add_function(wrap_pyfunction!(_doc_url, m)?)?; + m.add_function(wrap_pyfunction!(_append_doc_url, m)?)?; m.add("__version__", env!("CARGO_PKG_VERSION"))?; m.add( "_experimental_functions_enabled", diff --git a/python/src/namespace.rs b/python/src/namespace.rs index bb0e4d6d3..bbb0233ec 100644 --- a/python/src/namespace.rs +++ b/python/src/namespace.rs @@ -70,7 +70,11 @@ fn get_dict_with_model_dump_class(py: Python<'_>) -> PyResult> py.run( c"class DictWithModelDump(dict): def model_dump(self): - return dict(self)", + return dict(self) + def __getattr__(self, name): + if name.startswith('__'): + raise AttributeError(name) + return self.get(name)", None, Some(&locals), )?; diff --git a/python/src/oauth.rs b/python/src/oauth.rs index 1639f239a..08be6ac05 100644 --- a/python/src/oauth.rs +++ b/python/src/oauth.rs @@ -67,7 +67,7 @@ impl TryFrom for OAuthConfig { } OAuthFlow::AuthorizationCode(options) } - "device_code" => OAuthFlow::DeviceCode, + "device_code" => OAuthFlow::DeviceCode(Default::default()), "azure_managed_identity" => OAuthFlow::AzureManagedIdentity { client_id: py.managed_identity_client_id, }, @@ -327,7 +327,7 @@ mod tests { fn test_device_code_conversion() { let config = base_config(); let converted = OAuthConfig::try_from(config).unwrap(); - assert!(matches!(converted.flow, OAuthFlow::DeviceCode)); + assert!(matches!(converted.flow, OAuthFlow::DeviceCode(options) if !options.use_pkce)); } #[test] diff --git a/python/src/query.rs b/python/src/query.rs index 8687b3756..2097dac69 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -16,6 +16,7 @@ use arrow::array::make_array; use arrow::pyarrow::FromPyArrow; use arrow::pyarrow::IntoPyArrow; use arrow::pyarrow::ToPyArrow; +use lancedb::ApproxMode; use lancedb::index::scalar::{ BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery, FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery, @@ -354,6 +355,7 @@ pub struct PyQueryRequest { pub limit: Option, pub offset: Option, pub take_offsets: Option>, + pub take_row_ids: Option>, pub filter: Option, pub full_text_search: Option>, pub select: PySelect, @@ -370,6 +372,7 @@ pub struct PyQueryRequest { pub lower_bound: Option, pub upper_bound: Option, pub ef: Option, + pub approx_mode: Option, pub refine_factor: Option, pub distance_type: Option, pub bypass_vector_index: Option, @@ -385,6 +388,7 @@ impl From for PyQueryRequest { limit: query_request.limit, offset: query_request.offset, take_offsets: query_request.take_offsets, + take_row_ids: query_request.take_row_ids, filter: query_request.filter.map(PyQueryFilter), full_text_search: query_request .full_text_search @@ -403,6 +407,7 @@ impl From for PyQueryRequest { lower_bound: None, upper_bound: None, ef: None, + approx_mode: None, refine_factor: None, distance_type: None, bypass_vector_index: None, @@ -416,6 +421,7 @@ impl From for PyQueryRequest { 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, filter: vector_query.base.filter.map(PyQueryFilter), full_text_search: None, select_source_columns: PySelect::source_columns(&vector_query.base.select), @@ -432,6 +438,7 @@ impl From for PyQueryRequest { lower_bound: vector_query.lower_bound, upper_bound: vector_query.upper_bound, ef: vector_query.ef, + approx_mode: vector_query.approx_mode.map(|m| m.to_string()), refine_factor: vector_query.refine_factor, distance_type: vector_query.distance_type.map(|d| d.to_string()), bypass_vector_index: Some(!vector_query.use_index), @@ -1069,6 +1076,12 @@ impl VectorQuery { self.inner = self.inner.clone().ef(ef as usize); } + pub fn approx_mode(&mut self, approx_mode: String) -> PyResult<()> { + let approx_mode = ApproxMode::try_from(approx_mode.as_str()).infer_error()?; + self.inner = self.inner.clone().approx_mode(approx_mode); + Ok(()) + } + pub fn bypass_vector_index(&mut self) { self.inner = self.inner.clone().bypass_vector_index() } @@ -1246,6 +1259,10 @@ impl HybridQuery { self.inner_vec.ef(ef); } + pub fn approx_mode(&mut self, approx_mode: String) -> PyResult<()> { + self.inner_vec.approx_mode(approx_mode) + } + pub fn bypass_vector_index(&mut self) { self.inner_vec.bypass_vector_index(); } @@ -1291,6 +1308,7 @@ impl HybridQuery { req.maximum_nprobes = vec_req.maximum_nprobes; req.search_effort = vec_req.search_effort; req.ef = vec_req.ef; + req.approx_mode = vec_req.approx_mode; req.refine_factor = vec_req.refine_factor; req.lower_bound = vec_req.lower_bound; req.upper_bound = vec_req.upper_bound; diff --git a/python/src/table.rs b/python/src/table.rs index e7e72bd73..a4af55161 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -14,12 +14,12 @@ use crate::{ connection::Connection, error::PythonErrorExt, expr::PyExpr, - index::{IndexConfig, extract_index_params}, + index::{CodeAnalyzerOptions, IndexConfig, extract_index_params}, query::{Query, TakeQuery}, table::scannable::PyScannable, }; use arrow::{ - array::{Array, LargeBinaryArray}, + array::{Array, LargeBinaryArray, RecordBatchIterator, RecordBatchReader}, datatypes::{DataType, Schema}, ffi_stream::ArrowArrayStreamReader, pyarrow::{FromPyArrow, PyArrowType, ToPyArrow}, @@ -29,8 +29,8 @@ use lancedb::connection::LanceFileVersion; use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration, - FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform, - OptimizeAction, OptimizeOptions, Ref, Table as LanceDbTable, + FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform, Ref, + RefreshColumnOptions, Table as LanceDbTable, }; use lancedb::tokenize as lancedb_tokenize; use pyo3::{ @@ -42,6 +42,95 @@ use pyo3::{ mod scannable; +/// Keyword arguments shared by `refresh_column` and `refresh_column_async`. +struct RefreshColumnArgs { + where_clause: Option, + batch_size: Option, + gpu_class: Option, + gpu_count: Option, + retry_policy: Option, + error_policy: Option, + max_failed_fraction: Option, + max_failed_rows: Option, + row_timeout_seconds: Option, + init_timeout_seconds: Option, + num_workers: Option, + max_executor_processes_per_worker: Option, +} + +fn positive_count>(value: Option, name: &str) -> PyResult> { + value + .map(|v| { + T::try_from(v) + .ok() + .filter(|_| v > 0) + .ok_or_else(|| PyValueError::new_err(format!("{name} must be greater than zero"))) + }) + .transpose() +} + +fn refresh_column_options(args: RefreshColumnArgs) -> PyResult { + let RefreshColumnArgs { + where_clause, + batch_size, + gpu_class, + gpu_count, + retry_policy, + error_policy, + max_failed_fraction, + max_failed_rows, + row_timeout_seconds, + init_timeout_seconds, + num_workers, + max_executor_processes_per_worker, + } = args; + let mut options = RefreshColumnOptions::default(); + options.where_clause = where_clause; + options.max_failed_fraction = max_failed_fraction; + options.max_failed_rows = max_failed_rows + .map(u64::try_from) + .transpose() + .map_err(|_| PyValueError::new_err("max_failed_rows must be a non-negative integer"))?; + options.row_timeout_seconds = row_timeout_seconds; + options.init_timeout_seconds = init_timeout_seconds; + options.num_workers = positive_count(num_workers, "num_workers")?; + options.max_executor_processes_per_worker = positive_count( + max_executor_processes_per_worker, + "max_executor_processes_per_worker", + )?; + options.retry_policy = retry_policy + .map(|json| { + serde_json::from_str(&json) + .map_err(|error| PyValueError::new_err(format!("invalid retry_policy: {error}"))) + }) + .transpose()?; + options.error_policy = error_policy + .map(|value| { + serde_json::from_value(serde_json::Value::String(value)) + .map_err(|error| PyValueError::new_err(format!("invalid error_policy: {error}"))) + }) + .transpose()?; + options.batch_size = batch_size + .map(usize::try_from) + .transpose() + .map_err(|_| PyValueError::new_err("batch_size must be greater than zero"))?; + options.gpu_class = gpu_class; + options.gpu_count = gpu_count + .map(|count| { + u32::try_from(count) + .ok() + .filter(|count| *count > 0) + .ok_or_else(|| { + PyValueError::new_err( + "gpu_count must be a positive integer no greater than u32::MAX", + ) + }) + }) + .transpose()?; + options.validate().infer_error()?; + Ok(options) +} + /// Convert `RTEStats` to a Python dict, preserving the per-table-shard list. /// /// Deliberately not flattened to a table-level summary: a table is N @@ -584,27 +673,39 @@ impl From for RefreshColumnResult { #[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FunctionErrorRecord { + pub attempts: Option, pub job_id: String, pub fragment_id: u64, pub row_offset: Option, + pub row_id: Option, + pub row_address: Option, pub column: String, pub function: String, pub function_version: String, pub table_version: u64, pub error_type: String, pub error_message: String, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, pub created_at_millis: i64, } #[pymethods] impl FunctionErrorRecord { pub fn __repr__(&self) -> String { + let row_offset = self + .row_offset + .map_or_else(|| "None".to_string(), |value| value.to_string()); + let row_address = self + .row_address + .map_or_else(|| "None".to_string(), |value| value.to_string()); format!( - "FunctionErrorRecord(job_id={:?}, fragment_id={}, row_offset={:?}, column={:?}, \ - error_type={:?}, error_message={:?})", + "FunctionErrorRecord(job_id={:?}, fragment_id={}, row_offset={}, row_address={}, \ + column={:?}, error_type={:?}, error_message={:?})", self.job_id, self.fragment_id, - self.row_offset, + row_offset, + row_address, self.column, self.error_type, self.error_message @@ -615,15 +716,19 @@ impl FunctionErrorRecord { impl From for FunctionErrorRecord { fn from(record: lancedb::function::FunctionErrorRecord) -> Self { Self { + attempts: record.attempts, job_id: record.job_id, fragment_id: record.fragment_id, row_offset: record.row_offset, + row_id: record.row_id, + row_address: record.row_address, column: record.column, function: record.function, function_version: record.function_version, table_version: record.table_version, error_type: record.error_type, error_message: record.error_message, + traceback: record.traceback, created_at_millis: record.created_at_millis, } } @@ -994,7 +1099,12 @@ impl From for FtsToken { ascii_folding = true, ngram_min_length = 3, ngram_max_length = 3, - prefix_only = false + prefix_only = false, + analyzer = None, + split_identifiers = None, + split_on_numerics = None, + preserve_original = None, + index_operators = None ))] #[allow(clippy::too_many_arguments)] pub fn tokenize( @@ -1010,7 +1120,20 @@ pub fn tokenize( ngram_min_length: u32, ngram_max_length: u32, prefix_only: bool, + analyzer: Option, + split_identifiers: Option, + split_on_numerics: Option, + preserve_original: Option, + index_operators: Option, ) -> PyResult> { + let code_options = CodeAnalyzerOptions { + analyzer, + split_identifiers, + split_on_numerics, + preserve_original, + index_operators, + }; + let base_tokenizer = code_options.resolve_base_tokenizer(base_tokenizer)?; let mut params = FtsIndexBuilder::default() .base_tokenizer(base_tokenizer) .language(&language) @@ -1033,6 +1156,7 @@ pub fn tokenize( if let Some(remove_stop_words) = remove_stop_words { params = params.remove_stop_words(remove_stop_words); } + let params = code_options.apply(params); let tokens = lancedb_tokenize(&query, ¶ms).infer_error()?; Ok(tokens.into_iter().map(FtsToken::from).collect()) } @@ -1714,6 +1838,10 @@ impl Table { compaction_options: Option<&Bound<'py, PyDict>>, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); + let target_specified = compaction_options + .map(|options| options.contains("target_rows_per_fragment")) + .transpose()? + .unwrap_or(false); let compaction_options = parse_compaction_options(compaction_options)?; let older_than = if let Some(ms) = cleanup_since_ms { if ms > i64::MAX as u64 { @@ -1728,31 +1856,24 @@ impl Table { None }; future_into_py(self_.py(), async move { - let compaction_stats = inner - .optimize(OptimizeAction::Compact { - options: compaction_options, - remap_options: None, - }) - .await - .infer_error()? - .compaction - .unwrap(); - let prune_stats = inner - .optimize(OptimizeAction::Prune { - older_than, - delete_unverified, - error_if_tagged_old_versions: None, - }) - .await - .infer_error()? - .prune - .unwrap(); - inner - .optimize(lancedb::table::OptimizeAction::Index( - OptimizeOptions::default(), - )) - .await - .infer_error()?; + let stats = if inner.as_native().is_some() { + inner + .optimize_full(compaction_options, older_than, None, delete_unverified) + .await + } else { + let mut overrides = + lancedb::table::optimize::CompactionOverrides::try_from(compaction_options) + .infer_error()?; + if !target_specified { + overrides.target_rows_per_fragment = None; + } + inner + .optimize_full_with_overrides(overrides, older_than, None, delete_unverified) + .await + } + .infer_error()?; + let compaction_stats = stats.compaction.unwrap(); + let prune_stats = stats.prune.unwrap(); Ok(OptimizeStats { compaction: CompactionStats { files_added: compaction_stats.files_added as u64, @@ -1852,6 +1973,45 @@ impl Table { }) } + pub fn get_table_overrides(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let overrides = inner.get_table_overrides().await.infer_error()?; + serde_json::to_string(&overrides).map_err(|err| { + PyRuntimeError::new_err(format!("Failed to serialize table overrides: {err}")) + }) + }) + } + + pub fn update_table_overrides<'a>( + self_: PyRef<'a, Self>, + overrides_json: String, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let overrides = serde_json::from_str(&overrides_json).map_err(|err| { + PyValueError::new_err(format!("Invalid table overrides JSON: {err}")) + })?; + let overrides = inner + .update_table_overrides(overrides) + .await + .infer_error()?; + serde_json::to_string(&overrides).map_err(|err| { + PyRuntimeError::new_err(format!("Failed to serialize table overrides: {err}")) + }) + }) + } + + pub fn reset_table_overrides(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let overrides = inner.reset_table_overrides().await.infer_error()?; + serde_json::to_string(&overrides).map_err(|err| { + PyRuntimeError::new_err(format!("Failed to serialize table overrides: {err}")) + }) + }) + } + /// Whether a hybrid query on this table has already been refused `_rowid`. /// Learned from a previous refusal, never probed, so this is free. /// @@ -1925,7 +2085,7 @@ impl Table { inner .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "uses_v2_manifest_paths is not supported in LanceDB Distributed." + message: "uses_v2_manifest_paths is not supported in LanceDB Enterprise." .into(), }) .infer_error()? @@ -1941,7 +2101,7 @@ impl Table { inner .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "migrate_manifest_paths_v2 is not supported in LanceDB Distributed." + message: "migrate_manifest_paths_v2 is not supported in LanceDB Enterprise." .into(), }) .infer_error()? @@ -1969,6 +2129,29 @@ impl Table { }) } + pub fn add_columns_from_reader<'a>( + self_: PyRef<'a, Self>, + data: Bound<'a, PyAny>, + ) -> PyResult> { + let reader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?; + let schema = reader.schema(); + // Lance's surplus-row check treats trailing empty batches as extra data. + let reader = RecordBatchIterator::new( + reader.filter(|batch| !batch.as_ref().is_ok_and(|batch| batch.num_rows() == 0)), + schema, + ); + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let result = inner + .add_columns() + .transform(NewColumnTransform::Reader(Box::new(reader))) + .execute() + .await + .infer_error()?; + Ok(AddColumnsResult::from(result)) + }) + } + #[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] pub fn add_computed_columns( self_: PyRef<'_, Self>, @@ -2026,21 +2209,86 @@ impl Table { }) } - pub fn refresh_column(self_: PyRef<'_, Self>, column: String) -> PyResult> { + #[pyo3(signature = (column, *, r#where=None, batch_size=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))] + #[allow(clippy::too_many_arguments)] + pub fn refresh_column( + self_: PyRef<'_, Self>, + column: String, + r#where: Option, + batch_size: Option, + gpu_class: Option, + gpu_count: Option, + retry_policy: Option, + error_policy: Option, + max_failed_fraction: Option, + max_failed_rows: Option, + row_timeout_seconds: Option, + init_timeout_seconds: Option, + num_workers: Option, + max_executor_processes_per_worker: Option, + ) -> PyResult> { + let options = refresh_column_options(RefreshColumnArgs { + where_clause: r#where, + batch_size, + gpu_class, + gpu_count, + retry_policy, + error_policy, + max_failed_fraction, + max_failed_rows, + row_timeout_seconds, + init_timeout_seconds, + num_workers, + max_executor_processes_per_worker, + })?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { - let result = inner.refresh_column(column).await.infer_error()?; + let result = inner + .refresh_column_with_options(column, options) + .await + .infer_error()?; Ok(RefreshColumnResult::from(result)) }) } + #[pyo3(signature = (column, *, r#where=None, batch_size=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))] + #[allow(clippy::too_many_arguments)] pub fn refresh_column_async( self_: PyRef<'_, Self>, column: String, + r#where: Option, + batch_size: Option, + gpu_class: Option, + gpu_count: Option, + retry_policy: Option, + error_policy: Option, + max_failed_fraction: Option, + max_failed_rows: Option, + row_timeout_seconds: Option, + init_timeout_seconds: Option, + num_workers: Option, + max_executor_processes_per_worker: Option, ) -> PyResult> { + let options = refresh_column_options(RefreshColumnArgs { + where_clause: r#where, + batch_size, + gpu_class, + gpu_count, + retry_policy, + error_policy, + max_failed_fraction, + max_failed_rows, + row_timeout_seconds, + init_timeout_seconds, + num_workers, + max_executor_processes_per_worker, + })?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { - let job = inner.refresh_column_async(column).await.infer_error()?; + let job = inner + .refresh_column_async_with_options(column, options) + .await + .infer_error()?; Ok(crate::job::Job::new_typed(job)) }) } @@ -2064,11 +2312,16 @@ impl Table { }) } - #[pyo3(signature = (source_version=None, *, full=false))] + #[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=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, + gpu_class: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2076,6 +2329,18 @@ 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) = memory_bytes { + builder = builder.memory_bytes(value); + } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } + if let Some(value) = gpu_class { + builder = builder.gpu_class(value); + } if let Some(version) = source_version { builder = builder.source_version(version); } @@ -2084,11 +2349,16 @@ impl Table { }) } - #[pyo3(signature = (source_version=None, *, full=false))] + #[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=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, + gpu_class: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2096,6 +2366,18 @@ 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) = memory_bytes { + builder = builder.memory_bytes(value); + } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } + if let Some(value) = gpu_class { + builder = builder.gpu_class(value); + } if let Some(version) = source_version { builder = builder.source_version(version); } diff --git a/python/src/util.rs b/python/src/util.rs index 977608a73..a956066f1 100644 --- a/python/src/util.rs +++ b/python/src/util.rs @@ -61,6 +61,23 @@ pub fn validate_table_name(table_name: &str) -> PyResult<()> { .map_err(|e| PyValueError::new_err(e.to_string())) } +/// Parse field references with the same identifier syntax as Lance writes. +#[pyfunction(name = "_parse_field_path")] +pub fn parse_field_path(path: &str) -> PyResult> { + lance_core::datatypes::parse_field_path(path).map_err(|e| PyValueError::new_err(e.to_string())) +} + /// A wrapper around a LanceDB type to allow it to be used in Python #[derive(Debug, Clone)] pub struct PyLanceDB(pub T); +/// Validate the Function retry wire contract using the same rules as Rust APIs. +#[pyo3::pyfunction] +pub fn validate_function_retry_policy(json: &str) -> pyo3::PyResult<()> { + let policy: lancedb::function::FunctionRetryPolicy = + serde_json::from_str(json).map_err(|error| { + pyo3::exceptions::PyValueError::new_err(format!("invalid retry_policy: {error}")) + })?; + policy + .validate() + .map_err(|error| pyo3::exceptions::PyValueError::new_err(error.to_string())) +} diff --git a/python/uv.lock b/python/uv.lock index 9101dba74..2cd4ac496 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -4,10 +4,18 @@ requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.12' and python_full_version < '3.14'", - "python_full_version == '3.11.*'", - "python_full_version < '3.11'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", ] [[package]] @@ -224,16 +232,16 @@ wheels = [ [[package]] name = "anyio" -version = "4.14.1" +version = "4.16.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "idna" }, - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions", marker = "python_full_version < '3.15'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/3b/72/5562aabb8dd7181e8e860622a38bea08d17842b99ecd4c91f84ac95251b0/anyio-4.14.1.tar.gz", hash = "sha256:8d648a3544c1a700e3ff78615cd679e4c5c3f149904287e73687b2596963629e", size = 254831, upload-time = "2026-06-24T20:56:06.017Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/7b/90df4a0a816d98d6ea26f559d87836d494a2cf1fcf063be67df50a7bcc30/anyio-4.14.1-py3-none-any.whl", hash = "sha256:4e5533c5b8ff0a24f5d7a176cbe6877129cd183893f66b537f8f227d10527d72", size = 124875, upload-time = "2026-06-24T20:56:04.413Z" }, + { url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" }, ] [[package]] @@ -245,6 +253,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/81/29/5ecc3a15d5a33e31b26c11426c45c501e439cb865d0bff96315d86443b78/appnope-0.1.4-py2.py3-none-any.whl", hash = "sha256:502575ee11cd7a28c0205f379b525beefebab9d161b7c964670864014ed7213c", size = 4321, upload-time = "2024-02-06T09:43:09.663Z" }, ] +[[package]] +name = "asn1crypto" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/de/cf/d547feed25b5244fcb9392e288ff9fdc3280b10260362fc45d37a798a6ee/asn1crypto-1.5.1.tar.gz", hash = "sha256:13ae38502be632115abf8a24cbe5f4da52e3b5231990aff31123c805306ccb9c", size = 121080, upload-time = "2022-03-15T14:46:52.889Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/7f/09065fd9e27da0eda08b4d6897f1c13535066174cc023af248fc2a8d5e5a/asn1crypto-1.5.1-py2.py3-none-any.whl", hash = "sha256:db4e40728b728508912cbb3d44f19ce188f218e9eba635821bb4b68564f8fd67", size = 105045, upload-time = "2022-03-15T14:46:51.055Z" }, +] + [[package]] name = "asttokens" version = "3.0.1" @@ -656,6 +673,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/23/52/d5bee5b6ea81882d549b566d2545b044bbcbc33fe5fbe001008a7e745a21/charset_normalizer-3.4.8-py3-none-any.whl", hash = "sha256:b7c1fb310df524e01fbe84d43b7f95aa4f808f8eaa0dafc185f64ba395e37d54", size = 64279, upload-time = "2026-07-06T15:27:57.043Z" }, ] +[[package]] +name = "circuitbreaker" +version = "2.1.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/df/ac/de7a92c4ed39cba31fe5ad9203b76a25ca67c530797f6bb420fff5f65ccb/circuitbreaker-2.1.3.tar.gz", hash = "sha256:1a4baee510f7bea3c91b194dcce7c07805fe96c4423ed5594b75af438531d084", size = 10787, upload-time = "2025-03-31T08:12:08.963Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ae/34/15f08edd4628f65217de1fc3c1a27c82e46fe357d60c217fc9881e12ebcc/circuitbreaker-2.1.3-py3-none-any.whl", hash = "sha256:87ba6a3ed03fdc7032bc175561c2b04d52ade9d5faf94ca2b035fbdc5e6b1dd1", size = 7737, upload-time = "2025-03-31T08:12:07.802Z" }, +] + [[package]] name = "click" version = "8.4.2" @@ -714,7 +740,8 @@ dependencies = [ { 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 = "peft" }, - { name = "pillow" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "requests" }, { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, @@ -737,61 +764,150 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/60/97/891a0971e1e4a8c5d2b20bbe0e524dc04548d2307fee33cdeba148fd4fc7/comm-0.2.3-py3-none-any.whl", hash = "sha256:c615d91d75f7f04f095b30d1c1711babd43bdc6419c1be9886a85f2f4e489417", size = 7294, upload-time = "2025-07-25T14:02:02.896Z" }, ] +[[package]] +name = "crc32c" +version = "2.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/66/7e97aa77af7cf6afbff26e3651b564fe41932599bc2d3dce0b2f73d4829a/crc32c-2.8.tar.gz", hash = "sha256:578728964e59c47c356aeeedee6220e021e124b9d3e8631d95d9a5e5f06e261c", size = 48179, upload-time = "2025-10-17T06:20:13.61Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c4/a0/28b4686a8db0bb0f77970f4c6ccede90d1d5740a1d4b4703bd54c3e75655/crc32c-2.8-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:2c0f4eb01fe7c0a3e3f973a418e04d52101bb077dd77626fd80c658ec60aaf95", size = 66321, upload-time = "2025-10-17T06:18:53.543Z" }, + { url = "https://files.pythonhosted.org/packages/76/1f/1697f5b8b770f715ed9b264d79e36b4f77ae0527f81f3c749ef08937a32e/crc32c-2.8-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6baefcfbca82b1a9678455416da24f18629769a76920c640d5a538620a7d12bb", size = 62985, upload-time = "2025-10-17T06:18:54.97Z" }, + { url = "https://files.pythonhosted.org/packages/e0/e5/333cfa5ffa8d5779733aced2b984b5e5139b4a8ceaa2c6bc563e9a1092f3/crc32c-2.8-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d7f959fcf6c5aad1c4a653ee1a50f05760dab1d1c35d98ec4d7f0f68643f7612", size = 61517, upload-time = "2025-10-17T06:18:55.795Z" }, + { url = "https://files.pythonhosted.org/packages/e1/d8/362a009e8140dd926a153b44d56753e3aa7cb50aca243779a84adadbff11/crc32c-2.8-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9bb678507a4e4cf3f0506607b046ecc4ed1c58a19e08a3fb3c2d25441c480bf1", size = 79385, upload-time = "2025-10-17T06:18:56.598Z" }, + { url = "https://files.pythonhosted.org/packages/4a/9f/0d4ea3aa71ffb15f1285669d23024cc40779388ce32157d339dc2584491c/crc32c-2.8-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1a16f7ffa4c242a909558565567cbba95148603717b53538ea299c98da68e7a9", size = 80965, upload-time = "2025-10-17T06:18:57.384Z" }, + { url = "https://files.pythonhosted.org/packages/20/44/d77657aaca4a2c0283f2356a3da6f8e91b003567bb8f09daaf540cbf192f/crc32c-2.8-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:0184369aad562d801f91f454c81f56b9ecb966f6b96684c4d6cf82fc8741d2ad", size = 79993, upload-time = "2025-10-17T06:18:58.503Z" }, + { url = "https://files.pythonhosted.org/packages/ab/c0/07017a93ebf85d9408028b7e03ef96d5c6bfb14cb77cfe90d35eedcc1501/crc32c-2.8-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:86d2eeb5f0189bd803720abe7387019328ea34c4acde62999e5723f789bc316b", size = 79243, upload-time = "2025-10-17T06:18:59.273Z" }, + { url = "https://files.pythonhosted.org/packages/c7/1a/b3c5ac4cf2fd1f82395173d0bd8e1a15d09f0bc1eccdf10ea7f8caaccd67/crc32c-2.8-cp310-cp310-win32.whl", hash = "sha256:51da61904a9e753780a2e6011885677d601db1fa840be4b68799643a113e6f08", size = 64888, upload-time = "2025-10-17T06:19:00.089Z" }, + { url = "https://files.pythonhosted.org/packages/b6/f2/60c45fc7bb2221d3c93c7a872e921be591f40d45228fe46f879b1d8c0424/crc32c-2.8-cp310-cp310-win_amd64.whl", hash = "sha256:b2d6a1f2500daaf2e4b08f97ad0349aa2eff5faaaa5fd3350314a26eade334cd", size = 66639, upload-time = "2025-10-17T06:19:00.974Z" }, + { url = "https://files.pythonhosted.org/packages/dc/0b/5e03b22d913698e9cc563f39b9f6bbd508606bf6b8e9122cd6bf196b87ea/crc32c-2.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:e560a97fbb96c9897cb1d9b5076ef12fc12e2e25622530a1afd0de4240f17e1f", size = 66329, upload-time = "2025-10-17T06:19:01.771Z" }, + { url = "https://files.pythonhosted.org/packages/6b/38/2fe0051ffe8c6a650c8b1ac0da31b8802d1dbe5fa40a84e4b6b6f5583db5/crc32c-2.8-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6762d276d90331a490ef7e71ffee53b9c0eb053bd75a272d786f3b08d3fe3671", size = 62988, upload-time = "2025-10-17T06:19:02.953Z" }, + { url = "https://files.pythonhosted.org/packages/3e/30/5837a71c014be83aba1469c58820d287fc836512a0cad6b8fdd43868accd/crc32c-2.8-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:60670569f5ede91e39f48fb0cb4060e05b8d8704dd9e17ede930bf441b2f73ef", size = 61522, upload-time = "2025-10-17T06:19:03.796Z" }, + { url = "https://files.pythonhosted.org/packages/ca/29/63972fc1452778e2092ae998c50cbfc2fc93e3fa9798a0278650cd6169c5/crc32c-2.8-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:711743da6ccc70b3c6718c328947b0b6f34a1fe6a6c27cc6c1d69cc226bf70e9", size = 80200, upload-time = "2025-10-17T06:19:04.617Z" }, + { url = "https://files.pythonhosted.org/packages/cb/3a/60eb49d7bdada4122b3ffd45b0df54bdc1b8dd092cda4b069a287bdfcff4/crc32c-2.8-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5eb4094a2054774f13b26f21bf56792bb44fa1fcee6c6ad099387a43ffbfb4fa", size = 81757, upload-time = "2025-10-17T06:19:05.496Z" }, + { url = "https://files.pythonhosted.org/packages/f5/63/6efc1b64429ef7d23bd58b75b7ac24d15df327e3ebbe9c247a0f7b1c2ed1/crc32c-2.8-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:fff15bf2bd3e95780516baae935ed12be88deaa5ebe6143c53eb0d26a7bdc7b7", size = 80830, upload-time = "2025-10-17T06:19:06.621Z" }, + { url = "https://files.pythonhosted.org/packages/e1/eb/0ae9f436f8004f1c88f7429e659a7218a3879bd11a6b18ed1257aad7e98b/crc32c-2.8-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4c0e11e3826668121fa53e0745635baf5e4f0ded437e8ff63ea56f38fc4f970a", size = 80095, upload-time = "2025-10-17T06:19:07.381Z" }, + { url = "https://files.pythonhosted.org/packages/9e/81/4afc9d468977a4cd94a2eb62908553345009a7c0d30e74463a15d4b48ec3/crc32c-2.8-cp311-cp311-win32.whl", hash = "sha256:38f915336715d1f1353ab07d7d786f8a789b119e273aea106ba55355dfc9101d", size = 64886, upload-time = "2025-10-17T06:19:08.497Z" }, + { url = "https://files.pythonhosted.org/packages/d6/e8/94e839c9f7e767bf8479046a207afd440a08f5c59b52586e1af5e64fa4a0/crc32c-2.8-cp311-cp311-win_amd64.whl", hash = "sha256:60e0a765b1caab8d31b2ea80840639253906a9351d4b861551c8c8625ea20f86", size = 66639, upload-time = "2025-10-17T06:19:09.338Z" }, + { url = "https://files.pythonhosted.org/packages/b6/36/fd18ef23c42926b79c7003e16cb0f79043b5b179c633521343d3b499e996/crc32c-2.8-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:572ffb1b78cce3d88e8d4143e154d31044a44be42cb3f6fbbf77f1e7a941c5ab", size = 66379, upload-time = "2025-10-17T06:19:10.115Z" }, + { url = "https://files.pythonhosted.org/packages/7f/b8/c584958e53f7798dd358f5bdb1bbfc97483134f053ee399d3eeb26cca075/crc32c-2.8-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:cf827b3758ee0c4aacd21ceca0e2da83681f10295c38a10bfeb105f7d98f7a68", size = 63042, upload-time = "2025-10-17T06:19:10.946Z" }, + { url = "https://files.pythonhosted.org/packages/62/e6/6f2af0ec64a668a46c861e5bc778ea3ee42171fedfc5440f791f470fd783/crc32c-2.8-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:106fbd79013e06fa92bc3b51031694fcc1249811ed4364ef1554ee3dd2c7f5a2", size = 61528, upload-time = "2025-10-17T06:19:11.768Z" }, + { url = "https://files.pythonhosted.org/packages/17/8b/4a04bd80a024f1a23978f19ae99407783e06549e361ab56e9c08bba3c1d3/crc32c-2.8-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6dde035f91ffbfe23163e68605ee5a4bb8ceebd71ed54bb1fb1d0526cdd125a2", size = 80028, upload-time = "2025-10-17T06:19:12.554Z" }, + { url = "https://files.pythonhosted.org/packages/21/8f/01c7afdc76ac2007d0e6a98e7300b4470b170480f8188475b597d1f4b4c6/crc32c-2.8-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e41ebe7c2f0fdcd9f3a3fd206989a36b460b4d3f24816d53e5be6c7dba72c5e1", size = 81531, upload-time = "2025-10-17T06:19:13.406Z" }, + { url = "https://files.pythonhosted.org/packages/32/2b/8f78c5a8cc66486be5f51b6f038fc347c3ba748d3ea68be17a014283c331/crc32c-2.8-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ecf66cf90266d9c15cea597d5cc86c01917cd1a238dc3c51420c7886fa750d7e", size = 80608, upload-time = "2025-10-17T06:19:14.223Z" }, + { url = "https://files.pythonhosted.org/packages/db/86/fad1a94cdeeeb6b6e2323c87f970186e74bfd6fbfbc247bf5c88ad0873d5/crc32c-2.8-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:59eee5f3a69ad0793d5fa9cdc9b9d743b0cd50edf7fccc0a3988a821fef0208c", size = 79886, upload-time = "2025-10-17T06:19:15.345Z" }, + { url = "https://files.pythonhosted.org/packages/d5/db/1a7cb6757a1e32376fa2dfce00c815ea4ee614a94f9bff8228e37420c183/crc32c-2.8-cp312-cp312-win32.whl", hash = "sha256:a73d03ce3604aa5d7a2698e9057a0eef69f529c46497b27ee1c38158e90ceb76", size = 64896, upload-time = "2025-10-17T06:19:16.457Z" }, + { url = "https://files.pythonhosted.org/packages/bf/8e/2024de34399b2e401a37dcb54b224b56c747b0dc46de4966886827b4d370/crc32c-2.8-cp312-cp312-win_amd64.whl", hash = "sha256:56b3b7d015247962cf58186e06d18c3d75a1a63d709d3233509e1c50a2d36aa2", size = 66645, upload-time = "2025-10-17T06:19:17.235Z" }, + { url = "https://files.pythonhosted.org/packages/e8/d8/3ae227890b3be40955a7144106ef4dd97d6123a82c2a5310cdab58ca49d8/crc32c-2.8-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:36f1e03ee9e9c6938e67d3bcb60e36f260170aa5f37da1185e04ef37b56af395", size = 66380, upload-time = "2025-10-17T06:19:18.009Z" }, + { url = "https://files.pythonhosted.org/packages/bd/8b/178d3f987cd0e049b484615512d3f91f3d2caeeb8ff336bb5896ae317438/crc32c-2.8-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b2f3226b94b85a8dd9b3533601d7a63e9e3e8edf03a8a169830ee8303a199aeb", size = 63048, upload-time = "2025-10-17T06:19:18.853Z" }, + { url = "https://files.pythonhosted.org/packages/f2/a1/48145ae2545ebc0169d3283ebe882da580ea4606bfb67cf4ca922ac3cfc3/crc32c-2.8-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6e08628bc72d5b6bc8e0730e8f142194b610e780a98c58cb6698e665cb885a5b", size = 61530, upload-time = "2025-10-17T06:19:19.974Z" }, + { url = "https://files.pythonhosted.org/packages/06/4b/cf05ed9d934cc30e5ae22f97c8272face420a476090e736615d9a6b53de0/crc32c-2.8-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:086f64793c5ec856d1ab31a026d52ad2b895ac83d7a38fce557d74eb857f0a82", size = 80001, upload-time = "2025-10-17T06:19:20.784Z" }, + { url = "https://files.pythonhosted.org/packages/15/ab/4b04801739faf36345f6ba1920be5b1c70282fec52f8280afd3613fb13e2/crc32c-2.8-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bcf72ee7e0135b3d941c34bb2c26c3fc6bc207106b49fd89aaafaeae223ae209", size = 81543, upload-time = "2025-10-17T06:19:21.557Z" }, + { url = "https://files.pythonhosted.org/packages/a9/1b/6e38dde5bfd2ea69b7f2ab6ec229fcd972a53d39e2db4efe75c0ac0382ce/crc32c-2.8-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:8a717dd9c3fd777d9bc6603717eae172887d402c4ab589d124ebd0184a83f89e", size = 80644, upload-time = "2025-10-17T06:19:22.325Z" }, + { url = "https://files.pythonhosted.org/packages/ce/45/012176ffee90059ae8ec7131019c71724ea472aa63e72c0c8edbd1fad1d7/crc32c-2.8-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:0450bb845b3c3c7b9bdc0b4e95620ec9a40824abdc8c86d6285c919a90743c1a", size = 79919, upload-time = "2025-10-17T06:19:23.101Z" }, + { url = "https://files.pythonhosted.org/packages/f0/2b/f557629842f9dec2b3461cb3a0d854bb586ec45b814cea58b082c32f0dde/crc32c-2.8-cp313-cp313-win32.whl", hash = "sha256:765d220bfcbcffa6598ac11eb1e10af0ee4802b49fe126aa6bf79f8ddb9931d1", size = 64896, upload-time = "2025-10-17T06:19:23.88Z" }, + { url = "https://files.pythonhosted.org/packages/d0/db/fd0f698c15d1e21d47c64181a98290665a08fcbb3940cd559e9c15bda57e/crc32c-2.8-cp313-cp313-win_amd64.whl", hash = "sha256:171ff0260d112c62abcce29332986950a57bddee514e0a2418bfde493ea06bb3", size = 66646, upload-time = "2025-10-17T06:19:24.702Z" }, + { url = "https://files.pythonhosted.org/packages/db/b9/8e5d7054fe8e7eecab10fd0c8e7ffb01439417bdb6de1d66a81c38fc4a20/crc32c-2.8-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:b977a32a3708d6f51703c8557008f190aaa434d7347431efb0e86fcbe78c2a50", size = 66203, upload-time = "2025-10-17T06:19:25.872Z" }, + { url = "https://files.pythonhosted.org/packages/55/5f/cc926c70057a63cc0c98a3c8a896eb15fc7e74d3034eadd53c94917c6cc3/crc32c-2.8-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:7399b01db4adaf41da2fb36fe2408e75a8d82a179a9564ed7619412e427b26d6", size = 62956, upload-time = "2025-10-17T06:19:26.652Z" }, + { url = "https://files.pythonhosted.org/packages/a1/8a/0660c44a2dd2cb6ccbb529eb363b9280f5c766f1017bc8355ed8d695bd94/crc32c-2.8-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4379f73f9cdad31958a673d11a332ec725ca71572401ca865867229f5f15e853", size = 61442, upload-time = "2025-10-17T06:19:27.74Z" }, + { url = "https://files.pythonhosted.org/packages/f5/5a/6108d2dfc0fe33522ce83ba07aed4b22014911b387afa228808a278e27cd/crc32c-2.8-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2e68264555fab19bab08331550dab58573e351a63ed79c869d455edd3b0aa417", size = 79109, upload-time = "2025-10-17T06:19:28.535Z" }, + { url = "https://files.pythonhosted.org/packages/84/1e/c054f9e390090c197abf3d2936f4f9effaf0c6ee14569ae03d6ddf86958a/crc32c-2.8-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b48f2486727b8d0e7ccbae4a34cb0300498433d2a9d6b49cb13cb57c2e3f19cb", size = 80987, upload-time = "2025-10-17T06:19:29.305Z" }, + { url = "https://files.pythonhosted.org/packages/c8/ad/1650e5c3341e4a485f800ea83116d72965030c5d48ccc168fcc685756e4d/crc32c-2.8-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:ecf123348934a086df8c8fde7f9f2d716d523ca0707c5a1367b8bb00d8134823", size = 79994, upload-time = "2025-10-17T06:19:30.109Z" }, + { url = "https://files.pythonhosted.org/packages/d7/3b/f2ed924b177729cbb2ab30ca2902abff653c31d48c95e7b66717a9ca9fcc/crc32c-2.8-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:e636ac60f76de538f7a2c0d0f3abf43104ee83a8f5e516f6345dc283ed1a4df7", size = 79046, upload-time = "2025-10-17T06:19:30.894Z" }, + { url = "https://files.pythonhosted.org/packages/4b/80/413b05ee6ace613208b31b3670c3135ee1cf451f0e72a9c839b4946acc04/crc32c-2.8-cp313-cp313t-win32.whl", hash = "sha256:8dd4a19505e0253892e1b2f1425cc3bd47f79ae5a04cb8800315d00aad7197f2", size = 64837, upload-time = "2025-10-17T06:19:32.03Z" }, + { url = "https://files.pythonhosted.org/packages/3b/1b/85eddb6ac5b38496c4e35c20298aae627970c88c3c624a22ab33e84f16c7/crc32c-2.8-cp313-cp313t-win_amd64.whl", hash = "sha256:4bb18e4bd98fb266596523ffc6be9c5b2387b2fa4e505ec56ca36336f49cb639", size = 66574, upload-time = "2025-10-17T06:19:33.143Z" }, + { url = "https://files.pythonhosted.org/packages/aa/df/50e9079b532ff53dbfc0e66eed781374bd455af02ed5df8b56ad538de4ff/crc32c-2.8-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:3a3b2e4bcf7b3ee333050e7d3ff38e2ba46ea205f1d73d8949b248aaffe937ac", size = 66399, upload-time = "2025-10-17T06:19:34.279Z" }, + { url = "https://files.pythonhosted.org/packages/5a/2e/67e3b0bc3d30e46ea5d16365cc81203286387671e22f2307eb41f19abb9c/crc32c-2.8-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:445e559e66dff16be54f8a4ef95aa6b01db799a639956d995c5498ba513fccc2", size = 63044, upload-time = "2025-10-17T06:19:35.062Z" }, + { url = "https://files.pythonhosted.org/packages/36/ea/1723b17437e4344ed8d067456382ecb1f5b535d83fdc5aaebab676c6d273/crc32c-2.8-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:bf3040919e17afa5782e01b1875d6a05f44b8f19c05f211d8b9f8a1deb8bbd9c", size = 61541, upload-time = "2025-10-17T06:19:36.204Z" }, + { url = "https://files.pythonhosted.org/packages/4c/6a/cbec8a235c5b46a01f319939b538958662159aec0ed3a74944e3a6de21f1/crc32c-2.8-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:5607ab8221e1ffd411f64aa40dbb6850cf06dd2908c9debd05d371e1acf62ff3", size = 80139, upload-time = "2025-10-17T06:19:37.351Z" }, + { url = "https://files.pythonhosted.org/packages/21/31/d096722fe74b692d6e8206c27da1ea5f6b2a12ff92c54a62a6ba2f376254/crc32c-2.8-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7f5db4f16816926986d3c94253314920689706ae13a9bf4888b47336c6735ce", size = 81736, upload-time = "2025-10-17T06:19:38.16Z" }, + { url = "https://files.pythonhosted.org/packages/f6/a2/f75ef716ff7e3c22f385ba6ef30c5de80c19a21ebe699dc90824a1903275/crc32c-2.8-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:70b0153c4d418b673309d3529334d117e1074c4a3b2d7f676e430d72c14de67b", size = 80795, upload-time = "2025-10-17T06:19:38.948Z" }, + { url = "https://files.pythonhosted.org/packages/d8/94/6d647a12d96ab087d9b8eacee3da073f981987827d57c7072f89ffc7b6cd/crc32c-2.8-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c8933531442042438753755a5c8a9034e4d88b01da9eb796f7e151b31a7256c", size = 80042, upload-time = "2025-10-17T06:19:39.725Z" }, + { url = "https://files.pythonhosted.org/packages/cd/dc/32b8896b40a0afee7a3c040536d0da5a73e68df2be9fadd21770fd158e16/crc32c-2.8-cp314-cp314-win32.whl", hash = "sha256:cdc83a3fe6c4e5df9457294cfd643de7d95bd4e9382c1dd6ed1e0f0f9169172c", size = 64914, upload-time = "2025-10-17T06:19:40.527Z" }, + { url = "https://files.pythonhosted.org/packages/f2/b4/4308b27d307e8ecaf8dd1dcc63bbb0e47ae1826d93faa3e62d1ee00ee2d5/crc32c-2.8-cp314-cp314-win_amd64.whl", hash = "sha256:509e10035106df66770fe24b9eb8d9e32b6fb967df17744402fb67772d8b2bc7", size = 66723, upload-time = "2025-10-17T06:19:42.449Z" }, + { url = "https://files.pythonhosted.org/packages/90/d5/a19d2489fa997a143bfbbf971a5c9a43f8b1ba9e775b1fb362d8fb15260c/crc32c-2.8-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:864359a39777a07b09b28eb31337c0cc603d5c1bf0fc328c3af736a8da624ec0", size = 66201, upload-time = "2025-10-17T06:19:43.273Z" }, + { url = "https://files.pythonhosted.org/packages/98/c2/5f82f22d2c1242cb6f6fe92aa9a42991ebea86de994b8f9974d9c1d128e2/crc32c-2.8-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:14511d7cfc5d9f5e1a6c6b64caa6225c2bdc1ed00d725e9a374a3e84073ce180", size = 62956, upload-time = "2025-10-17T06:19:44.099Z" }, + { url = "https://files.pythonhosted.org/packages/9b/61/3d43d33489cf974fb78bfb3500845770e139ae6d1d83473b660bd8f79a6c/crc32c-2.8-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:918b7999b52b5dcbcea34081e9a02d46917d571921a3f209956a9a429b2e06e5", size = 61443, upload-time = "2025-10-17T06:19:44.89Z" }, + { url = "https://files.pythonhosted.org/packages/52/6d/f306ce64a352a3002f76b0fc88a1373f4541f9d34fad3668688610bab14b/crc32c-2.8-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:cc445da03fc012a5a03b71da1df1b40139729e6a5571fd4215ab40bfb39689c7", size = 79106, upload-time = "2025-10-17T06:19:45.688Z" }, + { url = "https://files.pythonhosted.org/packages/a5/b7/1f74965dd7ea762954a69d172dfb3a706049c84ffa45d31401d010a4a126/crc32c-2.8-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e3dde2ec59a8a830511d72a086ead95c0b0b7f0d418f93ea106244c5e77e350", size = 80983, upload-time = "2025-10-17T06:19:46.792Z" }, + { url = "https://files.pythonhosted.org/packages/1b/50/af93f0d91ccd61833ce77374ebfbd16f5805f5c17d18c6470976d9866d76/crc32c-2.8-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:61d51681a08b6a2a2e771b7f0cd1947fb87cb28f38ed55a01cb7c40b2ac4cdd8", size = 80009, upload-time = "2025-10-17T06:19:47.619Z" }, + { url = "https://files.pythonhosted.org/packages/ee/fa/94f394beb68a88258af694dab2f1284f55a406b615d7900bdd6235283bc4/crc32c-2.8-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:67c0716c3b1a02d5235be649487b637eed21f2d070f2b3f63f709dcd2fefb4c7", size = 79066, upload-time = "2025-10-17T06:19:48.409Z" }, + { url = "https://files.pythonhosted.org/packages/91/c6/a6050e0c64fd73c67a97da96cb59f08b05111e00b958fb87ecdce99f17ac/crc32c-2.8-cp314-cp314t-win32.whl", hash = "sha256:2e8fe863fbbd8bdb6b414a2090f1b0f52106e76e9a9c96a413495dbe5ebe492a", size = 64869, upload-time = "2025-10-17T06:19:49.197Z" }, + { url = "https://files.pythonhosted.org/packages/08/1f/c7735034e401cb1ea14f996a224518e3a3fa9987cb13680e707328a7d779/crc32c-2.8-cp314-cp314t-win_amd64.whl", hash = "sha256:20a9cfb897693eb6da19e52e2a7be2026fd4d9fc8ae318f086c0d71d5dd2d8e0", size = 66633, upload-time = "2025-10-17T06:19:50.003Z" }, + { url = "https://files.pythonhosted.org/packages/a7/1d/dd926c68eb8aac8b142a1a10b8eb62d95212c1cf81775644373fe7cceac2/crc32c-2.8-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:5833f4071da7ea182c514ba17d1eee8aec3c5be927d798222fbfbbd0f5eea02c", size = 62345, upload-time = "2025-10-17T06:20:09.39Z" }, + { url = "https://files.pythonhosted.org/packages/51/be/803404e5abea2ef2c15042edca04bbb7f625044cca879e47f186b43887c2/crc32c-2.8-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:1dc4da036126ac07b39dd9d03e93e585ec615a2ad28ff12757aef7de175295a8", size = 61229, upload-time = "2025-10-17T06:20:10.236Z" }, + { url = "https://files.pythonhosted.org/packages/fc/3a/00cc578cd27ed0b22c9be25cef2c24539d92df9fa80ebd67a3fc5419724c/crc32c-2.8-pp311-pypy311_pp73-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:15905fa78344654e241371c47e6ed2411f9eeb2b8095311c68c88eccf541e8b4", size = 64108, upload-time = "2025-10-17T06:20:11.072Z" }, + { url = "https://files.pythonhosted.org/packages/6b/bc/0587ef99a1c7629f95dd0c9d4f3d894de383a0df85831eb16c48a6afdae4/crc32c-2.8-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c596f918688821f796434e89b431b1698396c38bf0b56de873621528fe3ecb1e", size = 64815, upload-time = "2025-10-17T06:20:11.919Z" }, + { url = "https://files.pythonhosted.org/packages/73/42/94f2b8b92eae9064fcfb8deef2b971514065bd606231f8857ff8ae02bebd/crc32c-2.8-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:8d23c4fe01b3844cb6e091044bc1cebdef7d16472e058ce12d9fadf10d2614af", size = 66659, upload-time = "2025-10-17T06:20:12.766Z" }, +] + [[package]] name = "cryptography" -version = "49.0.0" +version = "50.0.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1f/99/d1c90d6041656cc6ee229dc99cd67fd0cd5aec3c5f7d72fffc27cc750054/cryptography-49.0.0.tar.gz", hash = "sha256:f89660a348f4f78a92366240a61404e337586ef7f5909a2fef59ca88ef505493", size = 854345, upload-time = "2026-06-12T20:02:30.512Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9b/22/adf66990e63584a68dfb50c24f48a125c07b1699899381c8151e63ed458c/cryptography-49.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:966fe0e9c67490071f14c0d2b1cb2dfb3023c5ce39457343931415f08382f2db", size = 4032100, upload-time = "2026-06-12T20:02:32.143Z" }, - { url = "https://files.pythonhosted.org/packages/09/41/3797cfaf69cae04a13ee78ebd83f0678d9c02b4779d21ce24445326f1a69/cryptography-49.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:36d1709f992593689b45bda411498d62c6e365f2ca00b84657d4dadd24de16db", size = 4692978, upload-time = "2026-06-12T20:01:21.305Z" }, - { url = "https://files.pythonhosted.org/packages/e6/8b/43011f7ebe515a8aa20d61f290a326cd890c2e738e16e59eaff8d9c3a412/cryptography-49.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0e959b578856a3924bc0cbb710fc12c387b9412a951389f3ca61704a9e25f325", size = 4716422, upload-time = "2026-06-12T20:01:48.566Z" }, - { url = "https://files.pythonhosted.org/packages/4a/91/01ce7303a4579e6d3a6abef01bd322848e9ea7a219adcabc5048b9033571/cryptography-49.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:53ecee2e23f7169b6117e99fc8a944e5e50f79e69758a83b52a00cb98ab2b2d2", size = 4700503, upload-time = "2026-06-12T20:02:47.091Z" }, - { url = "https://files.pythonhosted.org/packages/62/99/a2c95cf8293f07491e9e27c20cc4dcd18176d944e674679adeb1d0173fd6/cryptography-49.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:2eda353d8a27bcbcaa4cbed18994a74ab4d19a2ca897db188ea269ab9b71419b", size = 5309779, upload-time = "2026-06-12T20:02:08.987Z" }, - { url = "https://files.pythonhosted.org/packages/20/2c/0622f20ff02b2ef32558733443805dc82fd4c275be01b2d19d14676f3a1b/cryptography-49.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:2afe9051da7ae7bd5905da5a949280c7d2bb75682e188f650a9d0f2756b834c6", size = 4749683, upload-time = "2026-06-12T20:02:03.335Z" }, - { url = "https://files.pythonhosted.org/packages/a3/5b/c5246635d5fd3b64e0d45ae10e99fd32fe9676a79915ccfe5a61ba9af1a5/cryptography-49.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:0b82e28ee398a386f0807bba7884d30f25218855690f45115831bcce5d90822c", size = 4337874, upload-time = "2026-06-12T20:02:54.323Z" }, - { url = "https://files.pythonhosted.org/packages/6d/88/05563c7fe2e914e87d1a536d06fe83e66b4e1d95cb593e05aea375531da8/cryptography-49.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:ccac2bfebc306b862133e3bb71f3f6ee8bb525240089b2d952e4144b3a6d5da7", size = 4700283, upload-time = "2026-06-12T20:01:34.822Z" }, - { url = "https://files.pythonhosted.org/packages/c4/b6/d7696e4e890d6ae1469935164c9e5215c557671cb78d6e3f458ccceaa632/cryptography-49.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:d0527ce944105f257f605a827d6ebead966c752038b6e8656abb9c5edee6fc68", size = 5265844, upload-time = "2026-06-12T20:01:24.09Z" }, - { url = "https://files.pythonhosted.org/packages/a9/3c/f3ad17eecc1a57b0ba236dc01f90e783c51f4a2f35f64777cc4f47a184b2/cryptography-49.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:cbc77da8c523d5abd028635ba850a6966fcee2c82e2bf65a41d1d8afe0f98be9", size = 4749290, upload-time = "2026-06-12T20:01:30.848Z" }, - { url = "https://files.pythonhosted.org/packages/4f/01/339573cf1023163a400b0b5d16f6d507de413b9f60be6fd1b77feeaf6737/cryptography-49.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b87e65d263b3e5d3bb92a57e2a6638e2f31110fa7aa890c7b2dbba42248d0a3f", size = 4834612, upload-time = "2026-06-12T20:01:29.246Z" }, - { url = "https://files.pythonhosted.org/packages/71/fd/577302e213a1be9468f92d1afef66fcf1ef83d516819d9992ca547f592bd/cryptography-49.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:66ec79c3904820572d7e987abdf304281f141d37ad9a489b8e97066e7b9b6459", size = 4980804, upload-time = "2026-06-12T20:01:42.853Z" }, - { url = "https://files.pythonhosted.org/packages/1f/09/f42b1d190c5ba75f72062a387f8030d1d75f6ab035788f1d9c4b01de6525/cryptography-49.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:e5dfc1e64de5677cec922ffa8da89c546d0415bf6efdf081842e5d44c84e1f0e", size = 3810026, upload-time = "2026-06-12T20:02:39.262Z" }, - { url = "https://files.pythonhosted.org/packages/ec/9e/db72b3ae7fc9cfad53e630e56c6ae83b9b6ff0bf3718ffb8012d20b3aabf/cryptography-49.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:73a205dce83953d131a4aa1e0fd917a2fd1c5b1eef251e9d7152efefcbf5caf7", size = 4013892, upload-time = "2026-06-12T20:02:10.735Z" }, - { url = "https://files.pythonhosted.org/packages/86/12/c48a424f38db03027be9f7ed5c7dc5de9933dbee992865f98b13727a009d/cryptography-49.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:196ecd6a36e4e9aa10270393bb98d8df88fccee0bf1e5128b91ae4eb4375896d", size = 4678835, upload-time = "2026-06-12T20:02:48.743Z" }, - { url = "https://files.pythonhosted.org/packages/68/28/8a3ad4653662c93fc44dc4e5d8fd374c25c42e07b34bbfbadf49cf57a5a8/cryptography-49.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7abcee80084cda3f7691f3eb1ce480d8df49cec637b429aa35986c1de71738aa", size = 4697239, upload-time = "2026-06-12T20:02:56.03Z" }, - { url = "https://files.pythonhosted.org/packages/a8/b2/2193fc74f81aee4f9b62733133b73b5176718932ed8f2e4b03fa040480a6/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:4ae387c9cb68ea569ca17e490d66d8142b81c3cc814bf179974b7d146e490bbb", size = 4685593, upload-time = "2026-06-12T20:02:50.666Z" }, - { url = "https://files.pythonhosted.org/packages/47/f1/1d3eaa243bfc5de4a187b22aa8c048b3e4980bfbe830ac46e6bac2e66947/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:f37d847238971164fdbc68ade6f6574aecc9c0af714190e2083429ff68f4ce9d", size = 5289961, upload-time = "2026-06-12T20:01:46.468Z" }, - { url = "https://files.pythonhosted.org/packages/58/39/2d51306721330c486495853eda1c567880ff036de15a14c4b74f399934af/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:c2bc30226390d60ea19d9f82b19db005fe0452154a23c1c410c12ea801e43561", size = 4731145, upload-time = "2026-06-12T20:02:16.832Z" }, - { url = "https://files.pythonhosted.org/packages/17/50/983e838c7fd0d87fd8c969bcdd328edaf5f756e38df5281637424c155873/cryptography-49.0.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:07cab27cc7b7e0fd28e5e26bb9eeedde5c135c868b46de4a27845abe94af6122", size = 4321719, upload-time = "2026-06-12T20:02:52.611Z" }, - { url = "https://files.pythonhosted.org/packages/a7/f5/8f571d7e27c55bce9f76f026143bcb1e040a4233149ecca0bea5fa5dd5f7/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:b20133d204d2bb56ba047642199603876c872026ca53e79c35b83772ab2cc505", size = 4685209, upload-time = "2026-06-12T20:02:07.282Z" }, - { url = "https://files.pythonhosted.org/packages/e7/84/0e27016a6fc5a0886f797018b26aa42f40c09a82332bff77822a451deaaa/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:b970c6da94d5bb18629db453d14f2a1300f6bf59b61e9b82377931ef95504866", size = 5246285, upload-time = "2026-06-12T20:01:32.439Z" }, - { url = "https://files.pythonhosted.org/packages/11/2d/5e1fb307cb5931881516b464c98774b3f2c36b5d4bb9a2830253cf553cad/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:d8ecde755e2e91bf773fc94e8c9d730cd7f2007004cb492263a794ec3899a1c8", size = 4730441, upload-time = "2026-06-12T20:02:01.469Z" }, - { url = "https://files.pythonhosted.org/packages/e4/c0/bff5a02ee731d207d6a1ed51732549d8c53d2bc8da1d10ec6f2844201d68/cryptography-49.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e3fb64c420688e5319ae25113a354015abbd8dffbfbc41781a1ea66fc7622ac3", size = 4815869, upload-time = "2026-06-12T20:01:36.574Z" }, - { url = "https://files.pythonhosted.org/packages/b9/26/814681d14248d95d73d5c3eea0c39a94eb8302df966f670a2c60de90974b/cryptography-49.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:32703d93296f5c1f4b53349ad3a250c2cae0fdecd3a3dd5d47e616d8d616af27", size = 4960948, upload-time = "2026-06-12T20:02:18.688Z" }, - { url = "https://files.pythonhosted.org/packages/4c/fe/93ecac273d3738939d023612ad12cca9a3740a5345d69fda04134c43fd96/cryptography-49.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:33cd0565932807baddb67b96dbee92f2c374b5c89dee09fd74079aeb8c8dba61", size = 3799153, upload-time = "2026-06-12T20:01:39.059Z" }, - { url = "https://files.pythonhosted.org/packages/19/2a/5bb823f5bedcf80718cea7fbc95ec5515cca3769633c4b01a32be7f30e7c/cryptography-49.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ec5e529fb80935c94fe7b729f9972b50e351a0e6b50aa294fd5cabb109fcc29a", size = 4025947, upload-time = "2026-06-12T20:01:25.745Z" }, - { url = "https://files.pythonhosted.org/packages/3d/df/40577043ca124e17012f408ddddaeb213b856336ac82ddb3bc915f39e29f/cryptography-49.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f78ff2c9ed8dc2d036b0f4d640e22522213d047c1b14e61205a7e55c80a494d4", size = 4692429, upload-time = "2026-06-12T20:01:53.628Z" }, - { url = "https://files.pythonhosted.org/packages/2c/99/2d13299eb3dd27b02dcfaafcc91d6b5cb3329f7cbd6d8f51921acd566c1a/cryptography-49.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:35b151772baff2c74cba7fa290ceaff4c3b11c0c881eb93eb5dbc05a7cfbba18", size = 4700968, upload-time = "2026-06-12T20:02:45.383Z" }, - { url = "https://files.pythonhosted.org/packages/a5/4d/9c0cd02f95e2602dd5e563da149ee0830abef3537be8b34dc56281ebe27a/cryptography-49.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0f21641cf4b30fca7aee061ced0ec7ad7b073518088b7c9969a297c0ae796c69", size = 4697758, upload-time = "2026-06-12T20:01:41.13Z" }, - { url = "https://files.pythonhosted.org/packages/24/01/186c825898477d77e2324d5360fefe622ff1d8d1963ec0554e2cada8ec77/cryptography-49.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:9e82dcc8e56052715fb18b2429e3bca4823b1629136a2084fc45a9a5cecb9b64", size = 5298863, upload-time = "2026-06-12T20:02:24.579Z" }, - { url = "https://files.pythonhosted.org/packages/b8/7b/62cbbab75d0659865bf0273790031544a0b16c8072d258f9428dcd8190dc/cryptography-49.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:6f2debedf9ca60cf1d5bd466475638af5130f89965605cd818484d19987d3a21", size = 4735983, upload-time = "2026-06-12T20:01:50.14Z" }, - { url = "https://files.pythonhosted.org/packages/6c/72/3e798c064bc39e471008075d0f9bc9daf77a80879c092e4a8e170c585ed4/cryptography-49.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:8c25ceb16df5b9435f3f6a9829204985b0e0cbee3b48aacd432c7d2c850b44d9", size = 4334173, upload-time = "2026-06-12T20:01:44.743Z" }, - { url = "https://files.pythonhosted.org/packages/f0/ee/6fca21d1ac73e06f8bef71940abfd4d2f6472b4bca284d770f32bd4086f6/cryptography-49.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:28d8b15e6275f12c8a207dc309dfa957903c927d08d0cc937ee3f63f200693cc", size = 4697298, upload-time = "2026-06-12T20:02:20.918Z" }, - { url = "https://files.pythonhosted.org/packages/67/d0/a5fcd3515f0bae49a7b6d0413cc1bdccdcc1fc0047037a0d480642cdc5d6/cryptography-49.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6fc361c34fb6aac015ce19435876635e5c6d21db31998b0920f675f131e043b8", size = 5254338, upload-time = "2026-06-12T20:02:22.737Z" }, - { url = "https://files.pythonhosted.org/packages/a0/84/84fe36f19caf857d61cb7fc9c63035a47ffabd84ea12d1d393148efa3615/cryptography-49.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:2400ef9c9e2299a25614eb1dea3db54a69b1349efd043bfac9c67630d136df36", size = 4735650, upload-time = "2026-06-12T20:02:41.389Z" }, - { url = "https://files.pythonhosted.org/packages/6c/a0/db537264e234f7273a73ec020873d6d6b39dfd8a53db78b550ca8320440e/cryptography-49.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:67e1d20ad9ef3a563c59ef22e7a8a0b8210bd26604369ea4a30a7c66aefe504e", size = 4834820, upload-time = "2026-06-12T20:01:51.847Z" }, - { url = "https://files.pythonhosted.org/packages/93/77/8df9eb486495979bccecd1062e2eaf435250e84437040295b57d09048b0b/cryptography-49.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:42b0684e0e40cf26122427802486f6d93aea593612603a94fbf260c7eb1e9c1b", size = 4967968, upload-time = "2026-06-12T20:02:12.524Z" }, - { url = "https://files.pythonhosted.org/packages/c2/e6/f60198ea8d9dfa15fff9ed4ca02ce362f6eadd9ba757dcc50634c4257b63/cryptography-49.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:026ac7423e6fa66872d3bf889be5974507da3944f866f704fa200eadacd00001", size = 3785547, upload-time = "2026-06-12T20:02:26.847Z" }, - { url = "https://files.pythonhosted.org/packages/63/d3/4a83af35d65e3fad632c926fad684c193ea4398569ccb0bbbc7fe8f5dc9a/cryptography-49.0.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:fc1e275c2f1d97b1a6450b8b0ea3ebfa6e087a611c2b26cb2404d48588abab7b", size = 3993685, upload-time = "2026-06-12T20:02:14.883Z" }, - { url = "https://files.pythonhosted.org/packages/d6/a7/f9dac0ab7f80368c56993a7bf638ef9935f825c91902798481fac0898138/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:c83782480a4a9da4d0feb51950131ba32e12e70813848b3343f6e18c28a66838", size = 4676239, upload-time = "2026-06-12T20:02:28.793Z" }, - { url = "https://files.pythonhosted.org/packages/d7/70/2ba3769dd0ae167e2f33dfa9592d45db6ff9a61d62ca1a5b3d1bdd09068f/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:b39efa323140595abd3ecca8529d321ae50f55f3aa3ba9cc81ea56a6011953d5", size = 4715584, upload-time = "2026-06-12T20:01:27.495Z" }, - { url = "https://files.pythonhosted.org/packages/94/64/2923570ac1c0bd3a737aa366ac3abbbbde273042308b8cde95e2364a6e6a/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:b47db11c2c3525083296069b98ac5221907455e989ae0c2e3008bde851921615", size = 4675885, upload-time = "2026-06-12T20:01:55.49Z" }, - { url = "https://files.pythonhosted.org/packages/ab/f8/614dc7e051418cfe53d55173c1e24c6b0085e89996fe90508c2fdf769aef/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:084ef1af862eb07ec46d25f68689f2102a9fc0e05ce7b80f14f5fe51e4eef0f6", size = 4715449, upload-time = "2026-06-12T20:02:05.469Z" }, - { url = "https://files.pythonhosted.org/packages/aa/50/a9caea39ad19c431c1a3f8a31114df65b260cdfe67786b6c7e7c040c4c44/cryptography-49.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:be9fcb48a55f023493482827d4f459bd263cc20efde64f204b97c123201850c6", size = 3783731, upload-time = "2026-06-12T20:02:43.319Z" }, + { url = "https://files.pythonhosted.org/packages/e5/56/d194340cc4a57535e82e1bee9e89667ac4b7c13b5d3f59686deae3094dd5/cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb", size = 3914904, upload-time = "2026-09-30T14:43:44.339Z" }, + { url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" }, + { url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" }, + { url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" }, + { url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" }, + { url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" }, + { url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" }, + { url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" }, + { url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" }, + { url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" }, + { url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/adfc442765721292fff86d314ce385d3249d22db42295c0dd057727b60f3/cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c", size = 3824692, upload-time = "2026-09-30T14:44:11.671Z" }, + { url = "https://files.pythonhosted.org/packages/ce/cb/52eb3770c0d0be2702a98c6e96065ddc0a2877cf0845aa9c23397c142cd4/cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8", size = 3892731, upload-time = "2026-09-30T14:44:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" }, + { url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" }, + { url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" }, + { url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" }, + { url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" }, + { url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" }, + { url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" }, + { url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" }, + { url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" }, + { url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" }, + { url = "https://files.pythonhosted.org/packages/f8/cc/1d33befb3cd7ea7e77d2d73f43f2066471da1b21f24a6156efcaabf6d2e8/cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45", size = 3795868, upload-time = "2026-09-30T14:44:39.71Z" }, + { url = "https://files.pythonhosted.org/packages/2d/49/93f6a6e7a87c9aa68d44d3e1cdb5fe8f60c90d5d2f46acae9a56892816b8/cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37", size = 4133708, upload-time = "2026-09-30T14:44:41.807Z" }, + { url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" }, + { url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" }, + { url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" }, + { url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" }, + { url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" }, + { url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" }, + { url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" }, + { url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" }, + { url = "https://files.pythonhosted.org/packages/39/d1/55f8a3f2ef5d1529e16835ef10cf0fe3d559ce237b46dddc440c0bba3649/cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c", size = 4111557, upload-time = "2026-09-30T15:29:20.155Z" }, + { url = "https://files.pythonhosted.org/packages/23/ad/ac987755d00e1e64273760228d2635ae38dae2be83e3c6e0d3289d91dec3/cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2", size = 3943588, upload-time = "2026-09-30T15:29:22.265Z" }, + { url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" }, + { url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" }, + { url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" }, + { url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" }, + { url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" }, + { url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" }, + { url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" }, + { url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b6/a1faf3a27ae9405fb34b1713cc73b2d8a26b04d5c561578fa2e6ef3e5bb9/cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de", size = 3854095, upload-time = "2026-09-30T15:29:46.782Z" }, + { url = "https://files.pythonhosted.org/packages/1d/7a/f08d34ce09d60f89ebd391e2ebc6ba2b995e6dd7552f41820f8085f94e53/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67", size = 4716035, upload-time = "2026-09-30T15:29:48.681Z" }, + { url = "https://files.pythonhosted.org/packages/45/67/e18fb65592451a2acb76e9f2fbe14e0f47a8318b4c5430f1633851d03daa/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a", size = 4726917, upload-time = "2026-09-30T15:29:50.608Z" }, + { url = "https://files.pythonhosted.org/packages/83/28/38fdce17e60f6b825e69fc3b7f75e70a6612759980704697e1de4cbfaf6e/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48", size = 4715341, upload-time = "2026-09-30T15:29:52.522Z" }, + { url = "https://files.pythonhosted.org/packages/b6/b1/d9121a717e0f893c64bd6ca7702614778d7df2a5c309128a002421788516/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42", size = 4726322, upload-time = "2026-09-30T15:29:54.263Z" }, + { url = "https://files.pythonhosted.org/packages/36/8b/e6d153808bf353e152abd2fd4d8f09670d956ac78379ac46e60d7efbf04c/cryptography-50.0.2-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81", size = 3873097, upload-time = "2026-09-30T15:29:56.097Z" }, + { url = "https://files.pythonhosted.org/packages/ca/1d/1271f287ff7170ddafc2aad36260c4eec20ccd2fea70f38455e9d56d427b/cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452", size = 3805376, upload-time = "2026-09-30T15:29:58.729Z" }, ] [[package]] @@ -873,7 +989,8 @@ version = "54.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cloudpickle" }, - { name = "pyarrow" }, + { 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'" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/60/90/886f7e9cf827f07ebd60bd293e54e0a028a50dd49bbaef0ee42aae1981ea/datafusion-54.0.0.tar.gz", hash = "sha256:cfe7e8dfc026efc05824f49b53ad6a72caf5c2d6820759b6212a09e245a427ed", size = 276448, upload-time = "2026-06-29T11:19:34.816Z" } @@ -1437,7 +1554,9 @@ name = "ibm-watsonx-ai" version = "1.3.42" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version < '3.11'", + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", ] dependencies = [ { name = "cachetools" }, @@ -1463,9 +1582,15 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.12' and python_full_version < '3.14'", - "python_full_version == '3.11.*'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] dependencies = [ { name = "cachetools" }, @@ -1551,7 +1676,9 @@ name = "ipython" version = "8.39.0" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version < '3.11'", + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", ] dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, @@ -1578,9 +1705,15 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.12' and python_full_version < '3.14'", - "python_full_version == '3.11.*'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, @@ -1885,7 +2018,8 @@ dependencies = [ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "overrides", marker = "python_full_version < '3.12'" }, { name = "packaging" }, - { name = "pyarrow" }, + { 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'" }, { name = "pydantic" }, { name = "tqdm" }, ] @@ -1896,7 +2030,8 @@ azure = [ ] clip = [ { name = "open-clip-torch" }, - { name = "pillow" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "torch" }, ] dev = [ @@ -1923,10 +2058,12 @@ embeddings = [ { name = "ibm-watsonx-ai", version = "1.3.42", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "ibm-watsonx-ai", version = "1.5.14", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "instructorembedding" }, + { name = "oci" }, { name = "ollama" }, { name = "open-clip-torch" }, { name = "openai" }, - { name = "pillow" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "requests" }, { name = "sentence-transformers" }, { name = "sentencepiece" }, @@ -1939,7 +2076,8 @@ pylance = [ { name = "pylance" }, ] siglip = [ - { name = "pillow" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "sentencepiece" }, { name = "torch" }, { name = "transformers" }, @@ -1954,7 +2092,8 @@ tests = [ { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, { name = "pandas", version = "3.0.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, { name = "polars" }, - { name = "pyarrow" }, + { 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'" }, { name = "pyarrow-stubs" }, { name = "pylance" }, { name = "pytest" }, @@ -1988,6 +2127,7 @@ requires-dist = [ { name = "mkdocs-material", marker = "extra == 'docs'" }, { name = "mkdocstrings-python", marker = "extra == 'docs'" }, { name = "numpy", specifier = ">=1.24.0" }, + { name = "oci", marker = "extra == 'embeddings'", specifier = ">=2.165.1" }, { name = "ollama", marker = "extra == 'embeddings'", specifier = ">=0.3.0" }, { name = "open-clip-torch", marker = "extra == 'clip'" }, { name = "open-clip-torch", marker = "extra == 'embeddings'", specifier = ">=2.20.0" }, @@ -2003,11 +2143,11 @@ requires-dist = [ { name = "polars", marker = "extra == 'tests'", specifier = ">=0.19,<=1.32.3" }, { name = "pre-commit", marker = "extra == 'dev'", specifier = ">=3.5.0" }, { name = "pyarrow", specifier = ">=16" }, - { name = "pyarrow", marker = "extra == 'tests'", specifier = "<25" }, + { name = "pyarrow", marker = "extra == 'tests'", specifier = ">=16" }, { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b6" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b15" }, { 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" }, @@ -2607,7 +2747,9 @@ name = "networkx" version = "3.4.2" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version < '3.11'", + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", ] sdist = { url = "https://files.pythonhosted.org/packages/fd/1d/06475e1cd5264c0b870ea2cc6fdb3e37177c1e565c43f56ff17a10e3937f/networkx-3.4.2.tar.gz", hash = "sha256:307c3669428c5362aab27c8a1260aa8f47c4e91d3891f48be0141738d8d053e1", size = 2151368, upload-time = "2024-10-21T12:39:38.695Z" } wheels = [ @@ -2621,9 +2763,15 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.12' and python_full_version < '3.14'", - "python_full_version == '3.11.*'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" } wheels = [ @@ -2644,7 +2792,9 @@ name = "numpy" version = "2.2.6" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version < '3.11'", + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", ] sdist = { url = "https://files.pythonhosted.org/packages/76/21/7d2a95e4bba9dc13d043ee156a356c0a8f0c6309dff6b21b4d71a073b8a8/numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd", size = 20276440, upload-time = "2025-05-17T22:38:04.611Z" } wheels = [ @@ -2709,7 +2859,9 @@ name = "numpy" version = "2.4.6" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version == '3.11.*'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" } wheels = [ @@ -2793,8 +2945,12 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.12' and python_full_version < '3.14'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", ] sdist = { url = "https://files.pythonhosted.org/packages/22/fd/89965aa4ac08c74998539fcbf24fa3540f3e15237fbeb6bcf9c908f4aade/numpy-2.5.1.tar.gz", hash = "sha256:a48a113e6afea91f5608793bafa7ef2ad481fefbda87ec5069f483de61cb9fa3", size = 20755553, upload-time = "2026-07-04T17:08:00.933Z" } wheels = [ @@ -2992,6 +3148,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a8/64/3708a90d1ebe202ffdeb7185f878a3c84d15c2b2c31858da2ce0583e2def/nvidia_nvtx-13.0.85-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb7780edb6b14107373c835bf8b72e7a178bac7367e23da7acb108f973f157a6", size = 148878, upload-time = "2025-09-04T08:28:53.627Z" }, ] +[[package]] +name = "oci" +version = "2.188.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohttp" }, + { name = "certifi" }, + { name = "circuitbreaker" }, + { name = "crc32c" }, + { name = "cryptography" }, + { name = "pyjwt" }, + { name = "pyopenssl" }, + { name = "python-dateutil" }, + { name = "python-pkcs11" }, + { name = "pytz" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8e/09/69de33858a8574f6e7f7ebf3d027ac198986c95d3f0efd5c203a882be8d6/oci-2.188.0.tar.gz", hash = "sha256:a4ff307ed315112cf357d9dc0bd5091cb0bae77892870b51ffd0cf46175ba8b6", size = 18377765, upload-time = "2026-10-13T03:51:53.525Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/1b/3138ece59f7ff4afbf4ad53c9d2f88ec7e693f8eae893ebac305e31b45f4/oci-2.188.0-py3-none-any.whl", hash = "sha256:97cf5a0253b45f758c22070c009b7c3197d605d0711a64c7bb060e3d67eda127", size = 37373455, upload-time = "2026-10-13T03:51:47.162Z" }, +] + [[package]] name = "ollama" version = "0.6.2" @@ -3114,7 +3292,9 @@ name = "pandas" version = "2.2.3" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version < '3.11'", + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", ] dependencies = [ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, @@ -3165,8 +3345,12 @@ name = "pandas" version = "2.3.3" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.12' and python_full_version < '3.14'", - "python_full_version == '3.11.*'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] dependencies = [ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12' or python_full_version >= '3.14'" }, @@ -3233,7 +3417,9 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", ] dependencies = [ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" } }, @@ -3357,6 +3543,11 @@ wheels = [ name = "pillow" version = "12.3.0" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", +] sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/25/c2/669d88644cddb1485bd9534e63e8cf476c8e51cb3c3a1297677023505c0e/pillow-12.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a", size = 5392418, upload-time = "2026-07-01T11:53:27.808Z" }, @@ -3447,6 +3638,109 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" }, ] +[[package]] +name = "pillow" +version = "13.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", +] +sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/d7/af6af1b8cc55e07cb0489d5b0950bf5a9bb1461eeba825700b6d8d0e26ea/pillow-13.0.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb", size = 5592324, upload-time = "2026-10-16T22:15:24.672Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d2/2c12cb4fbb5d95f38d1001ff3d95fafcb830077018cba40e56a8f932dfbc/pillow-13.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061", size = 4856298, upload-time = "2026-10-16T22:15:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/229b27472483a4801ea94990815e710391836afdf987b4b722b62bd75db6/pillow-13.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0", size = 6517304, upload-time = "2026-10-16T22:15:29.43Z" }, + { url = "https://files.pythonhosted.org/packages/36/46/f509b74787f40ce0627501089d630b2c741b63b244c1f40b640b3b01e181/pillow-13.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c", size = 7140667, upload-time = "2026-10-16T22:15:31.368Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/5a398b8ec2c37145397d6461c0b551c23ec03072aa64f357aed25e582b00/pillow-13.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f", size = 6610583, upload-time = "2026-10-16T22:15:34.025Z" }, + { url = "https://files.pythonhosted.org/packages/4f/7b/f2f1109b230fd4e2d57ab2305de31adc37ea9b4ff8719436c623cb484415/pillow-13.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806", size = 7218241, upload-time = "2026-10-16T22:15:36.214Z" }, + { url = "https://files.pythonhosted.org/packages/ab/d3/069edb9083b267746baf59756282cacef904d3475c5288c7216fb5195a98/pillow-13.0.0-cp311-cp311-win32.whl", hash = "sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5", size = 6515278, upload-time = "2026-10-16T22:15:38.129Z" }, + { url = "https://files.pythonhosted.org/packages/7d/f6/6e2d96413e4c9dbec12ea584d9e646d602877d4cce3ea669099f959deac6/pillow-13.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3", size = 7278471, upload-time = "2026-10-16T22:15:40.286Z" }, + { url = "https://files.pythonhosted.org/packages/70/e7/baff21f8cb60496c8c250609501b88919eeedb4088d3da106f6c62f3f3c0/pillow-13.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13", size = 2698981, upload-time = "2026-10-16T22:15:42.637Z" }, + { url = "https://files.pythonhosted.org/packages/7a/b8/58d79332229482eb0d27c82973850808c19d37e5bdc14443d3417bd373f5/pillow-13.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:67c8d44ad89fa7eb88de5d6ef6199b1e03dd24974f85a67639fc8badb801fe79", size = 5568643, upload-time = "2026-10-16T22:15:44.474Z" }, + { url = "https://files.pythonhosted.org/packages/39/4b/f2ed53d83aa44ac19599ac0a54897f867fafb95f406980d1e24083f8cbe3/pillow-13.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc481f742ccda20e9ed760b8f978dff50f2a4e9bc253ac167fb0a05b0783ef52", size = 4852329, upload-time = "2026-10-16T22:15:46.284Z" }, + { url = "https://files.pythonhosted.org/packages/3b/bb/9e30e8ed18c20800ee327a12107d5249ad8dc444867b3adfcc21654e3c71/pillow-13.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d", size = 6519309, upload-time = "2026-10-16T22:15:48.14Z" }, + { url = "https://files.pythonhosted.org/packages/e6/99/fdf65cc539e266ab93546c261bdf98411fe165c6e4e13f9dbf597097192b/pillow-13.0.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca", size = 7144542, upload-time = "2026-10-16T22:15:50.093Z" }, + { url = "https://files.pythonhosted.org/packages/26/9b/f38b7c4d8f599537e2d1a6d546cec9beef7536ff8f5c49a3f9c78179d8ac/pillow-13.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4bd024d567eca931b668978d672dba914d4b8e2628e2c3073a2ad178de8a2620", size = 6618042, upload-time = "2026-10-16T22:15:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a8/7c/45ee28531f89ee4582967d8a17f7a26d71ca64cd902b93c269590cd60a00/pillow-13.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40", size = 7228137, upload-time = "2026-10-16T22:15:54.009Z" }, + { url = "https://files.pythonhosted.org/packages/01/bc/9c2a969cb1b70201d04fa17fd5aedf02a732870b8da86bceaaa30b0ca385/pillow-13.0.0-cp312-cp312-win32.whl", hash = "sha256:02464da86f561f410e13b061ec37c3068a9cb557a095494157742d07b3c24a27", size = 6515423, upload-time = "2026-10-16T22:15:56.25Z" }, + { url = "https://files.pythonhosted.org/packages/ff/cd/73a79ecdc822076002eb24b5e1e4a530b0bb5310fcb6d239abbec877110b/pillow-13.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b", size = 7272166, upload-time = "2026-10-16T22:15:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/4a/a3/be5a1236efd085b3984e4305da8f179ae9dab80c991d2ad78f2bd5c4c843/pillow-13.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:c3bc8ee0271387e0b1e3ad0ff893645990a656e79bf9c42f4f734a3642b11d51", size = 2698943, upload-time = "2026-10-16T22:16:00.637Z" }, + { url = "https://files.pythonhosted.org/packages/82/e2/9132d38df320e8099e2642d9fa538f18a7dfebf68a875a31725dc2a115aa/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00", size = 4190620, upload-time = "2026-10-16T22:16:02.527Z" }, + { url = "https://files.pythonhosted.org/packages/cb/be/436dac0996876f65ef1916ffb711c5ef4af2ebc57414b6f16642e07f6b47/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033", size = 4290286, upload-time = "2026-10-16T22:16:04.861Z" }, + { url = "https://files.pythonhosted.org/packages/60/16/7c1007162e4169ea0d5bec47e2e0b2174f56c50cf5b8c02a1dc23e41037e/pillow-13.0.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599", size = 3723169, upload-time = "2026-10-16T22:16:06.956Z" }, + { url = "https://files.pythonhosted.org/packages/08/bc/578ab2eaa04705a8978bd9be0fe15c3d43a8fc95097c4f7e39540e79e4fa/pillow-13.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe", size = 5568469, upload-time = "2026-10-16T22:16:08.664Z" }, + { url = "https://files.pythonhosted.org/packages/98/c8/ccede3dcc4f274b80fb49199eed1ef34ba05566c8b71976b9d1f111da2e3/pillow-13.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313", size = 4852187, upload-time = "2026-10-16T22:16:10.693Z" }, + { url = "https://files.pythonhosted.org/packages/fb/3c/cd0770e96d20bfd990db024bcbd43897ff3e88da1f4782cf90ea231b1d4f/pillow-13.0.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369", size = 6515908, upload-time = "2026-10-16T22:16:12.896Z" }, + { url = "https://files.pythonhosted.org/packages/ef/fe/f5cdaa2d1c4086e757430f368c271a58ee29cfe7378e7ae7b9d964015c25/pillow-13.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582", size = 7142544, upload-time = "2026-10-16T22:16:14.844Z" }, + { url = "https://files.pythonhosted.org/packages/fb/b5/a54f6d44adbcd23737c8c12953f42be107e4cca64e247c0ca3a5b563061c/pillow-13.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81", size = 6613097, upload-time = "2026-10-16T22:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/e6/b4/9e6c1207c21b2e91db0d15c16d30f3701ce5add1bd4da0e787761e66cb6e/pillow-13.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502", size = 7224846, upload-time = "2026-10-16T22:16:19.195Z" }, + { url = "https://files.pythonhosted.org/packages/78/9f/d3c3cb0518f3dd1eee0ef501535f53d15597a53c5c4118d178086143397a/pillow-13.0.0-cp313-cp313-win32.whl", hash = "sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8", size = 6516013, upload-time = "2026-10-16T22:16:21.389Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ed/1b16fb66a37e1b9e41370b93b2c614c7da761a5b2a41dc333f7af4639962/pillow-13.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42", size = 7284777, upload-time = "2026-10-16T22:16:23.393Z" }, + { url = "https://files.pythonhosted.org/packages/87/7d/8d02eba9f7ecc87f8e90f731e032cc4773802f2a843763afd0c66a535ff4/pillow-13.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f", size = 2698826, upload-time = "2026-10-16T22:16:25.382Z" }, + { url = "https://files.pythonhosted.org/packages/8e/45/fbad9c7f5e2f1745c373a434d46072bc84eddfefaa28b852425ac957fda6/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:44629d4498c9cb6b2051806155f22141df0d8a929c56134b166655232dfb2f8c", size = 4190721, upload-time = "2026-10-16T22:16:27.524Z" }, + { url = "https://files.pythonhosted.org/packages/a2/bf/2074902a259a90692c5dbf132885d21671644cbbd3f690047516243a55db/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:bf97ba1b5542050e9b0c74e632323b6d8136cc99d64e193abebee22fe6013c76", size = 4290236, upload-time = "2026-10-16T22:16:29.562Z" }, + { url = "https://files.pythonhosted.org/packages/ff/a5/3d1bb93b8ea38d15d21356c1b8e9f50971ac592aaa248f7fb71739094c0e/pillow-13.0.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aa694c49787040943570d61c9b8fc01271bd2a2cfdd55f0d896f8aecdce1a981", size = 3723093, upload-time = "2026-10-16T22:16:31.249Z" }, + { url = "https://files.pythonhosted.org/packages/84/a1/be060135d85187b25fa8b2573786c0e45c62ae27527fff5257675eb97f4a/pillow-13.0.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:49c12af515073e9bf511e4ef736743bf70d531a643668722279314b937742ba4", size = 5572253, upload-time = "2026-10-16T22:16:33.103Z" }, + { url = "https://files.pythonhosted.org/packages/b5/f4/0bf6f1ac9ba7ee2ffe9914aeb410a1035a0c1a3c42f122388d7fc950bc4b/pillow-13.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d9b0a2bee3f3e03e9f29057aedb807dbf1e1d96ee1b9d0f422d9db6c8583271d", size = 4852269, upload-time = "2026-10-16T22:16:35.102Z" }, + { url = "https://files.pythonhosted.org/packages/83/16/b603274617b3e6728da3a0133d4fba1ea8d7fbe0c4ea5fef9cbffa398b8b/pillow-13.0.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5933fcea5a5ba64c686f55c886a115cbfd92f2900460784a1e79909fdbafd7b6", size = 6516058, upload-time = "2026-10-16T22:16:37.228Z" }, + { url = "https://files.pythonhosted.org/packages/1d/f2/1371707ce438ba9a43f9d24089828494ec6f9396e28cd7903aa704dd6306/pillow-13.0.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e91c2b1cbeae768c98752e67e717e283d68dae45717b41f2d91eaee648e37b7d", size = 7142574, upload-time = "2026-10-16T22:16:39.172Z" }, + { url = "https://files.pythonhosted.org/packages/b9/a9/62cf68587f910bc87c5951bcb6e9430c7643a65076adf5f18b4bf350e2bd/pillow-13.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f6299e494e46253d40c34653cac369412f44ca53b5f85d848d3f95b1ed0546c", size = 6614295, upload-time = "2026-10-16T22:16:41.117Z" }, + { url = "https://files.pythonhosted.org/packages/6c/c9/9e9b48178649730299be0bafbf5f810a5b6977538f5a92d47e4ba5f5d608/pillow-13.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f9bd7d260d986f3553518c5d723544346fa48031f8aef3265d786aeb59845bc0", size = 7224841, upload-time = "2026-10-16T22:16:43.118Z" }, + { url = "https://files.pythonhosted.org/packages/8f/48/c44e91384b1b6c072a714a63d00608acc16a6a968735e478e4be4384e5ac/pillow-13.0.0-cp314-cp314-win32.whl", hash = "sha256:2e31c4e68cffd7b1f116127626813b82fcba19edf6b940a7b0c266d6484d0055", size = 6508694, upload-time = "2026-10-16T22:16:45.883Z" }, + { url = "https://files.pythonhosted.org/packages/50/e2/7ad17747517e4c813dca78257d6bb593466f8231baf1384bc98d92745edb/pillow-13.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:f7cbb7a64e7ec664775195e4f81923bc8a93d9451b963f844e59118f63147a7a", size = 7281830, upload-time = "2026-10-16T22:16:47.725Z" }, + { url = "https://files.pythonhosted.org/packages/41/9f/e5b51f2ce8ef4563215334035403ce61a244f93a2e65c24a940131618f87/pillow-13.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:a6aaa7871aebca081eb5c45f83e845bbd9712ae99fa9286dbfdcee835e63f4b4", size = 2695468, upload-time = "2026-10-16T22:16:49.515Z" }, + { url = "https://files.pythonhosted.org/packages/97/73/a53502f731f6c84805a4ce87a8881e86d07a65aee64728b900d112dc703e/pillow-13.0.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7b999816b5850a35ada08443e6e03945f1f6488144a83afe2d37b240a552aafa", size = 5578196, upload-time = "2026-10-16T22:16:51.291Z" }, + { url = "https://files.pythonhosted.org/packages/21/50/7e949959a56b5559c78ef172b70fc6025706acb289f3f648a15329e4fa6f/pillow-13.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:67871a13cf47275201553b536c025da777f997fa562a19eb798af4ad4b97c18f", size = 4857276, upload-time = "2026-10-16T22:16:53.399Z" }, + { url = "https://files.pythonhosted.org/packages/c9/52/43ded0ac08e77e39d17bd6d894162572201b5e8fdc4a022b14c55a1960a4/pillow-13.0.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8ca8f69b7c77fa96dad99f8638c1fc4f1c0bed4acaa1baf7a3c31bdb80a0ab1", size = 6607008, upload-time = "2026-10-16T22:16:55.525Z" }, + { url = "https://files.pythonhosted.org/packages/0d/2e/4a57ed216d5bf877387cba4d44c02aa87abe51ad2e06404aa6b597c4da39/pillow-13.0.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bce6a29c3898191f4c9998e4d4e8f69790caeabde46e54da4bc235ce5bde683", size = 7224281, upload-time = "2026-10-16T22:16:57.738Z" }, + { url = "https://files.pythonhosted.org/packages/5c/3d/2929b248e135752d63aaeabf53f6de797e905b7b6263f9c1e2adade20aba/pillow-13.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:816752a5ef76a80484c8c441c85593b7ea9304f6231fc5776ad1fbff7e773058", size = 6695600, upload-time = "2026-10-16T22:16:59.842Z" }, + { url = "https://files.pythonhosted.org/packages/bc/33/fb0da992cf084ed1ee6ee05e96b6191e35c351eb707ca2df874feb24ce47/pillow-13.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5bdb38ba220b61b4ec31dd1046dea6b016d3c6850a23f43ed8b58332b2fc668e", size = 7300589, upload-time = "2026-10-16T22:17:01.686Z" }, + { url = "https://files.pythonhosted.org/packages/bb/af/c30dd9ef6a3dce84ecb1b2393cac629047a32e66279056c6cb46c3ffd65c/pillow-13.0.0-cp314-cp314t-win32.whl", hash = "sha256:06903aac074d00c988e77a1fc435286dc498506d4ca8d6f69df9babddf4ecc15", size = 6517204, upload-time = "2026-10-16T22:17:03.722Z" }, + { url = "https://files.pythonhosted.org/packages/85/d5/ef3a8ae7609c8ab26570abf18194882534b480d245a9148b895a2262c004/pillow-13.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:9a635068d9793c7f0d929f39f18b58f1bd86c236e8e7b64167b86af9232ebca0", size = 7286695, upload-time = "2026-10-16T22:17:05.543Z" }, + { url = "https://files.pythonhosted.org/packages/84/3c/0861db0c69a03689ebe3e7599d35668a414deb5aaafd8255215e4e62e3d3/pillow-13.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0d1a9cf7bc6917538b20f8d06b9ab2147e542f68849e96fc58eb66bdf6acc692", size = 2698098, upload-time = "2026-10-16T22:17:07.674Z" }, + { url = "https://files.pythonhosted.org/packages/6e/eb/e86a41962a3a31ad495a3d6a912d9002b01bba4a6fa71c28703abdca7f69/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7d5e097eabd5d4915c27ac9f6e9325bb1e01a7c94d7348b5c4451d3fc30e8521", size = 4191213, upload-time = "2026-10-16T22:17:09.449Z" }, + { url = "https://files.pythonhosted.org/packages/dd/04/7e7445e706afec84ef06dc25b2c77f9cecff242c23730c62928ad1089d4a/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:51ebb529fc5e8abdd55302f6c3f8943037348ec2384329a3e55677f69ae2fdfc", size = 4290650, upload-time = "2026-10-16T22:17:11.196Z" }, + { url = "https://files.pythonhosted.org/packages/46/85/d534089068ac40c0f61f650389a296c812eab745a8a733f81feec39ae955/pillow-13.0.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:c87a04e7f152ee4db5dbe15f0bfa3fe628a1aeedbe66b81c43b87f52c813f9ac", size = 3723078, upload-time = "2026-10-16T22:17:12.772Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2b/00b5c3b401df538b5dbe311d3899730fae5ba1e21cb8b80a128887ac6747/pillow-13.0.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:20722cd5375533ad754053363a80b8fb30c79d37930a6f7228030e237ce3bd5d", size = 5572292, upload-time = "2026-10-16T22:17:14.539Z" }, + { url = "https://files.pythonhosted.org/packages/72/f5/a6b0610f946e9b54ae888ba7ad29d6e2f8d9b11f69e212d70416b7186c09/pillow-13.0.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:04a63720f79e22fd54d897c233a68314c50ca0603360f54ce2bd5db8f0f43782", size = 4852222, upload-time = "2026-10-16T22:17:16.521Z" }, + { url = "https://files.pythonhosted.org/packages/1e/d0/c0ff25bb0427ec70f32aac995453321fc3c4494a46c7292ff02d9d260b04/pillow-13.0.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4f8db54177035a2b5f717f94475b74907e12a96dc74f6d487f3966b0a4694071", size = 6527349, upload-time = "2026-10-16T22:17:18.534Z" }, + { url = "https://files.pythonhosted.org/packages/85/11/e46fa0bcc0fc117f1eacc206b3d51f04d583fab328b4b740672d0438d83f/pillow-13.0.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8f36aa77f74b14a2103622b196402c71330e4e7cf4122ee45c854e9a01e0eecf", size = 7152873, upload-time = "2026-10-16T22:17:20.415Z" }, + { url = "https://files.pythonhosted.org/packages/7c/53/2bdeca705f3a58679fa9201233193c86a30238340ca29b3a152c3fcc719b/pillow-13.0.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:149a1c323ba366f90b48e6f1a6db6582eb50512df374588de56fc909abc0f0f3", size = 6626871, upload-time = "2026-10-16T22:17:22.361Z" }, + { url = "https://files.pythonhosted.org/packages/14/de/3829030f209722ade3753bb456b805a0e7f885cf885b483407365c82e9ca/pillow-13.0.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e892354a424b1e82a78ba16785822bdd40de06f19446a3d4a28047df1a4f8932", size = 7236439, upload-time = "2026-10-16T22:17:24.352Z" }, + { url = "https://files.pythonhosted.org/packages/44/b1/67fc37388382bc036a74f04da5bb6fcbf90ec3ac1f45893e06176c373fd3/pillow-13.0.0-cp315-cp315-win32.whl", hash = "sha256:8e459b613cf31f8980f584387b4fe47bf08e076e288d61aa8eba1f7fd4ddbb81", size = 6508688, upload-time = "2026-10-16T22:17:26.314Z" }, + { url = "https://files.pythonhosted.org/packages/44/05/fdb6a79aee10861165526b41b7b440e36ee1ff58613b2fbefe3acbf06d4f/pillow-13.0.0-cp315-cp315-win_amd64.whl", hash = "sha256:d4737f50d23ddd11d6685faacbb9252887dde0bc7997127757247983d74399d6", size = 7281107, upload-time = "2026-10-16T22:17:28.198Z" }, + { url = "https://files.pythonhosted.org/packages/e6/9c/6c6f7dc2a566467baf121394e83de25ac287cffe34cc030726beb4be0224/pillow-13.0.0-cp315-cp315-win_arm64.whl", hash = "sha256:2310e2adfc13c6d457d7d0f2ffdd5c56a74a317650cf765887df8d515a647ac0", size = 2695513, upload-time = "2026-10-16T22:17:30.013Z" }, + { url = "https://files.pythonhosted.org/packages/23/16/e9120defdb8bff693b582d035312acc6f530cdc2bc5238a87f410efccd82/pillow-13.0.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:21c32061a5512dc13f87cc7303e120e4d77c2f70df89a35af0e3ce246e5ac57f", size = 5578129, upload-time = "2026-10-16T22:17:31.642Z" }, + { url = "https://files.pythonhosted.org/packages/47/22/76faf2bb2448f48a84cf894c1e2bb1090d7d2b1aa521ece131cb2f05d631/pillow-13.0.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1c774b9c0ba0d0b356f71530677b39028878a2cae5a93e0a13779cfd17120f88", size = 4857428, upload-time = "2026-10-16T22:17:33.43Z" }, + { url = "https://files.pythonhosted.org/packages/b3/64/0861ea4e03c50b14af9ed9dd8b9f388ab42f445c623a9fcbab19aef7aa55/pillow-13.0.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20822140c9a2ba9c5e42df342b0a892ab2e102fc0e3db967a133bb9ce3f898bb", size = 6612582, upload-time = "2026-10-16T22:17:35.415Z" }, + { url = "https://files.pythonhosted.org/packages/5c/20/cd1e9b3f60a9f3d5ebe46da36955c26004092a501f7f2c42f9fcc26611bc/pillow-13.0.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ffea6b2986a797c84b6d1d27d4f43e0b83c73fc16281a930891cd237cf0d08fe", size = 7230176, upload-time = "2026-10-16T22:17:37.362Z" }, + { url = "https://files.pythonhosted.org/packages/b6/ef/ffb0a2fc85690714fb7ac662956949645d57f15bf4426f520da361e7b6e3/pillow-13.0.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:05cd2cd39055d0b9650060e4513ef4a9a0aea870083950bd046a0d6490f93a22", size = 6703640, upload-time = "2026-10-16T22:17:39.313Z" }, + { url = "https://files.pythonhosted.org/packages/e0/c2/6402ee3ccb3363aeed8fdb3f9fe56703ac5377a539f0b81b53999d7e121f/pillow-13.0.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:c6fd031333dedcad7ce3e03d244093f43504f209e86925ebdb2b868fa4037630", size = 7309231, upload-time = "2026-10-16T22:17:41.021Z" }, + { url = "https://files.pythonhosted.org/packages/fc/96/d6b82e8b8c06ad143b66b12e0b31051e4bf489b4fabca1f390a14fe1ebde/pillow-13.0.0-cp315-cp315t-win32.whl", hash = "sha256:c50c80e3591e5cf9a8dfa6007d4f10732f02e32263850999286e56ccd650cfb2", size = 6517200, upload-time = "2026-10-16T22:17:42.886Z" }, + { url = "https://files.pythonhosted.org/packages/60/d4/0062e6005e9b270b165015aafd343364ac378ec5a685431ea42baad33357/pillow-13.0.0-cp315-cp315t-win_amd64.whl", hash = "sha256:adb3c2124c68e480f4632d06cb7caa3b48a51678475f483b4edb1c6dee29ea43", size = 7287488, upload-time = "2026-10-16T22:17:45.56Z" }, + { url = "https://files.pythonhosted.org/packages/e4/81/b8eb349746be7bce47dd95337c6634e84910af91b59aaa9159c034c614fa/pillow-13.0.0-cp315-cp315t-win_arm64.whl", hash = "sha256:4a25756244bdcce3b50580baadf320fa48297f0eeb8e114ba64139a40d4d0fc8", size = 2698073, upload-time = "2026-10-16T22:17:47.556Z" }, + { url = "https://files.pythonhosted.org/packages/68/c0/fb7b1caf25ed5ac5d46116f09b8b0706b9559833c65c667cecb1a53153f2/pillow-13.0.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca", size = 5521630, upload-time = "2026-10-16T22:17:50.008Z" }, + { url = "https://files.pythonhosted.org/packages/1a/e6/4d11d5b1137f4fc080605cce410cfaae4f303ad400bdec75d27d3083fa29/pillow-13.0.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039", size = 4806023, upload-time = "2026-10-16T22:17:51.932Z" }, + { url = "https://files.pythonhosted.org/packages/f1/45/0923202a658e8ff6aafd72c1a4395ebadcdebaa182c437d8595d3dd3db32/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad", size = 5464831, upload-time = "2026-10-16T22:17:53.742Z" }, + { url = "https://files.pythonhosted.org/packages/07/52/d3e38f0cad1dadea2a658b9a7d6ba8a04048f5ae14f011b806e5c3bd6bcb/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2", size = 6043133, upload-time = "2026-10-16T22:17:55.625Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f9/2ed7685980c1d64f8131a7d87a19c369424747577152622b73ddeff163b7/pillow-13.0.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c", size = 7365208, upload-time = "2026-10-16T22:17:57.509Z" }, + { url = "https://files.pythonhosted.org/packages/60/da/f6d644e631c5b370c5d0b899f3ccadd2780aab070b29a110527cf4e1fd2c/pillow-13.0.0-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:8619685cad8efc4c38c66d3b36aad854523297c43d748b3b6f0cc03c90ba3463", size = 5523188, upload-time = "2026-10-16T22:17:59.334Z" }, + { url = "https://files.pythonhosted.org/packages/e4/b0/2594f202d743a35d4fe80682bfd96f277e5ca7aecb27cf64ef5bfc1d000b/pillow-13.0.0-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:7e91e97a929232cdb828889ee6ad0e48d7f40f4ec38818f4e4a8968b2b1af22e", size = 4806808, upload-time = "2026-10-16T22:18:01.188Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ed/d504165ef79af6fafe25c76726cf30f544cc236002f7ed054f1d51adc4ff/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:93ff9c9c3663ce23aaa5d0b6b6abac55359e2a0c06c7e30f3771829af816be63", size = 5464358, upload-time = "2026-10-16T22:18:02.779Z" }, + { url = "https://files.pythonhosted.org/packages/7b/fe/a10aba5503ca13e9e009b8bd0a1a4ce5584bdce246245fd6f3a83701369c/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61", size = 6043514, upload-time = "2026-10-16T22:18:04.538Z" }, + { url = "https://files.pythonhosted.org/packages/c0/37/66b12dc476041fe523bca29c9d58fbf1ea92a4eaf73acfb9e993948f1191/pillow-13.0.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a", size = 7366030, upload-time = "2026-10-16T22:18:06.638Z" }, +] + [[package]] name = "platformdirs" version = "4.10.0" @@ -3682,59 +3976,127 @@ wheels = [ [[package]] name = "pyarrow" -version = "24.0.0" +version = "25.0.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/91/13/13e1069b351bdc3881266e11147ffccf687505dbb0ea74036237f5d454a5/pyarrow-24.0.0.tar.gz", hash = "sha256:85fe721a14dd823aca09127acbb06c3ca723efbd436c004f16bca601b04dcc83", size = 1180261, upload-time = "2026-04-21T10:51:25.837Z" } +resolution-markers = [ + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", +] +sdist = { url = "https://files.pythonhosted.org/packages/3d/e3/27f57f80141379d60defe6703eb50a707325706f07fedfd1312c7a751995/pyarrow-25.0.1.tar.gz", hash = "sha256:9150a83248bfed9813ea3c3af74c3856c1984d444aa28e58bf7733b9750ddf6a", size = 1201653, upload-time = "2026-08-10T12:40:53.904Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a5/bf/a34fee1d624152124fa8355c42f34195ad5fe5233ce5bb87946432047d52/pyarrow-24.0.0-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:7c2b98645d576a0b9616892ead22b64a83a5f043c5e2ca15ebcefcb5b70c80cb", size = 35076681, upload-time = "2026-04-21T08:51:46.845Z" }, - { url = "https://files.pythonhosted.org/packages/1d/41/64180033d7027afce12dc96d0fe1f504c6fa112190582b458acea2399530/pyarrow-24.0.0-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:644a246325b8c69c595ad1dd4b463eba4b0cdb731370e4a86137d433208d6147", size = 36684260, upload-time = "2026-04-21T08:51:53.642Z" }, - { url = "https://files.pythonhosted.org/packages/57/02/9b9320e673dd8a99411fac78690f3df92f6dd6f59754c750110bca66d64e/pyarrow-24.0.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:3a577bd840ca83f646f0a625dbc571dba7044c43c2d1503afc378b570954345c", size = 45698566, upload-time = "2026-04-21T10:46:02.133Z" }, - { url = "https://files.pythonhosted.org/packages/67/33/f75e91b9a64c3f33c787e263c93b871ad91b8a4a68c1d5cebddd9840e835/pyarrow-24.0.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:e3268e43984d0b1a185c89b4cfff282a7ead12fc93f56cfd7088bdbcbe727041", size = 48835562, upload-time = "2026-04-21T10:46:10.278Z" }, - { url = "https://files.pythonhosted.org/packages/a5/63/097510448e47e4091faa41c43ba92f97cecaab8f4535b56a3d149578f634/pyarrow-24.0.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:2392d954fcb920f42d230284b677605e4e2fbb11f2821e823e642abd67fbb491", size = 49394997, upload-time = "2026-04-21T10:46:18.08Z" }, - { url = "https://files.pythonhosted.org/packages/60/6b/c047d6222ab279024a062742d1807e2fbaf27bba88a98637299ff47b9236/pyarrow-24.0.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:bec9373df11544592b0ba7ec2af0e35059e5f0e7647c6183a854dedd193298f1", size = 51911424, upload-time = "2026-04-21T10:46:25.347Z" }, - { url = "https://files.pythonhosted.org/packages/3a/ba/464cc70761c2a525d97ebd84e21c31ebd47f3ef4bdcee117009f51c46f24/pyarrow-24.0.0-cp310-cp310-win_amd64.whl", hash = "sha256:c42ab9439498270139cc63e18847a02afe5c8b3ed9c931266533cfe378bd3591", size = 27251730, upload-time = "2026-04-21T10:46:30.913Z" }, - { url = "https://files.pythonhosted.org/packages/62/c9/a47ab7ece0d86cbe6678418a0fbd1ac4bb493b9184a3891dfa0e7f287ae0/pyarrow-24.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:b0e131f880cda8d04e076cee175a46fc0e8bc8b65c99c6c09dff6669335fde74", size = 35068898, upload-time = "2026-04-21T10:46:36.599Z" }, - { url = "https://files.pythonhosted.org/packages/d1/bc/8db86617a9a58008acf8913d6fed68ea2a46acb6de928db28d724c891a68/pyarrow-24.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:1b2fe7f9a5566401a0ef2571f197eb92358925c1f0c8dba305d6e43ea0871bb3", size = 36679915, upload-time = "2026-04-21T10:46:42.602Z" }, - { url = "https://files.pythonhosted.org/packages/eb/8e/fb178720400ef69db251eb4a9c3ccf4af269bc1feb5055529b8fc87170d1/pyarrow-24.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:0b3537c00fb8d384f15ac1e79b6eb6db04a16514c8c1d22e59a9b95c8ba42868", size = 45697931, upload-time = "2026-04-21T10:46:48.403Z" }, - { url = "https://files.pythonhosted.org/packages/f3/27/99c42abe8e21b44f4917f62631f3aa31404882a2c41d8a4cd5c110e13d52/pyarrow-24.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:14e31a3c9e35f1ab6356c6378f6f72830e6d2d5f1791df3774a7b097d18a6a1e", size = 48837449, upload-time = "2026-04-21T10:46:55.329Z" }, - { url = "https://files.pythonhosted.org/packages/36/b6/333749e2666e9032891125bf9c691146e92901bece62030ac1430e2e7c88/pyarrow-24.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b7d9a514e73bc42711e6a35aaccf3587c520024fe0a25d830a1a8a27c15f4f57", size = 49395949, upload-time = "2026-04-21T10:47:01.869Z" }, - { url = "https://files.pythonhosted.org/packages/17/25/c5201706a2dd374e8ba6ee3fd7a8c89fb7ffc16eed5217a91fd2bd7f7626/pyarrow-24.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b196eb3f931862af3fa84c2a253514d859c08e0d8fe020e07be12e75a5a9780c", size = 51912986, upload-time = "2026-04-21T10:47:09.872Z" }, - { url = "https://files.pythonhosted.org/packages/f8/d2/4d1bbba65320b21a49678d6fbdc6ff7c649251359fdcfc03568c4136231d/pyarrow-24.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:35405aecb474e683fb36af650618fd5340ee5471fc65a21b36076a18bbc6c981", size = 27255371, upload-time = "2026-04-21T10:47:15.943Z" }, - { url = "https://files.pythonhosted.org/packages/b4/a9/9686d9f07837f91f775e8932659192e02c74f9d8920524b480b85212cc68/pyarrow-24.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:6233c9ed9ab9d1db47de57d9753256d9dcffbf42db341576099f0fd9f6bf4810", size = 34981559, upload-time = "2026-04-21T10:47:22.17Z" }, - { url = "https://files.pythonhosted.org/packages/80/b6/0ddf0e9b6ead3474ab087ae598c76b031fc45532bf6a63f3a553440fb258/pyarrow-24.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:f7616236ec1bc2b15bfdec22a71ab38851c86f8f05ff64f379e1278cf20c634a", size = 36663654, upload-time = "2026-04-21T10:47:28.315Z" }, - { url = "https://files.pythonhosted.org/packages/7c/3b/926382efe8ce27ba729071d3566ade6dfb86bdf112f366000196b2f5780a/pyarrow-24.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:1617043b99bd33e5318ae18eb2919af09c71322ef1ca46566cdafc6e6712fb66", size = 45679394, upload-time = "2026-04-21T10:47:34.821Z" }, - { url = "https://files.pythonhosted.org/packages/b3/7a/829f7d9dfd37c207206081d6dad474d81dde29952401f07f2ba507814818/pyarrow-24.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:6165461f55ef6314f026de6638d661188e3455d3ec49834556a0ebbdbace18bb", size = 48863122, upload-time = "2026-04-21T10:47:42.056Z" }, - { url = "https://files.pythonhosted.org/packages/5f/e8/f88ce625fe8babaae64e8db2d417c7653adb3019b08aae85c5ed787dc816/pyarrow-24.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3b13dedfe76a0ad2d1d859b0811b53827a4e9d93a0bcb05cf59333ab4980cc7e", size = 49376032, upload-time = "2026-04-21T10:47:48.967Z" }, - { url = "https://files.pythonhosted.org/packages/36/7a/82c363caa145fff88fb475da50d3bf52bb024f61917be5424c3392eaf878/pyarrow-24.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:25ea65d868eb04015cd18e6df2fbe98f07e5bda2abefabcb88fce39a947716f6", size = 51929490, upload-time = "2026-04-21T10:47:55.981Z" }, - { url = "https://files.pythonhosted.org/packages/66/1c/e3e72c8014ad2743ca64a701652c733cc5cbcee15c0463a32a8c55518d9e/pyarrow-24.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:295f0a7f2e242dabd513737cf076007dc5b2d59237e3eca37b05c0c6446f3826", size = 27355660, upload-time = "2026-04-21T10:48:01.718Z" }, - { url = "https://files.pythonhosted.org/packages/6f/d3/a1abf004482026ddc17f4503db227787fa3cfe41ec5091ff20e4fea55e57/pyarrow-24.0.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:02b001b3ed4723caa44f6cd1af2d5c86aa2cf9971dacc2ffa55b21237713dfba", size = 34976759, upload-time = "2026-04-21T10:48:07.258Z" }, - { url = "https://files.pythonhosted.org/packages/4f/4a/34f0a36d28a2dd32225301b79daad44e243dc1a2bb77d43b60749be255c4/pyarrow-24.0.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:04920d6a71aabd08a0417709efce97d45ea8e6fb733d9ca9ecffb13c67839f68", size = 36658471, upload-time = "2026-04-21T10:48:13.347Z" }, - { url = "https://files.pythonhosted.org/packages/1f/78/543b94712ae8bb1a6023bcc1acf1a740fbff8286747c289cd9468fced2a5/pyarrow-24.0.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a964266397740257f16f7bb2e4f08a0c81454004beab8ff59dd531b73610e9f2", size = 45675981, upload-time = "2026-04-21T10:48:20.201Z" }, - { url = "https://files.pythonhosted.org/packages/84/9f/8fb7c222b100d314137fa40ec050de56cd8c6d957d1cfff685ce72f15b17/pyarrow-24.0.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:6f066b179d68c413374294bc1735f68475457c933258df594443bb9d88ddc2a0", size = 48859172, upload-time = "2026-04-21T10:48:27.541Z" }, - { url = "https://files.pythonhosted.org/packages/a7/d3/1ea72538e6c8b3b475ed78d1049a2c518e655761ea50fe1171fc855fcab7/pyarrow-24.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1183baeb14c5f587b1ec52831e665718ce632caab84b7cd6b85fd44f96114495", size = 49385733, upload-time = "2026-04-21T10:48:34.7Z" }, - { url = "https://files.pythonhosted.org/packages/c3/be/c3d8b06a1ba35f2260f8e1f771abbee7d5e345c0937aab90675706b1690a/pyarrow-24.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:806f24b4085453c197a5078218d1ee08783ebbba271badd153d1ae22a3ee804f", size = 51934335, upload-time = "2026-04-21T10:48:42.099Z" }, - { url = "https://files.pythonhosted.org/packages/9c/62/89e07a1e7329d2cde3e3c6994ba0839a24977a2beda8be6005ea3d860b99/pyarrow-24.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:e4505fc6583f7b05ab854934896bcac8253b04ac1171a77dfb73efef92076d91", size = 27271748, upload-time = "2026-04-21T10:49:42.532Z" }, - { url = "https://files.pythonhosted.org/packages/17/1a/cff3a59f80b5b1658549d46611b67163f65e0664431c076ad728bf9d5af4/pyarrow-24.0.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:1a4e45017efbf115032e4475ee876d525e0e36c742214fbe405332480ecd6275", size = 35238554, upload-time = "2026-04-21T10:48:48.526Z" }, - { url = "https://files.pythonhosted.org/packages/a8/99/cce0f42a327bfef2c420fb6078a3eb834826e5d6697bf3009fe11d2ad051/pyarrow-24.0.0-cp313-cp313t-macosx_12_0_x86_64.whl", hash = "sha256:7986f1fa71cee060ad00758bcc79d3a93bab8559bf978fab9e53472a2e25a17b", size = 36782301, upload-time = "2026-04-21T10:48:55.181Z" }, - { url = "https://files.pythonhosted.org/packages/2a/66/8e560d5ff6793ca29aca213c53eec0dd482dd46cb93b2819e5aab52e4252/pyarrow-24.0.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:d3e0b61e8efb24ed38898e5cdc5fffa9124be480008d401a1f8071500494ae42", size = 45721929, upload-time = "2026-04-21T10:49:03.676Z" }, - { url = "https://files.pythonhosted.org/packages/27/0c/a26e25505d030716e078d9f16eb74973cbf0b33b672884e9f9da1c83b871/pyarrow-24.0.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:55a3bc1e3df3b5567b7d27ef551b2283f0c68a5e86f1cd56abc569da4f31335b", size = 48825365, upload-time = "2026-04-21T10:49:11.714Z" }, - { url = "https://files.pythonhosted.org/packages/5f/eb/771f9ecb0c65e73fe9dccdd1717901b9594f08c4515d000c7c62df573811/pyarrow-24.0.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:641f795b361874ac9da5294f8f443dfdbee355cf2bd9e3b8d97aaac2306b9b37", size = 49451819, upload-time = "2026-04-21T10:49:21.474Z" }, - { url = "https://files.pythonhosted.org/packages/48/da/61ae89a88732f5a785646f3ec6125dbb640fa98a540eb2b9889caa561403/pyarrow-24.0.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8adc8e6ce5fccf5dc707046ae4914fd537def529709cc0d285d37a7f9cd442ca", size = 51909252, upload-time = "2026-04-21T10:49:31.164Z" }, - { url = "https://files.pythonhosted.org/packages/cb/1a/8dd5cafab7b66573fa91c03d06d213356ad4edd71813aa75e08ce2b3a844/pyarrow-24.0.0-cp313-cp313t-win_amd64.whl", hash = "sha256:9b18371ad2f44044b81a8d23bc2d8a9b6a6226dca775e8e16cfee640473d6c5d", size = 27388127, upload-time = "2026-04-21T10:49:37.334Z" }, - { url = "https://files.pythonhosted.org/packages/ad/80/d022a34ff05d2cbedd8ccf841fc1f532ecfa9eb5ed1711b56d0e0ea71fc9/pyarrow-24.0.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:1cc9057f0319e26333b357e17f3c2c022f1a83739b48a88b25bfd5fa2dc18838", size = 35007997, upload-time = "2026-04-21T10:49:48.796Z" }, - { url = "https://files.pythonhosted.org/packages/1a/ff/f01485fda6f4e5d441afb8dd5e7681e4db18826c1e271852f5d3957d6a80/pyarrow-24.0.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:e6f1278ee4785b6db21229374a1c9e54ec7c549de5d1efc9630b6207de7e170b", size = 36678720, upload-time = "2026-04-21T10:49:55.858Z" }, - { url = "https://files.pythonhosted.org/packages/9e/c2/2d2d5fea814237923f71b36495211f20b43a1576f9a4d6da7e751a64ec6f/pyarrow-24.0.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:adbbedc55506cbdabb830890444fb856bfb0060c46c6f8026c6c2f2cf86ae795", size = 45741852, upload-time = "2026-04-21T10:50:04.624Z" }, - { url = "https://files.pythonhosted.org/packages/8e/3a/28ba9c1c1ebdbb5f1b94dfebb46f207e52e6a554b7fe4132540fde29a3a0/pyarrow-24.0.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:ae8a1145af31d903fa9bb166824d7abe9b4681a000b0159c9fb99c11bc11ad26", size = 48889852, upload-time = "2026-04-21T10:50:12.293Z" }, - { url = "https://files.pythonhosted.org/packages/df/51/4a389acfd31dca009f8fb82d7f510bb4130f2b3a8e18cf00194d0687d8ac/pyarrow-24.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d7027eba1df3b2069e2e8d80f644fa0918b68c46432af3d088ddd390d063ecde", size = 49445207, upload-time = "2026-04-21T10:50:20.677Z" }, - { url = "https://files.pythonhosted.org/packages/19/4b/0bab2b23d2ae901b1b9a03c0efd4b2d070256f8ce3fc43f6e58c167b2081/pyarrow-24.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e56a1ffe9bf7b727432b89104cc0849c21582949dd7bdcb34f17b2001a351a76", size = 51954117, upload-time = "2026-04-21T10:50:29.14Z" }, - { url = "https://files.pythonhosted.org/packages/29/88/f4e9145da0417b3d2c12035a8492b35ff4a3dbc653e614fcfb51d9dedb38/pyarrow-24.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:38be1808cdd068605b787e6ca9119b27eb275a0234e50212c3492331680c3b1e", size = 28001155, upload-time = "2026-04-21T10:51:22.337Z" }, - { url = "https://files.pythonhosted.org/packages/79/4f/46a49a63f43526da895b1a45bbb51d5baf8e4d77159f8528fc3e5490007f/pyarrow-24.0.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:418e48ce50a45a6a6c73c454677203a9c75c966cb1e92ca3370959185f197a05", size = 35250387, upload-time = "2026-04-21T10:50:35.552Z" }, - { url = "https://files.pythonhosted.org/packages/a0/da/d5e0cd5ef00796922404806d5f00325cdadc3441ce2c13fe7115f2df9a64/pyarrow-24.0.0-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:2f16197705a230a78270cdd4ea8a1d57e86b2fdcbc34a1f6aebc72e65c986f9a", size = 36797102, upload-time = "2026-04-21T10:50:42.417Z" }, - { url = "https://files.pythonhosted.org/packages/34/c7/5904145b0a593a05236c882933d439b5720f0a145381179063722fbfc123/pyarrow-24.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:fb24ac194bfc5e86839d7dcd52092ee31e5fe6733fe11f5e3b06ef0812b20072", size = 45745118, upload-time = "2026-04-21T10:50:49.324Z" }, - { url = "https://files.pythonhosted.org/packages/13/d3/cca42fe166d1c6e4d5b80e530b7949104d10e17508a90ae202dac205ce2a/pyarrow-24.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:9700ebd9a51f5895ce75ff4ac4b3c47a7d4b42bc618be8e713e5d56bacf5f931", size = 48844765, upload-time = "2026-04-21T10:50:55.579Z" }, - { url = "https://files.pythonhosted.org/packages/b0/49/942c3b79878ba928324d1e17c274ed84581db8c0a749b24bcf4cbdf15bd3/pyarrow-24.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d8ddd2768da81d3ee08cfea9b597f4abb4e8e1dc8ae7e204b608d23a0d3ab699", size = 49471890, upload-time = "2026-04-21T10:51:02.439Z" }, - { url = "https://files.pythonhosted.org/packages/76/97/ff71431000a75d84135a1ace5ca4ba11726a231a8007bbb320a4c54075d5/pyarrow-24.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:61a3d7eaa97a14768b542f3d284dc6400dd2470d9f080708b13cd46b6ae18136", size = 51932250, upload-time = "2026-04-21T10:51:10.576Z" }, - { url = "https://files.pythonhosted.org/packages/51/be/6f79d55816d5c22557cf27533543d5d70dfe692adfbee4b99f2760674f38/pyarrow-24.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:c91d00057f23b8d353039520dc3a6c09d8608164c692e9f59a175a42b2ae0c19", size = 28131282, upload-time = "2026-04-21T10:51:16.815Z" }, + { url = "https://files.pythonhosted.org/packages/0a/3e/5cd70becb51e1d044c54ba5e627424a6e87df5b98008cbd22cc6abd409ca/pyarrow-25.0.1-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:0b1edbb2f385a6a65e9711b62ba86ac54a7816a3f8d17bb3e8a5929d65fb2485", size = 35954271, upload-time = "2026-08-10T12:36:33.857Z" }, + { url = "https://files.pythonhosted.org/packages/64/be/17599e086df264ea7dc221d1101e3131e181e00da428a2f9bd0358f0d06b/pyarrow-25.0.1-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:a4dd8bf99a8fac133efc0ed6a92f5fddbe2adba0d0f6dd720e39ba9855cea85c", size = 37647543, upload-time = "2026-08-10T12:36:39.486Z" }, + { url = "https://files.pythonhosted.org/packages/42/34/e138b451fd3970a6eda4599f68ae3b2b32b661bc958de3239d54a0bf6575/pyarrow-25.0.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:bddd0c4f7630c2a3ddf6347c1bdaa79d97bcf6bd445f9e60c816b7d77c85a5ae", size = 46837120, upload-time = "2026-08-10T12:36:46.58Z" }, + { url = "https://files.pythonhosted.org/packages/57/5c/f8fc0eb2de03464a557d5a4d0c15e972d73362414696618833b771f7eddd/pyarrow-25.0.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:a4d6d5e9a3d1879a97c08ded0c797579b7965eafd0f0c26c30b45ccc06db939b", size = 50066460, upload-time = "2026-08-10T12:36:53.702Z" }, + { url = "https://files.pythonhosted.org/packages/3f/d1/0dd64fd06de0333b808a02f60981635f067b71aad3a30698a9a104fae778/pyarrow-25.0.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:514ddb60285631af068875550c90eddc181db3e8e63a032b1559be189e82f056", size = 49937892, upload-time = "2026-08-10T12:37:00.349Z" }, + { url = "https://files.pythonhosted.org/packages/cb/3c/f89d1bd76d5f3284c2a44d7d7ebbd8204535e5ae2b41f4077069b4ff2ec6/pyarrow-25.0.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:cab40b1edfef0262e0e5251aa2c58d75630f24d06dd7794480243acc001a1d7d", size = 53107240, upload-time = "2026-08-10T12:37:07.205Z" }, + { url = "https://files.pythonhosted.org/packages/67/67/b554a8e09f3f3decccf405eb8fbe86696321cbcb5b62d18b4a5057a4c113/pyarrow-25.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:60e89d8f13861a1f7f8d950fa54aebb8023b30734d0ac51ffa80beabe2df4bba", size = 27848683, upload-time = "2026-08-10T12:37:12.058Z" }, + { url = "https://files.pythonhosted.org/packages/ee/8b/0d23b47702fcfe8b3618d5292035099675c5a1c48258932350c08020f7b5/pyarrow-25.0.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:51093dd9e10325fbdb3c10a2ae7c4806e5c822d94e74ae4938b26524a3323fee", size = 35946180, upload-time = "2026-08-10T12:37:18.934Z" }, + { url = "https://files.pythonhosted.org/packages/d8/17/707d17a5476c55a9541fde0db8213ac30979a792864d72415f176ba50c45/pyarrow-25.0.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:eb6203482ff3746a5632303a7279ae0b5a304c46985b49ed1378cb350ea6728d", size = 37644787, upload-time = "2026-08-10T12:37:25.795Z" }, + { url = "https://files.pythonhosted.org/packages/c1/b2/cdc98ecf1a6408280bc3a6a07054cdd99a3f4670acc0545d383ce113e87d/pyarrow-25.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:880523be3d29efcf83d3998835d206118ccf35e3871dbd2fb60408cf6b007a80", size = 46834633, upload-time = "2026-08-10T12:37:33.604Z" }, + { url = "https://files.pythonhosted.org/packages/c8/6e/d3fafc41f378b2c65be43b827798c0fae42049a641c8526633ed3eb573e2/pyarrow-25.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:25f8720bf6387d5dc2ebd2622112de630760419e4b66134405dd24110d15f37e", size = 50065507, upload-time = "2026-08-10T12:37:40.565Z" }, + { url = "https://files.pythonhosted.org/packages/d5/12/8d0698954b8c3001844a898e0a6900bebe83d7ee40c11195174c5122f324/pyarrow-25.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4facd65742a024a4a366328a1d2292062d72d6e023c1b7dda8d4c37544933a25", size = 49955690, upload-time = "2026-08-10T12:37:46.644Z" }, + { url = "https://files.pythonhosted.org/packages/d3/0b/1ecb936ac6409e90a34d58eea1c7cec09a9ae6d2141b9e49ad01a2b1ea47/pyarrow-25.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:aa0559502e1cd6254d6814614085dd9c5a3dd0419362978a936a3f68a9e5c3df", size = 53128198, upload-time = "2026-08-10T12:37:52.531Z" }, + { url = "https://files.pythonhosted.org/packages/8e/1c/5236033550633c9b7377b2a53660b2bbb06cb06dc09c4356332d67643ca1/pyarrow-25.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:62cd0d785b8aa6675ee355f9fc02252a340f4441257c42674937826fd7594325", size = 27857263, upload-time = "2026-08-10T12:37:56.943Z" }, + { url = "https://files.pythonhosted.org/packages/a6/e2/9ab15b88cbfac28e16419ce5439ec29234c5172cb8259301b4ba639bdec0/pyarrow-25.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:df961f2e7ae9cf496459259d798652c70625f6c080650d6952f8c04053c58ee9", size = 35861559, upload-time = "2026-08-10T12:38:02.567Z" }, + { url = "https://files.pythonhosted.org/packages/58/79/a0036dbe1eabe1f73127427342f1d99982584c4a2cde2651d6c93499c6f6/pyarrow-25.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:cc4aa407fde9fc660be3939e49ea31f50f3e9fec17c0ec63159f7711edd3efc9", size = 37628383, upload-time = "2026-08-10T12:38:09.083Z" }, + { url = "https://files.pythonhosted.org/packages/13/49/d93a57d375f4bf0cf82913dd6bb54acafde83dd993be2282c81ac5616cad/pyarrow-25.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:4340f0ba6c1d2e13f21658de1d7c662ca2545018568d0030a1e9afca159d87e3", size = 46820190, upload-time = "2026-08-10T12:38:15.458Z" }, + { url = "https://files.pythonhosted.org/packages/60/c9/711ca85d79f1ec98f29a5eae2b051e25b4ecec5de3e3c0e2d5c5dcb15664/pyarrow-25.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:5389cdf79447ed1515c9e31620e6e1e2302249564d603f2ad727d4f6d313e4c3", size = 50102437, upload-time = "2026-08-10T12:38:22.487Z" }, + { url = "https://files.pythonhosted.org/packages/80/53/8fb8359ff17cfb6263a1cf3ebf7caec9fe197de118719e84fcb1d0618026/pyarrow-25.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d51592cb7561e87877c506113e7adbf1342ab579e6c21f0ef44b8ba41cb74c80", size = 49942424, upload-time = "2026-08-10T12:38:28.755Z" }, + { url = "https://files.pythonhosted.org/packages/e8/83/4e5ae02a9341571b18a6fca380ac7a58ce6ddae7ab3c060208c0a1e79f02/pyarrow-25.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6109c94d8b9f3b17a041daca16cacb2f651ad8f1ef70a4232c2c0f37a23da2a8", size = 53144206, upload-time = "2026-08-10T12:38:34.862Z" }, + { url = "https://files.pythonhosted.org/packages/65/ee/197cbf47e49f83e6ebeb946a5259a48a638dea27ac774db42fe78022179d/pyarrow-25.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:8858d7bfc22e3f51529aeaa4077225029724623e4595dc9eff8c793935c34140", size = 27953934, upload-time = "2026-08-10T12:38:39.808Z" }, + { url = "https://files.pythonhosted.org/packages/cc/8d/8f271a7a034c834910ec925d56fa4b29733b1380f5289419f5aaa3b02777/pyarrow-25.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:c7c534ec03c358a76ea3e505e74c1b6aef290af90c444dfd092dbfe23e755b85", size = 35855328, upload-time = "2026-08-10T12:38:45.489Z" }, + { url = "https://files.pythonhosted.org/packages/d2/cd/5bac242f4e841b9971d5eb94fdfe2577e2b70be983e27401e72055786037/pyarrow-25.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:dda9470024204d7bbf2042b47c6e8a0e47a3eeb8e34405882dfaea6577e0c153", size = 37622415, upload-time = "2026-08-10T12:38:51.107Z" }, + { url = "https://files.pythonhosted.org/packages/63/1f/96d03b4e1506524f7087adb0fd6b2f69f0c9c7aaff1ec36d8030082e15a5/pyarrow-25.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:44a9120ce5bd81936b8ab9a88076e3fd47c2c6838e0e43630fed83626aca81d9", size = 46813813, upload-time = "2026-08-10T12:38:57.773Z" }, + { url = "https://files.pythonhosted.org/packages/98/d6/33a411115b61dbfc16ad6ad73e71730f6fea654ee3667673bc53ab0e2fe7/pyarrow-25.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:0befcf816e45a1af33ac775a9970b749e4868a230c7372f0ae5e932bee27039f", size = 50104452, upload-time = "2026-08-10T12:39:04.579Z" }, + { url = "https://files.pythonhosted.org/packages/33/ae/b1b97c9ca87f9f9ddbb5230c798df94eccce61bd79b9b45458c69a478588/pyarrow-25.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3f89685964f46e4216103c75483aac0c0692a5f72212d7ca835adba5ede56ce3", size = 49951343, upload-time = "2026-08-10T12:39:11.8Z" }, + { url = "https://files.pythonhosted.org/packages/98/9e/a112df5cfd5a68cb1d9fc31cfe38c28d5aec9f10865ce37ecef2e4450873/pyarrow-25.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6943e2fe7954d29d84de45d29d34c8dc36ce96570e67d89aa9976e650a4a9138", size = 53144784, upload-time = "2026-08-10T12:39:20.503Z" }, + { url = "https://files.pythonhosted.org/packages/31/24/97e8bd98f1e3b07e2ba08bcdff690674fbe16d69a7d2712cc3884665e615/pyarrow-25.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:31e49a7888fcdf3a835da33ae777f6bb9a866334e5a789282fc26dcf426f7f15", size = 27870159, upload-time = "2026-08-10T12:39:26.161Z" }, + { url = "https://files.pythonhosted.org/packages/36/4c/b525824ad3094076919273cd97db61fb3d78252dee76fa3b8dc8f76774aa/pyarrow-25.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:bf0b672390cdcb640d7288f96b826d71ff4e9abb254a86c89890baf51a29cee6", size = 35885255, upload-time = "2026-08-10T12:39:32.366Z" }, + { url = "https://files.pythonhosted.org/packages/08/62/448bb0e940de41aec31d1a956e63ad9c54afdf122a103cc3ab20c2a3ce33/pyarrow-25.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:38a9a4b4b9613380e200641891495a56c3d5a98a092db4a870af9975e220471d", size = 37644461, upload-time = "2026-08-10T12:39:38.142Z" }, + { url = "https://files.pythonhosted.org/packages/6e/9a/13587e38bd4806fd218f50fd13b8903fab60588a699ff0c406372e5b4043/pyarrow-25.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0b726ad7e7b669be982b0c71c07fe4b037d654354130da79a7902a669e93a66b", size = 46877146, upload-time = "2026-08-10T12:39:43.722Z" }, + { url = "https://files.pythonhosted.org/packages/8d/61/1c5d1229fa21da4cff5365e41e57177aaac57c563c727f35419b8513d1c1/pyarrow-25.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:9171748cdf796972d85a4b60157c279913e242992e350c90c7450182a9838b2a", size = 50131616, upload-time = "2026-08-10T12:39:49.304Z" }, + { url = "https://files.pythonhosted.org/packages/43/20/291e1d65cc0b09aa19f03cf25cf51a2f5fa94b5db315178f2d254ed5cad4/pyarrow-25.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:b7a296aac7a71fa0886c08e155ddb6c636a50013f801f6178daafa0f9e726188", size = 50008879, upload-time = "2026-08-10T12:39:56.891Z" }, + { url = "https://files.pythonhosted.org/packages/8b/7c/1b7c9ec28e76576337e4f97b31141c9a181b89b6d1d6221e9d8205621a58/pyarrow-25.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0fe7c8b6c03969b49c8c66182e4a18e3819ab92d07cfab5d8370c531b9369ef0", size = 53170864, upload-time = "2026-08-10T12:40:04.918Z" }, + { url = "https://files.pythonhosted.org/packages/b7/75/f3d789dc06011a765d14d86bda799cf72ac1d715b6a6edecaa0d73d95062/pyarrow-25.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:f729cfdbd36fd99d543b67a914d2de044c84ebe45be8b34902b299b608c15c8f", size = 28620729, upload-time = "2026-08-10T12:40:51.41Z" }, + { url = "https://files.pythonhosted.org/packages/fc/05/647a8ee6f7c2662feb6921315617bc04dcd6034763fb61b1199720bf6162/pyarrow-25.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:59a2de54c0cbd954da861eee4d1d330f8e909c45b53455baef696380f2c55033", size = 36130288, upload-time = "2026-08-10T12:40:11.014Z" }, + { url = "https://files.pythonhosted.org/packages/93/f8/c9ee997554d7bea94520667dd1933f109ac1da3ee3556d2b49381e023484/pyarrow-25.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:35935cd5de130aa5cf4dea052a63e6bf2e17006c35c3a468194242b9b2bf5956", size = 37762187, upload-time = "2026-08-10T12:40:16.592Z" }, + { url = "https://files.pythonhosted.org/packages/a2/08/a28c01c7fe9e96e8233ce2d13df1d402f4f999f848f51d2daacd6bb4c036/pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:f3831aaa25c67a99f99dc8b05873cb9d64560390372e2aa197ce9dd4a3f06a44", size = 46888003, upload-time = "2026-08-10T12:40:23.242Z" }, + { url = "https://files.pythonhosted.org/packages/1b/b9/58612e977d28dc58c878448866838369ee8da2f1e7cc8ed2c84b952aafee/pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:6a1fdfc6659b6b19022f2e50627fb5cf7156a66c46bf4299379955cbe742382a", size = 50079036, upload-time = "2026-08-10T12:40:29.169Z" }, + { url = "https://files.pythonhosted.org/packages/72/13/66e1402dcc860e1dc2760b1e0292c9a569b62b3bccab69def1b3e907d006/pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:169d3429d5be7c752125890620f75a60776d38b0035eddae939651640822332e", size = 50040226, upload-time = "2026-08-10T12:40:35.186Z" }, + { url = "https://files.pythonhosted.org/packages/78/10/3f1a5497a7ef732ab0f03ecca3e66d89d9c0f57fdc61b4794c456b781f01/pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:119297a6dc197e45d9c6d4415f7814a67ffa36c180d26f68c154c58067ae782d", size = 53149035, upload-time = "2026-08-10T12:40:41.454Z" }, + { url = "https://files.pythonhosted.org/packages/93/c0/37d4a7e8e2f7a6076283673d5298018ca26478b934c6ee369e10505ab32c/pyarrow-25.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:4288f27577352d608ca08553b0865e4a9b3aa14820c5d95b53337218d609835b", size = 28753071, upload-time = "2026-08-10T12:40:46.623Z" }, +] + +[[package]] +name = "pyarrow" +version = "26.0.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", +] +sdist = { url = "https://files.pythonhosted.org/packages/bc/5e/9cb2a56d5e293aab4e2fbecc5b0620d93227d66b8d5a63c554c31e1f80fe/pyarrow-26.0.1.tar.gz", hash = "sha256:93affcbd8a343e98dc19e9ec8fe17271ebf8fe98102d8b7454175074409f8b72", size = 1237985, upload-time = "2026-11-03T10:54:17.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/aa/459f3f5adebf6427a8bf1e976168f55793a3732ec1c6c6fe9e05a060b63b/pyarrow-26.0.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:9a62748f6b1f9f438706f0307acbb26e6a15010ea58f202c9d2725bc6eac0871", size = 37327168, upload-time = "2026-11-03T09:54:01.046Z" }, + { url = "https://files.pythonhosted.org/packages/5f/ed/29218597cb38aa9058dffda7906749df9e9da02b4c4da4e88dd8bcfa85eb/pyarrow-26.0.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:0187cbe6558cb158e148dd7b779f59cab6104163d148d808d04f293dc897b7ec", size = 39778863, upload-time = "2026-11-03T09:57:58.046Z" }, + { url = "https://files.pythonhosted.org/packages/03/f9/44489f525c73cc469f23fd02c0a3009882a8dcf45d0d9fb6ca1bb84a53e2/pyarrow-26.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:22a96a225de107eb9acd1ad9a818198ca832df2a4c0952412f754a7ed2105a98", size = 51836882, upload-time = "2026-11-03T10:48:50.544Z" }, + { url = "https://files.pythonhosted.org/packages/e6/87/6bf528898ef82dc3e8d762cbec7b42ae127a543895cc78c5df26a1f497f5/pyarrow-26.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:39cb0f2418282c24bea6ceda77b03e5a8f0a5766b63a8bf194d4e2a2c423548c", size = 55016622, upload-time = "2026-11-03T10:48:58.916Z" }, + { url = "https://files.pythonhosted.org/packages/97/e8/3b4898693744efb5aa60a859774ee3874a2635b288f309f1afb78a698f38/pyarrow-26.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:24350194bc83f1fde74aa321b6b43cd78bfdbfe613a795a6b9145fd4beaf4827", size = 55452257, upload-time = "2026-11-03T10:49:05.872Z" }, + { url = "https://files.pythonhosted.org/packages/86/96/bbeb5152a27406c65b80b72ecba4451fea18d549a5aea1fbb2c097d86b08/pyarrow-26.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ed1e19bfaf79565b74e3b0a45a0ba6d05620e68d5a5b48a8193c2bbee7cf5484", size = 58605344, upload-time = "2026-11-03T10:49:14.145Z" }, + { url = "https://files.pythonhosted.org/packages/bf/aa/afb7321eaed5f65332aa691fcd892bf67d0289e2ba884c8ce592d3188a26/pyarrow-26.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:5f681458e4fb81aefef50d3a8a432fe92f8480a87693616f9d95e95ceac8844c", size = 29034160, upload-time = "2026-11-03T10:49:19.45Z" }, + { url = "https://files.pythonhosted.org/packages/61/81/dc5814d61f8c956363e81bcaba61b4712a5d227324d40c766b3858160711/pyarrow-26.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:217497a51fd41abb74502ba2f4900872e0944c226945c02ee8a1cb4f81df3392", size = 37290209, upload-time = "2026-11-03T10:49:25.185Z" }, + { url = "https://files.pythonhosted.org/packages/f7/c8/dcc42b1cceb69ff032fa16430bd82c086b933e35ef05ab521e56313b76be/pyarrow-26.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:a2c5e9cec45b318917b630dc040cf197aef624d94866ab2c8e709708057123d2", size = 39757493, upload-time = "2026-11-03T10:49:30.886Z" }, + { url = "https://files.pythonhosted.org/packages/ab/7e/da9831bfcaaa908ae6d5d049c04c2233a5a7e216d6b961e22861056ef3fd/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:6c18167774fb599d42444b7ac558a893d49e750fb14232b538955e6f0d1d51ea", size = 51818506, upload-time = "2026-11-03T10:49:37.89Z" }, + { url = "https://files.pythonhosted.org/packages/d3/79/e2fc9b1317b7a21e7bcd57eb035cac3fe72f47af3efe2ec3b4dea9a08a04/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:c718bf97a92a6dea97fd1062c3b9f9e2e83cb9cc926e752289fa4ffff41738f9", size = 55043763, upload-time = "2026-11-03T10:49:45.732Z" }, + { url = "https://files.pythonhosted.org/packages/e3/66/dbe72f5fa21a92b645d56410bacac605defe63e5d3e9794b2fd8c7d77030/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:40aea57ab8bd3cf35a11e604cd7d0c7436dc90d1ce9b88b6711ef2f1a232968e", size = 55438656, upload-time = "2026-11-03T10:49:53.74Z" }, + { url = "https://files.pythonhosted.org/packages/d1/b1/c91322fc4c1800c1f7dd78f911b1dd74187acaeb246d86478a0f064f6af5/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:73534fbda7f73cab0791b569b93112d4c9e1546cedd0f309d1f69889beb6a08f", size = 58625736, upload-time = "2026-11-03T10:50:01.442Z" }, + { url = "https://files.pythonhosted.org/packages/30/61/d94decccacb4dd40a4ebeed0ff3b2cea8f0b680f50184ea7eb0264db779b/pyarrow-26.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:9379f0d1056cad6866c4697aec83a15830202ec7e0bd52f8bd508b316260fa61", size = 29078866, upload-time = "2026-11-03T10:50:06.854Z" }, + { url = "https://files.pythonhosted.org/packages/15/b8/c31c51fbe7df901817d88c73eeec25079d0da5f7c7b67fc0bf071f6a2df5/pyarrow-26.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:4cb739ccb87292c673e1f69819b68432a73bb8bb456e8599641bba9183a8a1dd", size = 37292947, upload-time = "2026-11-03T10:50:12.333Z" }, + { url = "https://files.pythonhosted.org/packages/fd/63/0c2559ae33ce59d2ca5ce74117676f8ff8da4cf102729a158ea46415eb50/pyarrow-26.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:50b40aea92f43b2b6da3427548a5337741b4b93b92e8015a8a3eefc0e75acca2", size = 39767535, upload-time = "2026-11-03T10:50:18.254Z" }, + { url = "https://files.pythonhosted.org/packages/31/02/d9462d1ae4e54c3964af38316a802b29c28970b7d375722ef190af736640/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a3a79661404ba3d41b7c9a45cb56113246a244b38cb1393fadae289bc66b91b4", size = 51815955, upload-time = "2026-11-03T10:50:25.332Z" }, + { url = "https://files.pythonhosted.org/packages/96/54/33c2df56948d88a4d83a52999a4a81a4871b2de481ff25ccd6f5ccd2589a/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:f71221bbc7707e3fad920d0478db9350791d4714ec445299ee0d56559fbc156c", size = 55038406, upload-time = "2026-11-03T10:50:32.551Z" }, + { url = "https://files.pythonhosted.org/packages/99/57/8e1f886ee96c7edab89ab6f15fbb00c85c2bb2173f3cb504925731d00564/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:8ccfb9958bcd09f34678c64fb42a0e270b47cd092ae79578da51e0d7bb144296", size = 55437362, upload-time = "2026-11-03T10:50:39.89Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c3/d87939a5f6cd30bb406bad6c20926fcedafc52ec5629f6eb27e4cd5db709/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:029e881af986375a2731da79c999fe734a72547fabb16503d65fc079d4bc7eb2", size = 58618865, upload-time = "2026-11-03T10:50:48.029Z" }, + { url = "https://files.pythonhosted.org/packages/c1/9e/b6c8afec2ffc06bbd00a88326826f9d66e4bbca752c0837ee8e2dbf2238f/pyarrow-26.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:8196f36a2f4cb8d2d6ef3651941b80e5ccf125d7653657d99af5bb298e7a7026", size = 28989592, upload-time = "2026-11-03T10:50:53.384Z" }, + { url = "https://files.pythonhosted.org/packages/de/48/999f6e30323e2e95a4439180b62f6308023970e4a37d31497080ea2a1a78/pyarrow-26.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:15435b595c14583f6ac8495c3ef89ac3fed6bc94f168467bfd3b6ba53ad3a643", size = 37334639, upload-time = "2026-11-03T10:50:59.462Z" }, + { url = "https://files.pythonhosted.org/packages/7f/3a/4458972c69ead95af5d3b701c80885133c351075895382499df49ed92d36/pyarrow-26.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:a44a244867cac106cd326dd0a04be0850d2b8af3b1418ed7aeb8146d13aba360", size = 39802150, upload-time = "2026-11-03T10:51:05.743Z" }, + { url = "https://files.pythonhosted.org/packages/86/d0/fa4bc5d66f78cbc4ec8482b210c2fc3b8cb59564efe171f3ca9be416f8ee/pyarrow-26.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0044cb9303c3ae082cc52a2493312109c955bcfa84e87be768736f7d6d8f6257", size = 51880097, upload-time = "2026-11-03T10:51:12.75Z" }, + { url = "https://files.pythonhosted.org/packages/f3/57/755a1b54d37c2a9e2c283d8bc648a50aa4ce57f977ce6a4b1d65eba29f51/pyarrow-26.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:7ae48ab53610b85e004b03bccff593fbdf22186d0ab48ed42c90797915dac814", size = 55063542, upload-time = "2026-11-03T10:51:20.417Z" }, + { url = "https://files.pythonhosted.org/packages/45/ba/7cd1d78c2ef5a36b1f8d137d1790179875639f197ed90702268084a2470a/pyarrow-26.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a97df0c52c966ae8970ac0899ae75d81083c5400eca267de2608ca0f13e6e118", size = 55490507, upload-time = "2026-11-03T10:51:28.295Z" }, + { url = "https://files.pythonhosted.org/packages/9f/02/39e18c5381ad908d7161cc16a02dce03b3db236d3c3ac99fc020878287fb/pyarrow-26.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5f665e73790222779613ae3d23d2a1d72f0f13a4646862277e9784bb46e14fca", size = 58648328, upload-time = "2026-11-03T10:51:36.303Z" }, + { url = "https://files.pythonhosted.org/packages/1c/18/2cd453cc2e282d465e9c9b60834d6ca17601dc08e2d402751cb40af92356/pyarrow-26.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:492dc499097968e51cac46e03e0054c68dd3c5f39d75098343f5ad05ec79f7df", size = 29757743, upload-time = "2026-11-03T10:52:35.061Z" }, + { url = "https://files.pythonhosted.org/packages/db/46/b97f117adb46f93620aa94bf13747a81ccc5e099be534cc195c94b281ba7/pyarrow-26.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:ec196b35270263eda71fc3f43bd31a89b778c6787f19872df5abb9d4264057ff", size = 37452099, upload-time = "2026-11-03T10:51:42.419Z" }, + { url = "https://files.pythonhosted.org/packages/a6/40/ac1796654fc8591049d200f6bcd646a2319509010784f47c1cf6b09d1000/pyarrow-26.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:8af2b4e004dc18da8dc77bce27d97c675d2f71348e3ade2741cecac85c3f0c21", size = 39888805, upload-time = "2026-11-03T10:51:48.766Z" }, + { url = "https://files.pythonhosted.org/packages/6c/93/bcff79148416896738a707992570c4ae8e3bb087bc9e0dca8df7dbf6e983/pyarrow-26.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:c2bf4444a7e86f109dc03e28b2c98eb6671e2eb95e6057c25043d25684e337e9", size = 51884587, upload-time = "2026-11-03T10:51:56.701Z" }, + { url = "https://files.pythonhosted.org/packages/fa/62/cb05e81d31cd1dc97c2e16151425e61fe3a19274ccd1254cafab3a173f96/pyarrow-26.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:b121de63e2f92704b6b9881fbe69cb3eeca786ea882379b59ce80b8012c1bd8c", size = 55018252, upload-time = "2026-11-03T10:52:05.813Z" }, + { url = "https://files.pythonhosted.org/packages/f8/f5/e8dbbb803bb28a32411491d502679e272c569af7f590816327e84725c748/pyarrow-26.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:40b9c1a5841559030ba8d1b8c15d6160bccb702ff2596b4ce296e1efd7665781", size = 55522075, upload-time = "2026-11-03T10:52:14.577Z" }, + { url = "https://files.pythonhosted.org/packages/9b/7a/5000d6082b116359d3db3ee6073a8f708f41cb4bb7d6414f94cd40a90fe7/pyarrow-26.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9519f70bd847f7628a2d16324d1ea8827e2ec1da347ee0bf96cc7c248195e923", size = 58625604, upload-time = "2026-11-03T10:52:23.045Z" }, + { url = "https://files.pythonhosted.org/packages/41/70/74a5a07eeee1a84cd51e81813b7fd2d5ffc90192a95981a51e97a8ced99e/pyarrow-26.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:6d9b558e1bce3270f1f422c61fd682615cfb34ffd320a51e765e868e8c155a72", size = 29925653, upload-time = "2026-11-03T10:52:29.188Z" }, + { url = "https://files.pythonhosted.org/packages/77/09/4e9461479930e3f4367cc0b4f4356d4444a23be9cb350272b159cd0c7fa9/pyarrow-26.0.1-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:2c118754a0abe0bf20ef17432f95534ebb0ded37a48b6e8690cdd02625a86d97", size = 37329458, upload-time = "2026-11-03T10:52:41.622Z" }, + { url = "https://files.pythonhosted.org/packages/40/5a/9e44840924b0939defacc2561e54dc9aba10eff1fc5dadcf41921202d99f/pyarrow-26.0.1-cp315-cp315-macosx_12_0_x86_64.whl", hash = "sha256:99574d8eabad06cc4bb3fed327b298c8a44a3596abd2d575738fa019df7ac59e", size = 39799948, upload-time = "2026-11-03T10:52:47.507Z" }, + { url = "https://files.pythonhosted.org/packages/70/3a/5fe40369653a082d86fdb6ce2b7c40a4ef435d90a68da60c05dda0c554fc/pyarrow-26.0.1-cp315-cp315-manylinux_2_28_aarch64.whl", hash = "sha256:12c5edbdf9b8a0f121a0a222be150c3a711149bc4322736d6a04693fbfd8c723", size = 51875337, upload-time = "2026-11-03T10:52:54.59Z" }, + { url = "https://files.pythonhosted.org/packages/5e/87/f768a458cf975c17c73912fb25a1e0693ceef8d76d78cf83ffdf1f63ec70/pyarrow-26.0.1-cp315-cp315-manylinux_2_28_x86_64.whl", hash = "sha256:8cb5bcfe627ee6b910fbec27871d38cf4f28f331ea6328902ce6a6272851ac70", size = 55060370, upload-time = "2026-11-03T10:53:02.19Z" }, + { url = "https://files.pythonhosted.org/packages/e0/30/280c24a7da9085b782cd6960ccae6763b0170f51385b9122385c12226ff2/pyarrow-26.0.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:e2ee5f01f84996109405759cba8bb92a16455c50deb6526a535ab3b8d5f4e326", size = 55488705, upload-time = "2026-11-03T10:53:09.8Z" }, + { url = "https://files.pythonhosted.org/packages/42/e7/8e7b7f7bd58c88fd8da93db0d0869c69175c3ddccf365afbcc13fbd691da/pyarrow-26.0.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e25d4a886868c5ce136d194f308bd690e1335aebf6b8bcae3511b0becdb3a65a", size = 58646822, upload-time = "2026-11-03T10:53:17.902Z" }, + { url = "https://files.pythonhosted.org/packages/3b/c7/6094fa2c0b5602d81b1177ac7f5b2de8a386862d08e57a75931da774f3e0/pyarrow-26.0.1-cp315-cp315-win_amd64.whl", hash = "sha256:6cdad5f67a30bbcea54c3c2a27ea45bd5a170377bf45f80f4d7e3a726e8e3283", size = 29755706, upload-time = "2026-11-03T10:54:14.582Z" }, + { url = "https://files.pythonhosted.org/packages/41/0f/86747650c8218bcea7443884e7c8ba9d3fe9a13fb5a4be99acdd5c2b9144/pyarrow-26.0.1-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:12dc85cec96aa62d429d7c43749c072e9330c373b67d6ee458edeef444c8941f", size = 37445268, upload-time = "2026-11-03T10:53:25.531Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ec/4159b2362267009b754a7c2f138f16bdfd6623b308005678eb7cf1b65863/pyarrow-26.0.1-cp315-cp315t-macosx_12_0_x86_64.whl", hash = "sha256:52e4daba8f1b4316b7b9ba7e84903a339cbc52998ebddc9a7c78b5ea37c23bbb", size = 39877540, upload-time = "2026-11-03T10:53:33.046Z" }, + { url = "https://files.pythonhosted.org/packages/a8/0e/df0501e93eef78402f94f33f948aba996181b3d3c54f97a3f16544916d05/pyarrow-26.0.1-cp315-cp315t-manylinux_2_28_aarch64.whl", hash = "sha256:322f6fc80c6db1ec87c9d905df3ce259cd22e922f47fbad3c58d0dd6f63bc7a9", size = 51874165, upload-time = "2026-11-03T10:53:41.281Z" }, + { url = "https://files.pythonhosted.org/packages/fb/30/0d43bf6a49fca51142a96c73d693ec34d229c902a46e007c25f3b9798b52/pyarrow-26.0.1-cp315-cp315t-manylinux_2_28_x86_64.whl", hash = "sha256:68b91f34e3424d55564e9d4d4f7491aaebd6db3998039cc33ba795a63167f04e", size = 55012741, upload-time = "2026-11-03T10:53:49.153Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ff/0e6cd73832d97c3852284eda9bee2428c53a92bcf6f6aa4bda1e15314a59/pyarrow-26.0.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b801300d65859adaf611c9c0a4cb39bd3cb1713b60b974ad20650a8a0f8af2fd", size = 55512474, upload-time = "2026-11-03T10:53:56.512Z" }, + { url = "https://files.pythonhosted.org/packages/f0/1e/43cdcf9719169f0228b3e516e5004ed0acfc3a4c70ce35e3f2a80a485baf/pyarrow-26.0.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:2623b6c20637c0e2c40be96bda3d127dde49d6e6734ad6e71df91a013e40a3c4", size = 58616300, upload-time = "2026-11-03T10:54:04.472Z" }, + { url = "https://files.pythonhosted.org/packages/df/bf/8e29b47c61fc961e92e96db129d5dc7b716c2091dfe05359e70f20d712b9/pyarrow-26.0.1-cp315-cp315t-win_amd64.whl", hash = "sha256:55b1d871f21c8ed249c93f7375a35c35aa9b7b3af6896405cb8a6b67ad9bc7f9", size = 29909417, upload-time = "2026-11-03T10:54:09.613Z" }, ] [[package]] @@ -3742,7 +4104,8 @@ name = "pyarrow-stubs" version = "20.0.0.20260625" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyarrow" }, + { 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'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ff/7d/a3eadf94131428ec61b44bc40a52acca2b093bf0f6a90a0596c44aa9fe62/pyarrow_stubs-20.0.0.20260625.tar.gz", hash = "sha256:cae81ae0900d0710e5b8a6271fef34ccfacb08663bb5f805d94f129baf13130e", size = 237707, upload-time = "2026-06-25T07:27:47.496Z" } wheels = [ @@ -3921,14 +4284,14 @@ wheels = [ [[package]] name = "pyjwt" -version = "2.13.0" +version = "2.15.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/3b/81/58d0ac84e1ef3a3843791d6954d94c0b33d526c75eeb1efbce9d0a4c4077/pyjwt-2.13.0.tar.gz", hash = "sha256:41571c89ca91598c79e8ef18a2d07367d4810fbbd6f637794879baf1b7703423", size = 107515, upload-time = "2026-05-21T19:54:36.618Z" } +sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274, upload-time = "2026-05-21T19:54:35.362Z" }, + { url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" }, ] [package.optional-dependencies] @@ -3938,20 +4301,22 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b6" +version = "15.0.0b15" 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" }, + { 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_2jARvj/pylance-15.0.0b6-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:88bd0646118c57e1c0a3118d04162323a74ebea28578f362977c927cdcb0f0c9" }, - { url = "https://pypi.fury.io/lance-format/-/ver_28yD6d/pylance-15.0.0b6-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:66613ecb88dcb8e02f0cd21d241987018d924b9f587cef4015bf7ea1815ab44f" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1Us94M/pylance-15.0.0b6-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:d0765efab1f21b4697207ab75b9d391f1962813afb08e78db794eeea280c0bcc" }, - { url = "https://pypi.fury.io/lance-format/-/ver_ccoue/pylance-15.0.0b6-cp310-abi3-win_amd64.whl", hash = "sha256:f21eb48c6ec5d2269bb1817b2c0bb036956383d05033fb54278c4df64251ead4" }, + { url = "https://pypi.fury.io/lance-format/-/ver_29HO58/pylance-15.0.0b15-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:46c870c3d650f911eccb7406ec77f72fa448f80b2f827ff35dd86bbc0b9e08ca" }, + { url = "https://pypi.fury.io/lance-format/-/ver_OBkXR/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b3f418584cdee98d27aac538ebe5203051a0b78a98668aff22bc29aebe3dd3c9" }, + { url = "https://pypi.fury.io/lance-format/-/ver_TMbLm/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3656d52ba65d297b41f1973d1a3efbb888f761cf7c934ff15e0c1aecc560b2d5" }, + { url = "https://pypi.fury.io/lance-format/-/ver_mmYmR/pylance-15.0.0b15-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a50d06e3a86d68acf8edf5a83736890a648a16a1cb8c8ccde9ef5b6c82ebef76" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1aYiTc/pylance-15.0.0b15-cp310-abi3-win_amd64.whl", hash = "sha256:6451499f0612d0326d54168bedcc6df29c1e0700c4f92902f5f00a6ecdf17745" }, ] [[package]] @@ -3967,6 +4332,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d6/54/da572c98c0b77626a91b5d3b89f0231d8bff5125c225420908632f8b342d/pymdown_extensions-11.0.1-py3-none-any.whl", hash = "sha256:db3943a62bab7e03af1364f0c4083e64b91fb097675a4b6cceccfbe9a77e5eb2", size = 269455, upload-time = "2026-07-02T17:59:21.271Z" }, ] +[[package]] +name = "pyopenssl" +version = "26.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3f/e8/7325d258199b159eb2c03fe32107533e2832e70e63f4fb88a6aa00023201/pyopenssl-26.4.0.tar.gz", hash = "sha256:28dfcce0162b9211413e26dfbfdf1d24317fbeba18fc93c12400a1856b2a0bc7", size = 182046, upload-time = "2026-08-01T19:50:50.512Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/ad/2cf6d3fa2fae5c79e1ed9960c0d42badd0f94d81dd12b50604cdc839e648/pyopenssl-26.4.0-py3-none-any.whl", hash = "sha256:f0eb0cb2d581d3ad2b9c489468485e7f2ab6727d08401bcf9d824c3caddf3c1c", size = 56026, upload-time = "2026-08-01T19:50:48.94Z" }, +] + [[package]] name = "pyright" version = "1.1.411" @@ -4049,6 +4427,47 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/28/78/9b77ecb4644d1bbea94d29abf78f21c47eca6eb79e9745b702ec0bed2e19/python_discovery-1.4.3-py3-none-any.whl", hash = "sha256:b6e1e4a7d9e3f6948c39746ffe8218225162d738ba39d05ab1d2f6c1cac4878c", size = 33885, upload-time = "2026-07-03T13:21:50.174Z" }, ] +[[package]] +name = "python-pkcs11" +version = "0.9.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "asn1crypto" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/89/33/4287ebdcbdcae6f93521be56ffdd5f474b6aebda1a50df4c4b9870a140fa/python_pkcs11-0.9.4.tar.gz", hash = "sha256:3d950aadefa473b880dc75f01539133487e65ec2a97db1e955c4f6bef1bd71d5", size = 180658, upload-time = "2026-04-13T13:32:51.769Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/36/98/6da01b81312c481f743b675577ae64ee1887a7d1c6ca4294b136a189f581/python_pkcs11-0.9.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:fbf1436684a74b2b26cb5f51e970f2505d81bac74ee084641b625d956f08af29", size = 558896, upload-time = "2026-04-13T13:31:51.089Z" }, + { url = "https://files.pythonhosted.org/packages/4a/b3/ffa8d044bf9831c20a7a9e305117cde8512c6ccdf26d5e95a605dc7bc5c6/python_pkcs11-0.9.4-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c2b1af32dad1457250959d42093e05ebc98f94f62d4c2393d72eef0c73c846c7", size = 1833458, upload-time = "2026-04-13T13:31:52.714Z" }, + { url = "https://files.pythonhosted.org/packages/bc/f7/d73bbfc9cca5a6837b7fce2aebf4a71290bacbcf31709271ff81faa92744/python_pkcs11-0.9.4-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2ac2f25bc27b618f8f1d17b4d6cd5887e4202ee32edec206052d6f46943f8990", size = 1851767, upload-time = "2026-04-13T13:31:54.673Z" }, + { url = "https://files.pythonhosted.org/packages/5d/b6/08a12c496ec6e49a40afc9aaad526b110a99e778822295778359fc2a1161/python_pkcs11-0.9.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:a3edf4ae24def328f454d38dffef1677baec69d376755523d4e56280fc177173", size = 1779639, upload-time = "2026-04-13T13:31:56.744Z" }, + { url = "https://files.pythonhosted.org/packages/bd/78/1792a808dd3aeeb46acfdcd2d28084d22c7648ce7b7cb925fc1c78b07052/python_pkcs11-0.9.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:975389457f533bdbaa96b845e9517ef6c4cdaed627a54515fb77165014399c27", size = 1830315, upload-time = "2026-04-13T13:31:58.715Z" }, + { url = "https://files.pythonhosted.org/packages/9f/ed/80063318f6fc8f775200add5eefb0a2b6dcf6bdc5da89b562c8d5530cb9c/python_pkcs11-0.9.4-cp310-cp310-win_amd64.whl", hash = "sha256:8ed0225ae59ec061575076bf67db4bd2b4b71e1157462fed4c7c10f11bd6709d", size = 284002, upload-time = "2026-04-13T13:32:00.268Z" }, + { url = "https://files.pythonhosted.org/packages/00/10/e2f33f3acca84b72d36b7bc66f62f2eac9b12b61268fb1a3c452ca084fcf/python_pkcs11-0.9.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:585bfeaafd12db0875fa74e2c4cbe8b055a75a6c359f873a4777deefbcbb2c6f", size = 557105, upload-time = "2026-04-13T13:32:01.725Z" }, + { url = "https://files.pythonhosted.org/packages/db/e6/fd48a495d57f488976b0871f1c08efed1a19722aadea253a49b989c611b1/python_pkcs11-0.9.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b8bff8267d1e5813c591290b02c1c7e700786b94a3ba750fda5f8d44f9fc7191", size = 1916836, upload-time = "2026-04-13T13:32:03.486Z" }, + { url = "https://files.pythonhosted.org/packages/bc/d2/a627fdd228c1253e25f9dd4b6facf3499cb7b2d76260bf337b1f84cb1bd2/python_pkcs11-0.9.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54399a5235c427c25f654c89f451648084dbabe0696bf9e685e86c741460857b", size = 1935363, upload-time = "2026-04-13T13:32:05.101Z" }, + { url = "https://files.pythonhosted.org/packages/3c/c0/3430e1d3cdd1f684cc9766030867d850fd75fd810c4729d7b93b6fed3648/python_pkcs11-0.9.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b1e9d98d5b4f732eba6503260afe805053fbd67663bd00184cdc8c478f26625a", size = 1865096, upload-time = "2026-04-13T13:32:06.759Z" }, + { url = "https://files.pythonhosted.org/packages/5b/de/1afe8d791787e00212d35895919328e8d6381379f5421f5f1cd5897aa089/python_pkcs11-0.9.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:afe3d78afa6cf30c6a26bfe4e9215500809c3b76f7561d809100e367d7a22dd4", size = 1914261, upload-time = "2026-04-13T13:32:08.923Z" }, + { url = "https://files.pythonhosted.org/packages/58/f4/7b207d44a1f21352018225396e8b8e4dc7763c4975eecfcfa27375188bba/python_pkcs11-0.9.4-cp311-cp311-win_amd64.whl", hash = "sha256:ed40fc57d78714e3281da4e6ee67fb8aebe677a83c9430af3a1d5defa16e9201", size = 284870, upload-time = "2026-04-13T13:32:10.731Z" }, + { url = "https://files.pythonhosted.org/packages/f4/af/1b6525ba52b7216e28fd2ccc0802fd1382a5f672c8d86e7f5dd0feff164c/python_pkcs11-0.9.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:aa22cd0d172a560618134943784ee6a405b578d187b41d7cc66dc43d8f482dbf", size = 523923, upload-time = "2026-04-13T13:32:12.145Z" }, + { url = "https://files.pythonhosted.org/packages/ad/6a/c199375fdda4e5ac1e630f05500f528c651d2377c48e0ecaa0d13fefd93c/python_pkcs11-0.9.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e05cb5d780bbccdee2588be4fc98c977e4f2024a70ae70a1a109d47a9afd525b", size = 1847563, upload-time = "2026-04-13T13:32:13.803Z" }, + { url = "https://files.pythonhosted.org/packages/71/54/fe792b7ce715866c210a9263464e776dc28c1b8424d9c2e96b6f6cc3daeb/python_pkcs11-0.9.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f49715b81b7afaaa8efaa9d91ed0c1eaac34f190a908347e42d4530da1bc5eb", size = 1895189, upload-time = "2026-04-13T13:32:15.763Z" }, + { url = "https://files.pythonhosted.org/packages/d0/5d/e30b3664794c5d49e995831a536d456a92c283eb73e5c933226d83ad3125/python_pkcs11-0.9.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:050ee672467aa885de79ad4f1f57e4a16f2bca9b4fcac42c72e14e31d5ba700f", size = 1780227, upload-time = "2026-04-13T13:32:17.632Z" }, + { url = "https://files.pythonhosted.org/packages/79/7a/f781c7360eecc96e8331cb9e8c38a43c7bcfcb03b075ef520cd8575c76ff/python_pkcs11-0.9.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2bbab746a84f15a0727e017289e074a322c061cf0203fa2706729bde9ac60648", size = 1854335, upload-time = "2026-04-13T13:32:19.181Z" }, + { url = "https://files.pythonhosted.org/packages/ea/36/e3652bbaa37fde1444ee861e82448d351f89bb8672577394bbe9c8a4cde6/python_pkcs11-0.9.4-cp312-cp312-win_amd64.whl", hash = "sha256:91fe4e11c7187e548293dc5c020f69665304ebdaa5724b7806251c6473d70004", size = 274412, upload-time = "2026-04-13T13:32:20.762Z" }, + { url = "https://files.pythonhosted.org/packages/d2/a9/52150a1bd0c01d16e73de557fc25aa3d682c4bda6ee6931fabfbaf681550/python_pkcs11-0.9.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:38e80866d35e3d591972af796d2fd2557a4071b1586d4f79e14d93ab61e60425", size = 521406, upload-time = "2026-04-13T13:32:22.107Z" }, + { url = "https://files.pythonhosted.org/packages/34/88/e0eb7702d369f9844df6a341f5f31ecade2f5463a32290fb291270d0c766/python_pkcs11-0.9.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dcb7f6e08a5c2a9a0c6f557b829bba12dd4ae6489d2d65e92cea222650ca3160", size = 1852110, upload-time = "2026-04-13T13:32:23.47Z" }, + { url = "https://files.pythonhosted.org/packages/48/44/ada8dd48e7fc4db5d5f715b9206bdf8bbbe756592fe0206574c8f68253a0/python_pkcs11-0.9.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3f700992fe99a147fc64a6003999615337e5e1fe27c5f381b0d91c1a68db6967", size = 1889010, upload-time = "2026-04-13T13:32:24.989Z" }, + { url = "https://files.pythonhosted.org/packages/07/36/4ebdc96f660228dc0810db4b81db6fbad6a929656c130ef8fd366cebf275/python_pkcs11-0.9.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3680ad0ac2a48dddd5ffdc87d2bfefe5a1995f8db26d5aa69e985771b5a2ab66", size = 1790342, upload-time = "2026-04-13T13:32:26.836Z" }, + { url = "https://files.pythonhosted.org/packages/9f/cb/8850277a94b434918c742c4a55704c5d105fe94b88201906624a69b298a5/python_pkcs11-0.9.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3912989be7e9c10c330fe13a663baeab568f222addbe612e4183409b20bffc36", size = 1852955, upload-time = "2026-04-13T13:32:28.846Z" }, + { url = "https://files.pythonhosted.org/packages/3c/0c/f75061daf8ae64b340235f6afe206a0d23f148c0e3de98d384ecd7527d8d/python_pkcs11-0.9.4-cp313-cp313-win_amd64.whl", hash = "sha256:2d2b5827fb888fc388c2026e040c14a257c41ba97d543fbf08b5730aad0c6899", size = 275081, upload-time = "2026-04-13T13:32:30.603Z" }, + { url = "https://files.pythonhosted.org/packages/e8/04/aa4c33e3d14612d3855dd3f6f72f6ef9db82d1575a387fce8a22678fe908/python_pkcs11-0.9.4-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:0e1c88481eeada4fd81cfefe117413137a2868cc072e588c05972aca92020cc8", size = 524552, upload-time = "2026-04-13T13:32:32.124Z" }, + { url = "https://files.pythonhosted.org/packages/a3/fd/eaf6527c25c116a29fec54776634c1afc7cb9326a2e07c1af1f9f843494e/python_pkcs11-0.9.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5c24e6a25ee6756f8116960a9b0757c54dc355ae1b86ec47a0704bde5c6ee62", size = 1847496, upload-time = "2026-04-13T13:32:33.562Z" }, + { url = "https://files.pythonhosted.org/packages/82/d7/711f205660a4a6ce4f2e937b2fe1bd9f1274449658a07cd050cfb4ed9507/python_pkcs11-0.9.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2351da910df98e6b9f4befdafbfc2c81fc9c86358ec88dd802e67e6e3ae85f33", size = 1865861, upload-time = "2026-04-13T13:32:35.23Z" }, + { url = "https://files.pythonhosted.org/packages/de/51/43be836fb48a87e8589adddd47fbee86c0b0c09b9edd60ea267cc7fefc55/python_pkcs11-0.9.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7081ec0a3456a40abcde382c8b64048b922076391e9ae90a272a970c96dc10c8", size = 1783570, upload-time = "2026-04-13T13:32:37.357Z" }, + { url = "https://files.pythonhosted.org/packages/b3/05/492e46d0f60bccebed71f4e3429a55842ad5989e07d9ad98989d762d9455/python_pkcs11-0.9.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:16aba462e30169a9898f51532297aad94f13ee944873fa48eb2504b6efaf373d", size = 1830078, upload-time = "2026-04-13T13:32:38.897Z" }, + { url = "https://files.pythonhosted.org/packages/53/ef/4b95b463e48fd2474e6c51446ea45d9b7042b8a67b5abc1e06bfbfbc8595/python_pkcs11-0.9.4-cp314-cp314-win_amd64.whl", hash = "sha256:d13f9a6b76d56ff5628a85530aab7b021e9f90e3300be985423b69301c6aae38", size = 280929, upload-time = "2026-04-13T13:32:40.712Z" }, +] + [[package]] name = "pytz" version = "2026.2" @@ -4376,7 +4795,9 @@ name = "rpds-py" version = "0.30.0" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version < '3.11'", + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", ] sdist = { url = "https://files.pythonhosted.org/packages/20/af/3f2f423103f1113b36230496629986e0ef7e199d2aa8392452b484b38ced/rpds_py-0.30.0.tar.gz", hash = "sha256:dd8ff7cf90014af0c0f787eea34794ebf6415242ee1d6fa91eaba725cc441e84", size = 69469, upload-time = "2025-11-30T20:24:38.837Z" } wheels = [ @@ -4503,9 +4924,15 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.12' and python_full_version < '3.14'", - "python_full_version == '3.11.*'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } wheels = [ @@ -4704,7 +5131,9 @@ name = "scikit-learn" version = "1.7.2" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version < '3.11'", + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", ] dependencies = [ { name = "joblib" }, @@ -4753,9 +5182,15 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.12' and python_full_version < '3.14'", - "python_full_version == '3.11.*'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] dependencies = [ { name = "joblib" }, @@ -4805,7 +5240,9 @@ name = "scipy" version = "1.15.3" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version < '3.11'", + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", ] dependencies = [ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, @@ -4864,7 +5301,9 @@ name = "scipy" version = "1.17.1" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version == '3.11.*'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] dependencies = [ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, @@ -4940,8 +5379,12 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.12' and python_full_version < '3.14'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", ] dependencies = [ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" } }, @@ -5348,7 +5791,8 @@ dependencies = [ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "pillow" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "torch" }, ] wheels = [ @@ -5522,11 +5966,11 @@ wheels = [ [[package]] name = "urllib3" -version = "2.7.0" +version = "2.8.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, ] [[package]] diff --git a/release_process.md b/release_process.md index a1130fdf7..55521774e 100644 --- a/release_process.md +++ b/release_process.md @@ -1,8 +1,9 @@ # Release process -We release four `lancedb` packages: Python, Rust, Java, and Node.js. +We release four `lancedb` SDK packages (Python, Rust, Java, and Node.js) and +standalone `lancedb` command-line binaries. -All four share a single version number, defined by `current_version` in +All SDKs and the CLI share a single version number, defined by `current_version` in `.bumpversion.toml`. One `vX.Y.Z` tag releases all of them, so a breaking change in any SDK bumps the minor version for every SDK. @@ -84,7 +85,10 @@ The workflow creates a new version commit and tag. Compare that tag with the validated candidate and check that only the expected mechanical version and lockfile updates were introduced. Code or dependency changes require renewed validation. Verify all four SDK publishing workflows and the exact registry -artifacts before reporting the stable release as complete. +artifacts, plus the three CLI archives and their `SHA256SUMS` on the GitHub +release, before reporting the stable release as complete. Download the CLI +archives, verify their checksums, and confirm their reported versions on the +corresponding platforms. ## Making releases @@ -95,7 +99,7 @@ The release process uses a handful of GitHub actions to automate the process. │Create Release Commit│ └─┬───────────────────┘ │ ┌──────────────┐ - └──►(tag) vX.Y.Z ─┬─►│GitHub Release├───►GH Release + └──►(tag) vX.Y.Z ─┬─►│GitHub Release├───►CLI packages + GH Release │ └──────────────┘ │ ┌────────────┐ ├─►│PyPI Publish├─────►Python Wheels @@ -134,6 +138,38 @@ Select `bump-minor` according to the version and breaking-change check below. > is needed and fail the `Create Release Commit` job. To fix, select the > "bump minor version" option. +### CLI release packages + +The GitHub Release workflow calls **CLI release packages** before creating the +release. Both stable and beta tags produce these archives: + +* `lancedb-v-x86_64-unknown-linux-gnu.tar.gz` +* `lancedb-v-aarch64-unknown-linux-gnu.tar.gz` +* `lancedb-v-aarch64-apple-darwin.tar.gz` + +Each archive contains a matching top-level directory with the `lancedb` +executable, `LICENSE`, and `RUST_THIRD_PARTY_LICENSES.html`. Linux builds target +glibc 2.28; x86_64 retains the repository's Haswell/AVX2 CPU requirements. macOS +builds target Apple Silicon on macOS 14 or newer. + +Packaging runs on relevant PRs without publishing. To dry-run packaging on a +candidate branch before merging or tagging, run: + +```bash +gh workflow run cli-release.yml --repo lancedb/lancedb --ref +``` + +Inspect the `cli-release` workflow artifact: it must contain all three archives +and a matching `SHA256SUMS`. The workflow checks runtime library compatibility +and runs the extracted executables; Linux also runs on a clean AlmaLinux 8 +system. A tag must match both the CLI and SDK manifests before any build starts. + +A CLI packaging failure blocks GitHub release creation. SDK registry workflows +run independently. Fix the failure and rerun the failed GitHub Release jobs; +the publishing job replaces assets with matching names on an existing release. +Verify beta releases remain marked as prereleases and do not take the latest +release designation. + ## Breaking changes We try to avoid breaking changes, but sometimes they are necessary. When there diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 64252f772..6f5d45232 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.17" +version = "0.42.0-beta.9" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true @@ -74,7 +74,7 @@ aws-smithy-types = { workspace = true, optional = true } # Default features include the legacy `rustls` feature, which pulls in rustls 0.21. aws-sdk-bedrockruntime = { version = "1.77.0", optional = true, default-features = false, features = ["default-https-client", "rt-tokio"] } # For remote feature -reqwest = { version = "0.13.0", default-features = false, features = [ +reqwest = { workspace = true, features = [ "charset", "gzip", "http2", @@ -101,16 +101,18 @@ hf-hub = { workspace = true, optional = true, features = [ "tokio", "ureq", ] } -candle-core = { version = "0.9.1", optional = true } -candle-transformers = { version = "0.9.1", optional = true } -candle-nn = { version = "0.9.1", optional = true } +candle-core = { version = "0.11.1", optional = true } +candle-transformers = { version = "0.11.1", optional = true } +candle-nn = { version = "0.11.1", optional = true } tokenizers = { version = "0.19.1", optional = true } semver = { workspace = true } -roaring = "0.11.4" +roaring = { version = "0.11.4", features = ["serde"] } sha2.workspace = true [dev-dependencies] anyhow.workspace = true +# `test-util` adds the per-request records that the `assert_io_*` macros print. +lance-io = { workspace = true, features = ["test-util"] } lance-testing = { workspace = true } # RestAdapter is only used by cfg(test) code. Keep rest-adapter off the # production remote feature so Python wheels do not resolve its Axum 0.7 stack. diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index df9291647..601d0f58b 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.1.0" +version = "0.42.0-beta.9" edition = "2021" license.workspace = true repository.workspace = true diff --git a/rust/lancedb/cli/src/auth.rs b/rust/lancedb/cli/src/auth.rs index 090bfd1d8..18eab7c20 100644 --- a/rust/lancedb/cli/src/auth.rs +++ b/rust/lancedb/cli/src/auth.rs @@ -221,7 +221,7 @@ impl ManagedOidc { async fn sdk_config(&self) -> Result { let flow = match self.config.flow { OidcFlow::ClientCredentials => OAuthFlow::ClientCredentials, - OidcFlow::DeviceCode => OAuthFlow::DeviceCode, + OidcFlow::DeviceCode => OAuthFlow::DeviceCode(Default::default()), OidcFlow::AuthorizationCode => { let mut options = AuthorizationCodeOptions::new(); if let Some(uri) = &self.config.redirect_uri { diff --git a/rust/lancedb/cli/src/main.rs b/rust/lancedb/cli/src/main.rs index 01f65e386..a128587c3 100644 --- a/rust/lancedb/cli/src/main.rs +++ b/rust/lancedb/cli/src/main.rs @@ -5,6 +5,7 @@ use clap::Parser; #[tokio::main] async fn main() -> anyhow::Result<()> { + lancedb::docs::set_sdk_ident("cli", env!("CARGO_PKG_VERSION")); let _ = rustls::crypto::ring::default_provider().install_default(); lancedb_cli::run(lancedb_cli::Args::parse()).await } diff --git a/rust/lancedb/cli/tests/command_surface.rs b/rust/lancedb/cli/tests/command_surface.rs index 9d2f9c50e..474aadb09 100644 --- a/rust/lancedb/cli/tests/command_surface.rs +++ b/rust/lancedb/cli/tests/command_surface.rs @@ -3,6 +3,21 @@ use std::process::Command; +#[test] +fn version_matches_the_release() { + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .arg("--version") + .output() + .unwrap(); + assert!(output.status.success()); + assert_eq!( + String::from_utf8(output.stdout).unwrap().trim(), + format!("lancedb {}", env!("CARGO_PKG_VERSION")) + ); + assert_eq!(lancedb_cli::build_version(), env!("CARGO_PKG_VERSION")); + assert!(output.stderr.is_empty()); +} + #[test] fn an_unconfigured_default_sql_invocation_prints_usage() { use lancedb_cli::server_config::{Config, Profile}; diff --git a/rust/lancedb/src/authz/mod.rs b/rust/lancedb/src/authz/mod.rs index 3191627e0..f53cd3fb1 100644 --- a/rust/lancedb/src/authz/mod.rs +++ b/rust/lancedb/src/authz/mod.rs @@ -42,7 +42,7 @@ pub mod subject; pub use api::*; pub use object::{ DatabaseObject, FunctionObject, NamespaceObject, NamespacePath, Object, SecretObject, - TableObject, ViewObject, + StorageIntegrationObject, TableObject, ViewObject, }; pub use privilege::*; pub use subject::{Subject, SubjectKind}; diff --git a/rust/lancedb/src/authz/object.rs b/rust/lancedb/src/authz/object.rs index fd324b748..13279e911 100644 --- a/rust/lancedb/src/authz/object.rs +++ b/rust/lancedb/src/authz/object.rs @@ -16,6 +16,7 @@ pub const NAMESPACE_TYPE_STRING: &str = "namespace"; pub const TABLE_TYPE_STRING: &str = "table"; pub const VIEW_TYPE_STRING: &str = "view"; pub const SECRET_TYPE_STRING: &str = "secret"; +pub const STORAGE_INTEGRATION_TYPE_STRING: &str = "storage_integration"; pub const FUNCTION_TYPE_STRING: &str = "function"; pub const UNKNOWN_TYPE_STRING: &str = "unknown"; @@ -102,6 +103,7 @@ pub enum Object { Table(TableObject), View(ViewObject), Secret(SecretObject), + StorageIntegration(StorageIntegrationObject), Function(FunctionObject), Unknown(String), } @@ -116,6 +118,7 @@ impl Object { Self::Table(object) => object.validate(), Self::View(object) => object.validate(), Self::Secret(object) => object.validate(), + Self::StorageIntegration(object) => object.validate(), Self::Function(object) => object.validate(), Self::Unknown(value) if value.is_empty() => Err("object must not be empty".into()), Self::Unknown(_) => Ok(()), @@ -131,6 +134,7 @@ impl Object { Self::Table(object) => Some(&object.database), Self::View(object) => Some(&object.database), Self::Secret(object) => Some(&object.database), + Self::StorageIntegration(object) => Some(&object.database), Self::Function(object) => Some(&object.database), Self::Unknown(_) => None, } @@ -144,6 +148,7 @@ impl Object { Self::Table(_) => TABLE_TYPE_STRING, Self::View(_) => VIEW_TYPE_STRING, Self::Secret(_) => SECRET_TYPE_STRING, + Self::StorageIntegration(_) => STORAGE_INTEGRATION_TYPE_STRING, Self::Function(_) => FUNCTION_TYPE_STRING, Self::Unknown(_) => UNKNOWN_TYPE_STRING, } @@ -170,6 +175,7 @@ impl std::fmt::Display for Object { Self::Table(object) => object.fmt(f), Self::View(object) => object.fmt(f), Self::Secret(object) => object.fmt(f), + Self::StorageIntegration(object) => object.fmt(f), Self::Function(object) => object.fmt(f), Self::Unknown(s) => f.write_str(s), } @@ -215,6 +221,12 @@ impl<'de> Deserialize<'de> for Object { let view = ViewObject::deserialize(serde::de::value::StringDeserializer::::new(s))?; Ok(Self::View(view)) + } else if kind == STORAGE_INTEGRATION_TYPE_STRING { + let object = + StorageIntegrationObject::deserialize(serde::de::value::StringDeserializer::< + D::Error, + >::new(s))?; + Ok(Self::StorageIntegration(object)) } else if kind == SECRET_TYPE_STRING { let secret = SecretObject::deserialize( serde::de::value::StringDeserializer::::new(s), @@ -503,6 +515,61 @@ impl<'de> Deserialize<'de> for SecretObject { } } +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct StorageIntegrationObject { + pub database: String, + pub namespace: NamespacePath, + pub storage_integration: String, +} + +impl StorageIntegrationObject { + fn validate(&self) -> Result<(), String> { + validate_database_name(&self.database).map_err(|error| error.to_string())?; + validate_secret_name(&self.storage_integration).map_err(|error| error.to_string())?; + Ok(()) + } +} + +impl std::fmt::Display for StorageIntegrationObject { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "storage_integration:{}:{}${}", + self.database, self.namespace, self.storage_integration + ) + } +} + +impl Serialize for StorageIntegrationObject { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.validate().map_err(S::Error::custom)?; + self.to_string().serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for StorageIntegrationObject { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + let invalid = || D::Error::custom(format!("invalid StorageIntegrationObject {s:?}")); + let rest = s.strip_prefix("storage_integration:").ok_or_else(invalid)?; + let (database, path) = rest.split_once(':').ok_or_else(invalid)?; + let (namespace, storage_integration) = path.rsplit_once('$').ok_or_else(invalid)?; + let object = Self { + database: database.to_string(), + namespace: NamespacePath::parse(namespace).map_err(D::Error::custom)?, + storage_integration: storage_integration.to_string(), + }; + object.validate().map_err(D::Error::custom)?; + Ok(object) + } +} + /// A function resource, encoded as `function:DATABASE:NAMESPACE$FUNCTION`. /// /// ``` diff --git a/rust/lancedb/src/authz/privilege.rs b/rust/lancedb/src/authz/privilege.rs index 66b07643a..2782a17bd 100644 --- a/rust/lancedb/src/authz/privilege.rs +++ b/rust/lancedb/src/authz/privilege.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _}; /// A LanceDB privilege, serialized by name (for example, `SELECT`). /// Numeric aliases use `PRIVILEGE` followed by decimal digits. Numbers 0 through -/// 13 map to the known privileges in declaration order. Unassigned numbers are +/// 14 map to the known privileges in declaration order. Unassigned numbers are /// preserved verbatim; their meaning and validity are determined by the server. /// /// ``` @@ -81,6 +81,9 @@ pub enum Privilege { /// - can read server configuration. Operate, + /// On a namespace: can register a storage integration. + CreateStorageIntegration, + /// A future privilege name, preserved verbatim. #[strum(to_string = "{0}")] Unknown(UnknownPrivilege), @@ -97,7 +100,7 @@ impl fmt::Display for UnknownPrivilege { } impl Privilege { - pub const KNOWN: [Self; 14] = [ + pub const KNOWN: [Self; 15] = [ Self::Ownership, Self::Usage, Self::Select, @@ -112,6 +115,7 @@ impl Privilege { Self::CreateSecret, Self::CreateFunction, Self::Operate, + Self::CreateStorageIntegration, ]; pub fn valid_for_system(&self) -> bool { @@ -138,6 +142,7 @@ impl Privilege { | Self::CreateMaterializedView | Self::CreateView | Self::CreateSecret + | Self::CreateStorageIntegration | Self::CreateFunction | Self::Unknown(_) ) @@ -170,6 +175,11 @@ impl Privilege { matches!(self, Self::Ownership | Self::Usage | Self::Unknown(_)) } + /// Privileges accepted on a storage integration. + pub fn valid_for_storage_integration(&self) -> bool { + matches!(self, Self::Ownership | Self::Usage | Self::Unknown(_)) + } + /// Whether this privilege can mutate database contents or schema. /// Unknown privileges are conservatively treated as writes. pub fn is_write(&self) -> bool { @@ -203,6 +213,7 @@ impl FromStr for Privilege { Ok(11) => Self::CreateSecret, Ok(12) => Self::CreateFunction, Ok(13) => Self::Operate, + Ok(14) => Self::CreateStorageIntegration, _ => Self::Unknown(UnknownPrivilege(name.to_owned())), }); } @@ -242,6 +253,7 @@ impl TryFrom<&Privilege> for u8 { Privilege::CreateSecret => 11, Privilege::CreateFunction => 12, Privilege::Operate => 13, + Privilege::CreateStorageIntegration => 14, Privilege::Unknown(unknown) => unknown.0["PRIVILEGE".len()..].parse()?, }) } @@ -288,6 +300,16 @@ impl<'de> Deserialize<'de> for Privilege { mod tests { use super::Privilege; + #[test] + fn storage_integration_creation_is_namespace_scoped() { + let privilege = Privilege::CreateStorageIntegration; + assert!(!privilege.valid_for_system()); + assert!(privilege.valid_for_namespace()); + assert!(!privilege.valid_for_database()); + assert!(!privilege.valid_for_storage_integration()); + assert!(privilege.is_write()); + } + #[test] fn display_matches_serde() { for privilege in Privilege::KNOWN { @@ -337,6 +359,7 @@ mod tests { (11, Privilege::CreateSecret), (12, Privilege::CreateFunction), (13, Privilege::Operate), + (14, Privilege::CreateStorageIntegration), ] { assert_eq!(u8::try_from(&privilege).unwrap(), number); assert_eq!(u8::try_from(privilege.clone()).unwrap(), number); @@ -364,7 +387,7 @@ mod tests { #[test] fn unknown_privileges_convert_to_u8() { - for number in 14..=u8::MAX { + for number in 15..=u8::MAX { for name in [ format!("PRIVILEGE{number}"), format!("PRIVILEGE{number:03}"), @@ -399,7 +422,7 @@ mod tests { #[test] fn future_privilege_names_round_trip() { for name in [ - "PRIVILEGE14", + "PRIVILEGE15", "PRIVILEGE20", "PRIVILEGE64", "PRIVILEGE256", @@ -442,7 +465,7 @@ mod tests { #[test] fn unknown_privileges_are_valid_for_all_objects_and_treated_as_writes() { - for name in ["PRIVILEGE14", "PRIVILEGE20", "PRIVILEGE64", "PRIVILEGE256"] { + for name in ["PRIVILEGE15", "PRIVILEGE20", "PRIVILEGE64", "PRIVILEGE256"] { let privilege: Privilege = name.parse().unwrap(); assert!(privilege.valid_for_system()); assert!(privilege.valid_for_database()); @@ -475,6 +498,7 @@ mod tests { | Privilege::CreateView | Privilege::CreateSecret | Privilege::CreateFunction + | Privilege::CreateStorageIntegration ), "unexpected write classification for {privilege}" ); diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index 409edcc2a..a8a816fdd 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -288,7 +288,7 @@ impl BlobFile { } } - /// Physical byte offset in the data file. `None` on LanceDB Distributed handles. The + /// Physical byte offset in the data file. `None` on LanceDB Enterprise handles. The /// server's byte-range route does not expose storage layout. pub fn position(&self) -> Option { match &self.inner { @@ -298,7 +298,7 @@ impl BlobFile { } } - /// Path of the data file holding the blob. `None` on LanceDB Distributed handles. The + /// Path of the data file holding the blob. `None` on LanceDB Enterprise handles. The /// server's byte-range route does not expose storage layout. pub fn data_path(&self) -> Option<&Path> { match &self.inner { @@ -308,7 +308,7 @@ impl BlobFile { } } - /// Native storage layout. `None` on LanceDB Distributed handles. The server's + /// Native storage layout. `None` on LanceDB Enterprise handles. The server's /// byte-range route does not expose layout. pub fn kind(&self) -> Option { match &self.inner { @@ -318,7 +318,7 @@ impl BlobFile { } } - /// External URI for native handles. LanceDB Distributed handles do not expose storage URIs. + /// External URI for native handles. LanceDB Enterprise handles do not expose storage URIs. pub fn uri(&self) -> Option<&str> { match &self.inner { BlobFileInner::Native(file) => file.uri(), diff --git a/rust/lancedb/src/catalog.rs b/rust/lancedb/src/catalog.rs index 18373ed5a..df80b6de6 100644 --- a/rust/lancedb/src/catalog.rs +++ b/rust/lancedb/src/catalog.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! Catalogs manage databases. A remote catalog is the root namespace of a server. +//! Catalogs manage databases at the server root. Storage integrations belong to databases. //! //! ``` //! # #[cfg(feature = "remote")] @@ -200,13 +200,14 @@ impl Stream for DatabaseNames { } } -/// A backend that manages databases. Implementations own database lifecycle semantics. +/// A backend that manages databases. #[async_trait::async_trait] pub trait Catalog: Send + Sync + std::fmt::Debug + 'static { /// Obtain deployment-wide authorization, if supported by this backend. fn authz(&self) -> Result> { Err(crate::Error::NotSupported { - message: "Authorization administration is not supported by this catalog".into(), + message: crate::docs::DocLink::Authorization + .append_to("Authorization administration is not supported by this catalog"), }) } @@ -265,7 +266,6 @@ impl CatalogConnection { pub fn catalog(&self) -> &Arc { &self.catalog } - /// Create a database; pass a name or [`CreateDatabaseRequest`] for additional options. pub async fn create_database( &self, diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 147be8c32..1efd1fa1c 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -28,6 +28,8 @@ use crate::database::{ }; use crate::embeddings::{EmbeddingRegistry, MemoryRegistry}; use crate::error::{Error, Result}; +use crate::function::GpuClass; +use crate::graph::{PropertyGraphDefinition, PropertyGraphDescription}; use crate::listing::{Listing, ListingOptions, ListingPage}; #[cfg(feature = "remote")] use crate::remote::{ @@ -38,7 +40,10 @@ use crate::remote::{ }, }; use crate::secrets::SecretInfo; -use crate::utils::{validate_namespace, validate_secret_reference, validate_view_reference}; +use crate::utils::{ + validate_namespace, validate_property_graph_reference, validate_secret_reference, + validate_view_reference, +}; use crate::view::ViewDescription; use lance::io::ObjectStoreParams; pub use lance_file::version::LanceFileVersion; @@ -176,7 +181,7 @@ impl OpenTableBuilder { /// Advanced parameters that can be used to customize table reads /// - /// LanceDB Distributed connections reject these parameters with [`Error::NotSupported`]. + /// LanceDB Enterprise connections reject these parameters with [`Error::NotSupported`]. /// /// If set, these will take precedence over any overlapping `OpenTableOptions` options pub fn lance_read_params(mut self, params: ReadParams) -> Self { @@ -338,7 +343,7 @@ pub struct CloneTableBuilder { request: CloneTableRequest, } -/// Builder for asynchronously executing a SQL statement on a LanceDB Distributed database. +/// Builder for asynchronously executing a SQL statement on a LanceDB Enterprise database. pub struct ExecuteQueryAsyncBuilder { parent: Arc, request: ExecuteQueryRequest, @@ -504,7 +509,7 @@ impl Connection { &self.internal } - /// Start executing SQL on a LanceDB Distributed database. + /// Start executing SQL on a LanceDB Enterprise database. /// /// The query can reference tables in other databases with SQL dot notation. /// Use [`ExecuteQueryAsyncBuilder::default_namespace_path`] to avoid qualifying @@ -659,9 +664,10 @@ impl Connection { /// in `namespace_path`, which is empty for the root namespace. /// /// The server-side job builds the OCI image, then registers the completed - /// artifact. Waiting on the returned typed job yields the durable - /// [`crate::function::FunctionVersion`]. Creation is supported only in LanceDB Distributed. - /// LanceDB Embedded databases return [`Error::NotSupported`]. + /// artifact. The returned job has type `query` and the SQL query UUID as its + /// ID. Waiting on the returned typed job yields the durable + /// [`crate::function::FunctionVersion`]. Creation is remote-only. + /// Local databases return [`Error::NotSupported`]. /// pub async fn create_function_async( &self, @@ -692,8 +698,8 @@ impl Connection { /// List every published immutable Function version in `namespace_path` of /// the remote catalog. Functions in child namespaces are not included. /// - /// Results are ordered by Function name then version. LanceDB Embedded databases return - /// [`Error::NotSupported`]. + /// Results are ordered by Function name then numeric version, using + /// `SHOW FUNCTIONS HISTORY`. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// # Example /// @@ -727,11 +733,13 @@ impl Connection { }) } - /// Remove the current Function name binding, retaining the object history. + /// Remove one published Function revision, preserving sibling revisions and their grants. /// - /// Returns `true` when the server appended a Dropped transition and - /// `false` for an idempotent replay. LanceDB Embedded databases return - /// [`Error::NotSupported`]. + /// Returns `true` when the requested revision was removed and `false` for + /// a repeated drop or a missing name. A revision never published under an + /// existing name is an error. Only the last visible revision's removal + /// releases the name and schedules object cleanup. LanceDB Embedded databases + /// return [`Error::NotSupported`]. pub async fn drop_function( &self, name: impl AsRef, @@ -743,12 +751,28 @@ impl Connection { .await } - /// Start dropping a Function and return its cleanup job. + /// Internal bridge for the Python binding to preserve the public bool API + /// while forwarding advisory SQL warnings to Python's existing warning + /// mechanism. + #[doc(hidden)] + pub async fn drop_function_with_warnings( + &self, + name: impl AsRef, + version: impl AsRef, + namespace_path: &[String], + ) -> Result<(bool, Vec)> { + self.internal + .drop_function_with_warnings(name.as_ref(), version.as_ref(), namespace_path) + .await + } + + /// Drop one Function revision and return its SQL query handle. /// - /// The name is unbound before this returns; the object's content may still be being - /// deleted. Await [`Job::wait`][crate::job::Job::wait] to wait for that to finish. When - /// the server deletes inline, or when nothing was bound, the returned job is already - /// finished and has no id. LanceDB Embedded databases return [`Error::NotSupported`]. + /// The boolean reports removal of the requested revision from the catalog. + /// Sibling revisions and their grants remain available. The query job retains + /// its query ID, and repeated waits confirm that revision's removal. Dropping + /// the last visible revision releases the name and schedules background object + /// cleanup. Local databases return [`Error::NotSupported`]. pub async fn drop_function_async( &self, name: impl AsRef, @@ -760,6 +784,69 @@ impl Connection { .await } + /// Register storage access in this database. Names follow Secret namespace rules. + /// + /// ``` + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// use lancedb::storage_integration::CreateStorageIntegrationRequest; + /// let info = db.create_storage_integration("raw", CreateStorageIntegrationRequest::s3("s3://customer-bucket/raw/", "arn:aws:iam::123456789012:role/access"), &[]).await?; + /// println!("{}", info.configuration_instructions); + /// # Ok(()) + /// # } + /// ``` + pub async fn create_storage_integration( + &self, + name: impl AsRef, + request: crate::storage_integration::CreateStorageIntegrationRequest, + namespace_path: &[String], + ) -> Result { + validate_secret_reference(name.as_ref(), namespace_path)?; + self.internal + .create_storage_integration(name.as_ref(), request, namespace_path) + .await + } + /// Describe a storage integration, returning secret references without credential values. + pub async fn describe_storage_integration( + &self, + name: impl AsRef, + namespace_path: &[String], + ) -> Result { + validate_secret_reference(name.as_ref(), namespace_path)?; + self.internal + .describe_storage_integration(name.as_ref(), namespace_path) + .await + } + /// Lazily list storage integrations in a namespace of this database. + pub fn list_storage_integrations( + &self, + namespace_path: &[String], + options: ListingOptions, + ) -> Listing { + let database = self.database().clone(); + let namespace_path = namespace_path.to_vec(); + Listing::new(options, move |options| { + let database = database.clone(); + let namespace_path = namespace_path.clone(); + async move { + validate_namespace(&namespace_path)?; + database + .list_storage_integrations(&namespace_path, options) + .await + } + }) + } + /// Drop an integration with ownership permission; integrations in use cannot be dropped. + pub async fn drop_storage_integration( + &self, + name: impl AsRef, + namespace_path: &[String], + ) -> Result<()> { + validate_secret_reference(name.as_ref(), namespace_path)?; + self.internal + .drop_storage_integration(name.as_ref(), namespace_path) + .await + } + /// Create a named Secret in this database. /// /// Fails if the name is taken, so a create can never silently become a @@ -936,31 +1023,23 @@ impl Connection { .await } - /// Drop a view and wait for its definition to be deleted. + /// Drop a view and wait for catalog removal. /// /// The tables it reads are untouched: a view holds no rows of its own. - /// Use [`Connection::drop_view_async`] to get the cleanup job instead of - /// waiting on it. LanceDB Embedded databases return [`Error::NotSupported`]. + /// Use [`Connection::drop_view_async`] to retain its SQL query job. + /// Completion confirms catalog removal; physical cleanup continues + /// separately. LanceDB Embedded databases return [`Error::NotSupported`]. pub async fn drop_view(&self, name: impl AsRef, namespace_path: &[String]) -> Result<()> { validate_view_reference(name.as_ref(), namespace_path)?; self.internal.drop_view(name.as_ref(), namespace_path).await } - /// Start dropping a view and return the job deleting its definition. + /// Drop a view and return its SQL query job. /// - /// The name is free before this returns; the definition dataset may still - /// be being deleted. Await [`Job::wait`][crate::job::Job::wait] to wait for - /// that. When nothing was bound to the name, the returned job is already - /// finished and has no id. LanceDB Embedded databases return [`Error::NotSupported`]. - /// - /// ```no_run - /// # use lancedb::Connection; - /// # async fn drop(conn: &Connection) -> lancedb::Result<()> { - /// let job = conn.drop_view_async("recent_orders", &[]).await?; - /// job.wait().await?; - /// # Ok(()) - /// # } - /// ``` + /// The job has type `query` and its ID is the SQL query UUID. Await + /// [`Job::wait`][crate::job::Job::wait] to confirm catalog removal; physical + /// cleanup continues separately. LanceDB Embedded databases return + /// [`Error::NotSupported`]. pub async fn drop_view_async( &self, name: impl AsRef, @@ -1007,9 +1086,144 @@ impl Connection { }) } + /// Create a property graph over tables in its namespace. + /// + /// The definition names the tables that hold its nodes, with each one's + /// key column and label, and the tables that hold its edges, with the node + /// keys each one's source and destination columns reference -- the shape + /// of SQL/PGQ's `CREATE PROPERTY GRAPH`. The graph stores nothing else: a + /// query reads its tables through SQL `GRAPH_TABLE`, as they are when it + /// runs. + /// + /// The database checks the definition against the tables now, so one they + /// cannot satisfy is refused here rather than at the first query. The + /// returned description lists each table's properties as they resolved. + /// A name another property graph holds is an error. Local databases return + /// [`Error::NotSupported`]. + /// + /// # Example + /// + /// ```no_run + /// use futures::TryStreamExt; + /// use lancedb::graph::{EdgeTable, Endpoint, NodeTable, PropertyGraphDefinition}; + /// + /// # async fn graph_lifecycle( + /// # connection: &lancedb::Connection, + /// # ) -> Result<(), Box> { + /// let namespace = vec!["analytics".to_string()]; + /// + /// let definition = PropertyGraphDefinition { + /// nodes: vec![NodeTable::new("person", "person_id", "Person").properties(["name"])], + /// edges: vec![EdgeTable::new( + /// "knows", + /// "KNOWS", + /// Endpoint::new("src_id", "person", "person_id"), + /// Endpoint::new("dst_id", "person", "person_id"), + /// )], + /// }; + /// let graph = connection + /// .create_property_graph("social", &definition, &namespace) + /// .await?; + /// // The key is always a property, beside the columns asked for. + /// println!("{:?}", graph.definition.nodes[0].properties); + /// + /// let names: Vec<_> = connection + /// .list_property_graphs(&namespace, Default::default()) + /// .try_collect() + /// .await?; + /// assert!(names.iter().any(|name| name == "social")); + /// + /// // Dropping the graph leaves `person` and `knows` untouched. + /// connection.drop_property_graph("social", &namespace).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn create_property_graph( + &self, + name: impl AsRef, + definition: &PropertyGraphDefinition, + namespace_path: &[String], + ) -> Result { + validate_property_graph_reference(name.as_ref(), namespace_path)?; + self.internal + .create_property_graph(name.as_ref(), definition, namespace_path) + .await + } + + /// What this database records about one property graph: its node and edge + /// tables, with each table's properties as create resolved them. + /// + /// Local databases return [`Error::NotSupported`]. + pub async fn describe_property_graph( + &self, + name: impl AsRef, + namespace_path: &[String], + ) -> Result { + validate_property_graph_reference(name.as_ref(), namespace_path)?; + self.internal + .describe_property_graph(name.as_ref(), namespace_path) + .await + } + + /// Drop a property graph and wait for its definition to be deleted. + /// + /// The tables it reads are untouched: a property graph holds no rows of + /// its own. Local databases return [`Error::NotSupported`]. + pub async fn drop_property_graph( + &self, + name: impl AsRef, + namespace_path: &[String], + ) -> Result<()> { + validate_property_graph_reference(name.as_ref(), namespace_path)?; + self.internal + .drop_property_graph(name.as_ref(), namespace_path) + .await + } + + /// The names of the property graphs in one namespace. + /// + /// Names only; a definition comes from [`Self::describe_property_graph`]. + /// Local databases return [`Error::NotSupported`]. + /// + /// Results are fetched lazily, one page at a time. See [`Listing`] + /// for cached-result and continuation-token semantics. Errors terminate iteration. + /// + /// ``` + /// use futures::TryStreamExt; + /// + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// let mut items = connection.list_property_graphs(&[], Default::default()); + /// while let Some(item) = items.try_next().await? { + /// println!("{item:?}"); + /// } + /// # Ok(()) + /// # } + /// ``` + pub fn list_property_graphs( + &self, + namespace_path: &[String], + options: ListingOptions, + ) -> Listing { + let database = self.database().clone(); + let namespace_path = namespace_path.to_vec(); + Listing::new(options, move |options| { + let database = database.clone(); + let namespace_path = namespace_path.clone(); + async move { + validate_namespace(&namespace_path)?; + database + .list_property_graphs(&namespace_path, options) + .await + } + }) + } + /// Rename a table in the database. /// - /// This is only supported in LanceDB Distributed. + /// Supported in LanceDB Enterprise and by namespace backends that implement + /// renaming. Directory namespaces support renaming tables resolved through + /// their manifest, including tables within or across child namespaces. + /// Directory-listing root tables cannot be renamed. pub async fn rename_table( &self, old_name: impl AsRef, @@ -1062,6 +1276,16 @@ impl Connection { self.internal.open_job(job_id.as_ref()).await } + /// List the operator-configured GPU classes available to Function workers. + /// + /// The result describes configured hardware, not current free capacity. + /// The principal needs System Usage permission. LanceDB Embedded and + /// older Enterprise servers without `GET /v1/gpu/classes` return + /// [`Error::NotSupported`]. + pub async fn list_gpu_classes(&self) -> Result> { + self.database().list_gpu_classes().await + } + /// List server-side jobs across the database's tables. /// /// Results are fetched lazily, one page at a time. See [`Listing`] @@ -1213,7 +1437,7 @@ impl Connection { /// For ListingDatabase, it is the equivalent DirectoryNamespace. /// For RemoteDatabase, it is the equivalent RestNamespace. /// - /// LanceDB Distributed connections using dynamic headers forward them through the + /// LanceDB Enterprise connections using dynamic headers forward them through the /// namespace client's per-request context provider. pub async fn namespace_client(&self) -> Result> { self.internal.namespace_client().await @@ -1224,7 +1448,7 @@ impl Connection { /// - impl_type: "dir" for DirectoryNamespace, "rest" for RestNamespace /// - properties: configuration properties for the namespace /// - /// LanceDB Distributed connections using dynamic headers cannot be exported because the + /// LanceDB Enterprise connections using dynamic headers cannot be exported because the /// namespace client config only carries static headers. pub async fn namespace_client_config( &self, @@ -1562,7 +1786,7 @@ impl ConnectBuilder { /// Enable or disable manifest-backed directory namespace mode for local /// native connections. - /// LanceDB Distributed connections reject enabling this option with [`Error::NotSupported`]. + /// LanceDB Enterprise connections reject enabling this option with [`Error::NotSupported`]. /// /// When enabled, the connection uses the directory namespace database /// directly for all table operations and forces @@ -1598,7 +1822,7 @@ impl ConnectBuilder { } /// Set a custom session for object stores and caching. - /// LanceDB Distributed connections reject this option with [`Error::NotSupported`]. + /// LanceDB Enterprise connections reject this option with [`Error::NotSupported`]. /// /// By default, a new session with default configuration will be created. /// This method allows you to provide a custom session with your own @@ -1641,7 +1865,7 @@ impl ConnectBuilder { if provided { return Err(Error::NotSupported { message: format!( - "{option} is not supported for LanceDB Distributed connections" + "{option} is not supported for LanceDB Enterprise connections" ), }); } diff --git a/rust/lancedb/src/connection/create_table.rs b/rust/lancedb/src/connection/create_table.rs index 0eb11711c..3d1774de9 100644 --- a/rust/lancedb/src/connection/create_table.rs +++ b/rust/lancedb/src/connection/create_table.rs @@ -56,7 +56,7 @@ impl CreateTableBuilder { /// Apply the given write options when writing the initial data /// - /// LanceDB Distributed connections reject explicit Lance write parameters with + /// LanceDB Enterprise connections reject explicit Lance write parameters with /// [`Error::NotSupported`] instead of silently using server defaults. pub fn write_options(mut self, write_options: WriteOptions) -> Self { self.request.write_options = write_options; @@ -83,7 +83,7 @@ impl CreateTableBuilder { /// Set multiple options for the storage layer. /// - /// Table-level storage options are not supported by LanceDB Distributed connections. + /// Table-level storage options are not supported by LanceDB Enterprise connections. /// /// Options already set on the connection will be inherited by the table, /// but can be overridden here. diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 54d51c24f..44d038521 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -28,7 +28,10 @@ use lance_namespace::models::{ }; use crate::data::scannable::Scannable; +use crate::docs::DocLink; use crate::error::Result; +use crate::function::GpuClass; +use crate::graph::{PropertyGraphDefinition, PropertyGraphDescription}; use crate::job::Job; use crate::listing::{ListingOptions, ListingPage}; use crate::materialized_view::CreateMaterializedViewRequest; @@ -192,7 +195,7 @@ impl CloneTableRequest { } } -/// A request to start a SQL statement on a LanceDB Distributed database. +/// A request to start a SQL statement on a LanceDB Enterprise database. #[derive(Clone, Debug)] pub struct ExecuteQueryRequest { /// The SQL text. @@ -246,6 +249,34 @@ pub struct JobInfo { pub state: String, /// When the job was created, in milliseconds since the epoch. pub created_at_millis: i64, + /// Latest progress sample for a job type that reports structured progress. + pub progress: Option, + /// Coarse server-derived phase, including phases introduced by newer + /// servers. + pub phase: Option, + /// Whether an operator has parked this job. + pub paused: bool, +} + +impl JobInfo { + /// A flat progress mapping for list callers. Lifecycle and pause metadata + /// remain available when a job type or older server has no counters. + pub fn progress_snapshot(&self) -> serde_json::Value { + let mut snapshot = serde_json::Map::new(); + snapshot.insert("job_type".to_string(), self.job_type.clone().into()); + snapshot.insert("state".to_string(), self.state.clone().into()); + snapshot.insert("creation_ms".to_string(), self.created_at_millis.into()); + snapshot.insert("paused".to_string(), self.paused.into()); + if let Some(phase) = &self.phase { + snapshot.insert("phase".to_string(), phase.clone().into()); + } + if let Some(serde_json::Value::Object(progress)) = &self.progress { + for (key, value) in progress { + snapshot.insert(key.clone(), value.clone()); + } + } + serde_json::Value::Object(snapshot) + } } /// The server-side record behind a [`crate::job::Job`] handle: lifecycle @@ -258,6 +289,17 @@ pub struct JobDescription { pub state: String, /// When the job was created, in milliseconds since the epoch. pub creation_ms: i64, + /// Latest progress sample for a job type that reports structured progress. + pub progress: Option, + /// Coarse server-derived phase, including phases introduced by newer + /// servers. + pub phase: Option, + /// Why this job is queued before execution. Absent once work can start. + pub queue_reason: Option, + /// Maintenance job this queued job is waiting for, if any. + pub waiting_for_job_id: Option, + /// When the job was paused, if it is. + pub paused_at_millis: Option, /// The job-type-specific specification. Null when the server omits it. pub spec: serde_json::Value, /// The job-type-specific terminal result, for job types that define one. @@ -269,6 +311,42 @@ pub struct JobDescription { pub failure: Option, } +impl JobDescription { + /// A flat, job-type-neutral progress snapshot for SDK callers. + /// + /// Lifecycle metadata is always available. Queue metadata and structured + /// progress fields are included when supplied by the server; older servers + /// simply omit those fields. + pub fn progress_snapshot(&self) -> serde_json::Value { + let mut snapshot = serde_json::Map::new(); + snapshot.insert("job_type".to_string(), self.job_type.clone().into()); + snapshot.insert("state".to_string(), self.state.clone().into()); + snapshot.insert("creation_ms".to_string(), self.creation_ms.into()); + if let Some(phase) = &self.phase { + snapshot.insert("phase".to_string(), phase.clone().into()); + } + if let Some(queue_reason) = &self.queue_reason { + snapshot.insert("queue_reason".to_string(), queue_reason.clone().into()); + } + if let Some(waiting_for_job_id) = &self.waiting_for_job_id { + snapshot.insert( + "waiting_for_job_id".to_string(), + waiting_for_job_id.clone().into(), + ); + } + snapshot.insert("paused".to_string(), self.paused_at_millis.is_some().into()); + if let Some(paused_at_millis) = self.paused_at_millis { + snapshot.insert("paused_at_millis".to_string(), paused_at_millis.into()); + } + if let Some(serde_json::Value::Object(progress)) = &self.progress { + for (key, value) in progress { + snapshot.insert(key.clone(), value.clone()); + } + } + serde_json::Value::Object(snapshot) + } +} + /// The server's answer to a pause request. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PauseJobStatus { @@ -294,25 +372,52 @@ pub enum ResumeJobStatus { fn job_op_not_supported(what: &str) -> Result { Err(crate::error::Error::NotSupported { - message: format!("{} is not supported by this database", what), + message: DocLink::Jobs.append_to(format!("{what} is not supported by this database")), + }) +} + +fn materialized_view_op_not_supported(what: &str) -> Result { + Err(crate::error::Error::NotSupported { + message: DocLink::MaterializedViews + .append_to(format!("{what} is not supported by this database")), }) } fn function_catalog_not_supported() -> Result { Err(crate::error::Error::NotSupported { - message: "Function catalog operations are not supported by this database".to_string(), + message: DocLink::Functions + .append_to("Function catalog operations are not supported by this database"), + }) +} + +fn gpu_class_catalog_not_supported() -> Result { + Err(crate::error::Error::NotSupported { + message: DocLink::GpuClasses + .append_to("GPU class discovery is supported only by LanceDB Enterprise"), }) } fn secret_catalog_not_supported() -> Result { Err(crate::error::Error::NotSupported { - message: "Secret operations are not supported by this database".to_string(), + message: DocLink::Secrets.append_to("Secret operations are not supported by this database"), }) } fn view_ops_not_supported() -> Result { Err(crate::error::Error::NotSupported { - message: "View operations are not supported by this database".to_string(), + message: DocLink::Views.append_to("View operations are not supported by this database"), + }) +} + +fn property_graph_ops_not_supported() -> Result { + Err(crate::error::Error::NotSupported { + message: "Property graph operations are not supported by this database".to_string(), + }) +} + +fn sql_not_supported() -> Result { + Err(crate::error::Error::NotSupported { + message: DocLink::Sql.append_to("SQL is not supported by this database"), }) } @@ -370,6 +475,10 @@ pub trait Database: ) -> Result> { function_catalog_not_supported() } + /// List the operator-configured GPU classes available to Function workers. + async fn list_gpu_classes(&self) -> Result> { + gpu_class_catalog_not_supported() + } /// Create a materialized view through a remote catalog and return its /// initial-population job. Local connections use the native declaration /// path directly. @@ -378,7 +487,7 @@ pub trait Database: &self, _request: CreateMaterializedViewRequest, ) -> Result { - job_op_not_supported("remote materialized-view creation") + materialized_view_op_not_supported("remote materialized-view creation") } /// Drop a materialized view through its resource endpoint and return its /// cleanup job. Local connections validate the view and use table drop. @@ -388,7 +497,7 @@ pub trait Database: _name: &str, _namespace_path: &[String], ) -> Result { - job_op_not_supported("remote materialized-view drop") + materialized_view_op_not_supported("remote materialized-view drop") } /// Fetch one page of materialized-view names in a namespace. /// Local backends filter a page of table names, so an empty result may @@ -460,10 +569,9 @@ pub trait Database: ) -> Result { function_catalog_not_supported() } - /// Start dropping a Function and return a handle to the cleanup job. - /// - /// Backends without asynchronous cleanup complete the drop before returning an - /// already-finished job. + /// Drop a Function binding and return its completion handle. + /// SQL backends return a query job confirming catalog removal; physical + /// cleanup continues separately. async fn drop_function_async( &self, name: &str, @@ -473,6 +581,52 @@ pub trait Database: let dropped = self.drop_function(name, version, namespace_path).await?; Ok((dropped, crate::job::Job::new_done())) } + /// Internal bridge for the Python binding to preserve the public bool API + /// while making advisory SQL warnings available to the wrapper. + #[doc(hidden)] + async fn drop_function_with_warnings( + &self, + name: &str, + version: &str, + namespace_path: &[String], + ) -> Result<(bool, Vec)> { + let dropped = self.drop_function(name, version, namespace_path).await?; + Ok((dropped, Vec::new())) + } + /// Create a database-owned storage integration in a namespace. + async fn create_storage_integration( + &self, + _name: &str, + _request: crate::storage_integration::CreateStorageIntegrationRequest, + _namespace_path: &[String], + ) -> Result { + secret_catalog_not_supported() + } + /// Describe a database-owned storage integration. + async fn describe_storage_integration( + &self, + _name: &str, + _namespace_path: &[String], + ) -> Result { + secret_catalog_not_supported() + } + /// List one namespace of storage integrations. + async fn list_storage_integrations( + &self, + _namespace_path: &[String], + _options: ListingOptions, + ) -> Result> { + secret_catalog_not_supported() + } + /// Drop a database-owned storage integration. + async fn drop_storage_integration( + &self, + _name: &str, + _namespace_path: &[String], + ) -> Result<()> { + secret_catalog_not_supported() + } + /// Create a named Secret in this database. Fails if the name is taken, so /// a create can never silently become a rotation. async fn create_secret( @@ -553,6 +707,50 @@ pub trait Database: ) -> Result> { view_ops_not_supported() } + /// Create a property graph over tables in its namespace. The tables are + /// checked against the definition, and each table's properties resolved, + /// once, by the database, so a definition they cannot satisfy is refused + /// now rather than at the first query. + async fn create_property_graph( + &self, + _name: &str, + _definition: &PropertyGraphDefinition, + _namespace_path: &[String], + ) -> Result { + property_graph_ops_not_supported() + } + /// What the database records about one property graph: its node and edge + /// tables, with the properties create resolved. + async fn describe_property_graph( + &self, + _name: &str, + _namespace_path: &[String], + ) -> Result { + property_graph_ops_not_supported() + } + /// Drop a property graph and wait for its definition to be deleted. The + /// tables it reads are untouched. + async fn drop_property_graph(&self, _name: &str, _namespace_path: &[String]) -> Result<()> { + property_graph_ops_not_supported() + } + /// Drop a property graph and return the job deleting its definition, + /// without waiting. + #[doc(hidden)] + async fn drop_property_graph_async( + &self, + _name: &str, + _namespace_path: &[String], + ) -> Result { + property_graph_ops_not_supported() + } + /// Fetch one page of property graph names in one namespace. + async fn list_property_graphs( + &self, + _namespace_path: &[String], + _options: ListingOptions, + ) -> Result> { + property_graph_ops_not_supported() + } /// Open a job by id, returning a handle with its record already /// populated. Fails with [`crate::Error::JobNotFound`] when the server has /// no such job. @@ -581,24 +779,18 @@ pub trait Database: } /// Establish the SQL transport without executing a statement. async fn check_sql_connection(&self) -> Result<()> { - Err(crate::Error::NotSupported { - message: "SQL is not supported by this database".into(), - }) + sql_not_supported() } - /// Start executing a SQL statement on a LanceDB Distributed database. + /// Start executing a SQL statement on a LanceDB Enterprise database. async fn execute_query_async( &self, _request: ExecuteQueryRequest, ) -> Result { - Err(crate::error::Error::NotSupported { - message: "SQL is not supported by this database".to_string(), - }) + sql_not_supported() } /// Describe a submitted SQL query by its connection-scoped id. async fn describe_query(&self, _query_id: uuid::Uuid) -> Result { - Err(crate::error::Error::NotSupported { - message: "SQL is not supported by this database".to_string(), - }) + sql_not_supported() } /// Open a table in the database async fn open_table(&self, request: OpenTableRequest) -> Result>; diff --git a/rust/lancedb/src/docs.rs b/rust/lancedb/src/docs.rs new file mode 100644 index 000000000..d69a1612c --- /dev/null +++ b/rust/lancedb/src/docs.rs @@ -0,0 +1,873 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Central registry of documentation links emitted in SDK warnings and +//! Enterprise-only error messages. +//! +//! Every link appends standard UTM query parameters (`utm_source=lancedb_sdk`, +//! `utm_medium=warning|error`, `utm_campaign=`, +//! `utm_content=-`) before any `#anchor` fragment, and never +//! includes table names, URIs, hostnames, machine IDs, or other user data. + +use std::collections::HashSet; +use std::sync::{LazyLock, Mutex, OnceLock}; + +use lance::Dataset; +use roaring::RoaringBitmap; + +/// Base URL for the LanceDB documentation site. +pub const DOCS_BASE_URL: &str = "https://docs.lancedb.com"; + +/// Fragment size threshold (in physical rows) below which a fragment is counted +/// as a small fragment for compaction warnings and `Table::stats()`. +pub const SMALL_FRAGMENT_ROW_THRESHOLD: usize = 100_000; + +/// Minimum number of small fragments (`< 100k` physical rows each) on an opened +/// table before emitting a one-time compaction warning. +pub const SMALL_FRAGMENT_WARN_COUNT_THRESHOLD: usize = 100; + +/// Minimum number of unindexed rows on any user index of an opened table before +/// emitting a one-time index-maintenance warning. +pub const UNINDEXED_ROWS_WARN_THRESHOLD: u64 = 1_000_000; + +static SDK_UTM_CONTENT: OnceLock = OnceLock::new(); + +static SMALL_FRAGMENTS_WARNED: LazyLock>> = + LazyLock::new(|| Mutex::new(HashSet::new())); +static UNINDEXED_ROWS_WARNED: LazyLock>> = + LazyLock::new(|| Mutex::new(HashSet::new())); + +/// Record which SDK and version are running in this process for `utm_content`. +/// +/// Language bindings (`python`, `nodejs`, `cli`) call this once during module +/// initialization. If never called, `utm_content` defaults to +/// `rust-`. +pub fn set_sdk_ident(sdk: &str, version: &str) { + let _ = SDK_UTM_CONTENT.set(format!("{sdk}-{version}")); +} + +/// The `-` value used for `utm_content`. +pub fn sdk_utm_content() -> &'static str { + SDK_UTM_CONTENT + .get_or_init(|| concat!("rust-", env!("CARGO_PKG_VERSION")).to_string()) + .as_str() +} + +/// The `utm_medium` parameter value for a documentation link. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UtmMedium { + Warning, + Error, +} + +impl UtmMedium { + pub const fn as_str(self) -> &'static str { + match self { + Self::Warning => "warning", + Self::Error => "error", + } + } +} + +/// Every documentation link emitted by the SDK. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum DocLink { + /// Compaction maintenance warning for tables with many small fragments. + Compaction, + /// Incremental reindexing maintenance warning for tables with many unindexed rows. + Reindexing, + /// SQL execution (Enterprise only). + Sql, + /// Server-side job management and event history (Enterprise only). + Jobs, + /// Registered Python Functions and Function-backed columns (Enterprise only). + Functions, + /// GPU class discovery for Function workers (Enterprise only). + GpuClasses, + /// Database Secrets and storage integrations (Enterprise only). + Secrets, + /// Per-row Function error store (Enterprise only). + FunctionErrors, + /// SQL views (Enterprise only). + Views, + /// Materialized views (Enterprise only). + MaterializedViews, + /// Branch diff against `main` (Enterprise only). + BranchDiff, + /// Branch cherry-pick onto `main` (Enterprise only). + BranchCherryPick, + /// Data cache prewarming (Enterprise only). + PrewarmData, + /// Deployment-wide authorization administration (Enterprise only). + Authorization, +} + +impl DocLink { + /// Every defined [`DocLink`] variant, enumerated by CI and unit tests. + pub const ALL: &'static [Self] = &[ + Self::Compaction, + Self::Reindexing, + Self::Sql, + Self::Jobs, + Self::Functions, + Self::GpuClasses, + Self::Secrets, + Self::FunctionErrors, + Self::Views, + Self::MaterializedViews, + Self::BranchDiff, + Self::BranchCherryPick, + Self::PrewarmData, + Self::Authorization, + ]; + + /// Look up a [`DocLink`] by its `utm_campaign` identifier. + pub fn from_campaign(campaign: &str) -> Option { + Self::ALL + .iter() + .copied() + .find(|link| link.campaign() == campaign) + } + + /// The `utm_campaign` identifier for this link. + pub const fn campaign(self) -> &'static str { + match self { + Self::Compaction => "compaction", + Self::Reindexing => "reindexing", + Self::Sql => "sql", + Self::Jobs => "jobs", + Self::Functions => "functions", + Self::GpuClasses => "gpu_classes", + Self::Secrets => "secrets", + Self::FunctionErrors => "function_errors", + Self::Views => "views", + Self::MaterializedViews => "materialized_views", + Self::BranchDiff => "branch_diff", + Self::BranchCherryPick => "branch_cherry_pick", + Self::PrewarmData => "prewarm_data", + Self::Authorization => "authorization", + } + } + + /// The documentation page path (starting with `/`). + /// + /// Every path here must return HTTP 200 on the currently published + /// `https://docs.lancedb.com` edition and also resolve (directly or via a + /// redirect entry in `docs/web/docs.json`) in the upcoming `docs/web` + /// edition. + pub const fn path(self) -> &'static str { + match self { + Self::Compaction => "/performance", + Self::Reindexing => "/indexing/reindexing", + Self::Sql => "/search/sql", + Self::BranchDiff | Self::BranchCherryPick => "/tables/branching", + Self::Jobs + | Self::Functions + | Self::GpuClasses + | Self::Secrets + | Self::FunctionErrors + | Self::Views + | Self::MaterializedViews + | Self::PrewarmData + | Self::Authorization => "/basics/embedded-vs-enterprise", + } + } + + /// Optional `#anchor` fragment on the target documentation page. + pub const fn anchor(self) -> Option<&'static str> { + match self { + Self::Compaction => Some("compaction-and-cleanup"), + Self::Reindexing => Some("incremental-reindexing"), + Self::BranchDiff => Some("diff-a-branch"), + Self::BranchCherryPick => Some("merge-a-branch"), + Self::Sql + | Self::Jobs + | Self::Functions + | Self::GpuClasses + | Self::Secrets + | Self::FunctionErrors + | Self::Views + | Self::MaterializedViews + | Self::PrewarmData + | Self::Authorization => None, + } + } + + /// The `utm_medium` associated with this link. + pub const fn medium(self) -> UtmMedium { + match self { + Self::Compaction | Self::Reindexing => UtmMedium::Warning, + Self::Sql + | Self::Jobs + | Self::Functions + | Self::GpuClasses + | Self::Secrets + | Self::FunctionErrors + | Self::Views + | Self::MaterializedViews + | Self::BranchDiff + | Self::BranchCherryPick + | Self::PrewarmData + | Self::Authorization => UtmMedium::Error, + } + } + + /// Build the full URL with UTM parameters placed before any `#anchor`. + pub fn url(self) -> String { + self.url_with_content(sdk_utm_content()) + } + + pub(crate) fn url_with_content(self, utm_content: &str) -> String { + let path = self.path(); + let medium = self.medium().as_str(); + let campaign = self.campaign(); + match self.anchor() { + Some(anchor) => format!( + "{DOCS_BASE_URL}{path}?utm_source=lancedb_sdk&utm_medium={medium}&utm_campaign={campaign}&utm_content={utm_content}#{anchor}" + ), + None => format!( + "{DOCS_BASE_URL}{path}?utm_source=lancedb_sdk&utm_medium={medium}&utm_campaign={campaign}&utm_content={utm_content}" + ), + } + } + + /// Append `. See ` (or ` See ` if `message` already ends with `.`) + /// to an error or warning message. + pub fn append_to(self, message: impl AsRef) -> String { + let message = message.as_ref().trim_end(); + let url = self.url(); + if message.ends_with('.') { + format!("{message} See {url}") + } else { + format!("{message}. See {url}") + } + } +} + +fn is_warned(set: &Mutex>, table_key: &str) -> bool { + set.lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .contains(table_key) +} + +fn mark_warned(set: &Mutex>, table_key: &str) -> bool { + set.lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(table_key.to_string()) +} + +/// Check already-loaded dataset metadata when a table is opened and emit +/// rate-limited maintenance warnings (at most once per table per process). +pub(crate) async fn check_table_maintenance_warnings(dataset: &Dataset, table_key: &str) { + if !log::log_enabled!(log::Level::Warn) { + return; + } + if let Some(msg) = check_small_fragments_warning(dataset, table_key) { + log::warn!("{msg}"); + } + if let Some(msg) = check_unindexed_rows_warning(dataset, table_key).await { + log::warn!("{msg}"); + } +} + +pub(crate) fn check_small_fragments_warning(dataset: &Dataset, table_key: &str) -> Option { + if is_warned(&SMALL_FRAGMENTS_WARNED, table_key) { + return None; + } + dataset.manifest().writer_version.as_ref()?; + let num_small_fragments = dataset + .manifest() + .fragments + .iter() + .filter(|frag| { + frag.physical_rows + .is_some_and(|rows| rows < SMALL_FRAGMENT_ROW_THRESHOLD) + }) + .count(); + if num_small_fragments >= SMALL_FRAGMENT_WARN_COUNT_THRESHOLD + && mark_warned(&SMALL_FRAGMENTS_WARNED, table_key) + { + Some(format!( + "Table has {num_small_fragments} small fragments (<100k rows each), \ + which can degrade query performance. Run optimize() to compact fragments. \ + See {}", + DocLink::Compaction.url() + )) + } else { + None + } +} + +fn segment_supports_optimize_without_io(segment: &lance_table::format::IndexMetadata) -> bool { + let Some(raw_details) = segment.index_details.as_ref() else { + return false; + }; + let details = lance::index::scalar::IndexDetails(raw_details.clone()); + if details.is_vector() { + return true; + } + details + .get_plugin() + .is_ok_and(|plugin| plugin.supports_optimization()) +} + +pub(crate) async fn check_unindexed_rows_warning( + dataset: &Dataset, + table_key: &str, +) -> Option { + if is_warned(&UNINDEXED_ROWS_WARNED, table_key) { + return None; + } + dataset.manifest().index_section?; + let total_rows: u64 = dataset + .manifest() + .fragments + .iter() + .filter_map(|frag| frag.num_rows().map(|rows| rows as u64)) + .sum(); + if total_rows < UNINDEXED_ROWS_WARN_THRESHOLD { + return None; + } + + let store = dataset.object_store(None).await.ok()?; + let raw_indices = lance_table::io::manifest::read_manifest_indexes( + store.as_ref(), + dataset.manifest_location(), + dataset.manifest(), + ) + .await + .ok()?; + if raw_indices + .iter() + .any(|idx| idx.name == lance_index::frag_reuse::FRAG_REUSE_INDEX_NAME) + { + // Remapping fragment coverage after fragment reuse requires opening the + // fragment-reuse index artifact under `_indices/`. Skip rather than + // read index files during `open_table()`. + return None; + } + + let mut covered_by_index: std::collections::BTreeMap<&str, Option> = + std::collections::BTreeMap::new(); + for index in &raw_indices { + if lance_index::is_system_index(index) { + continue; + } + let Some(bitmap) = index + .fragment_bitmap + .as_ref() + .filter(|_| segment_supports_optimize_without_io(index)) + else { + covered_by_index.insert(index.name.as_str(), None); + continue; + }; + match covered_by_index.get_mut(index.name.as_str()) { + Some(Some(acc)) => *acc |= bitmap, + Some(None) => {} + None => { + covered_by_index.insert(index.name.as_str(), Some(bitmap.clone())); + } + } + } + + for covered in covered_by_index.values().flatten() { + let unindexed_rows: u64 = dataset + .manifest() + .fragments + .iter() + .filter(|frag| !covered.contains(frag.id as u32)) + .filter_map(|frag| frag.num_rows().map(|rows| rows as u64)) + .sum(); + if unindexed_rows >= UNINDEXED_ROWS_WARN_THRESHOLD { + if mark_warned(&UNINDEXED_ROWS_WARNED, table_key) { + return Some(format!( + "Table has {unindexed_rows} unindexed rows, \ + which can degrade search performance. Run optimize() to update indexes. \ + See {}", + DocLink::Reindexing.url() + )); + } + return None; + } + } + None +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + use std::sync::Arc; + + use arrow_array::{FixedSizeListArray, Float32Array, Int32Array, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + use lance::dataset::WriteDestination; + use lance::dataset::builder::DatasetBuilder; + use lance::dataset::transaction::Operation; + use lance_table::format::Fragment; + use lance_table::io::commit::write_manifest_file_to_path; + use lance_table::io::manifest::read_manifest_indexes; + use tempfile::tempdir; + + use crate::connect; + use crate::database::ExecuteQueryRequest; + use crate::function::FunctionErrorsRequest; + use crate::index::Index; + use crate::index::vector::IvfFlatIndexBuilder; + + use super::*; + + fn strip_mdx_comments(content: &str) -> String { + let mut out = String::with_capacity(content.len()); + let mut rest = content; + while let Some(start) = rest.find("{/*") { + out.push_str(&rest[..start]); + match rest[start + 3..].find("*/}") { + Some(end) => { + rest = &rest[start + 3 + end + 3..]; + } + None => return out, + } + } + out.push_str(rest); + out + } + + #[test] + fn test_doc_link_url_format_and_campaign_lookup() { + for &link in DocLink::ALL { + assert_eq!(DocLink::from_campaign(link.campaign()), Some(link)); + let url = link.url_with_content("python-0.42.0"); + let (before_hash, fragment) = match url.split_once('#') { + Some((before, frag)) => (before, Some(frag)), + None => (url.as_str(), None), + }; + assert!( + before_hash.starts_with(&format!( + "{DOCS_BASE_URL}{}?utm_source=lancedb_sdk&", + link.path() + )), + "unexpected URL prefix: {url}" + ); + assert!( + before_hash.contains(&format!("utm_medium={}", link.medium().as_str())), + "missing utm_medium in {url}" + ); + assert!( + before_hash.contains(&format!("utm_campaign={}", link.campaign())), + "missing utm_campaign in {url}" + ); + assert!( + before_hash.contains("utm_content=python-0.42.0"), + "missing utm_content before fragment in {url}" + ); + assert_eq!(fragment, link.anchor(), "mismatched #anchor in {url}"); + } + } + + #[test] + fn test_all_doc_links_resolve_in_repo_docs() { + let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let docs_web = manifest_dir.join("../../docs/web"); + let docs_json = std::fs::read_to_string(docs_web.join("docs.json")) + .expect("docs/web/docs.json must exist"); + let parsed_docs_json: serde_json::Value = + serde_json::from_str(&docs_json).expect("docs/web/docs.json must be valid JSON"); + let redirect_map: std::collections::HashMap = parsed_docs_json + .get("redirects") + .and_then(|v| v.as_array()) + .into_iter() + .flatten() + .filter_map(|entry| { + Some(( + entry.get("source")?.as_str()?.to_string(), + entry.get("destination")?.as_str()?.to_string(), + )) + }) + .collect(); + let mintignore = std::fs::read_to_string(docs_web.join(".mintignore")).unwrap_or_default(); + let ignored: HashSet<&str> = mintignore + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .collect(); + + for &link in DocLink::ALL { + if let Some(destination) = redirect_map.get(link.path()) { + let dest_page = destination + .split_once('#') + .map_or(destination.as_str(), |(p, _)| p) + .trim_start_matches('/'); + let dest_mdx = if dest_page.is_empty() || dest_page == "index" { + docs_web.join("index.mdx") + } else if docs_web.join(format!("{dest_page}.mdx")).is_file() { + docs_web.join(format!("{dest_page}.mdx")) + } else { + docs_web.join(format!("{dest_page}/index.mdx")) + }; + assert!( + dest_mdx.is_file(), + "DocLink::{link:?} redirect destination '{destination}' does not resolve under docs/web" + ); + continue; + } + + let rel_page = link.path().trim_start_matches('/'); + let direct_mdx = format!("{rel_page}.mdx"); + let index_mdx = format!("{rel_page}/index.mdx"); + assert!( + !ignored.contains(direct_mdx.as_str()) && !ignored.contains(index_mdx.as_str()), + "DocLink::{link:?} points to a .mintignore'd page: {rel_page}" + ); + + // Mintlify serves MDX pages even when they are intentionally omitted + // from navigation, so docs.json membership is not required. + let mdx_path = if docs_web.join(&direct_mdx).is_file() { + docs_web.join(&direct_mdx) + } else if docs_web.join(&index_mdx).is_file() { + docs_web.join(&index_mdx) + } else { + panic!("DocLink::{link:?} target page does not exist under docs/web: {rel_page}"); + }; + + if let Some(anchor) = link.anchor() { + let raw_mdx = std::fs::read_to_string(&mdx_path) + .unwrap_or_else(|e| panic!("failed to read {}: {e}", mdx_path.display())); + let active_mdx = strip_mdx_comments(&raw_mdx); + let heading_anchor = format!("{{#{anchor}}}"); + let span_anchor_double = format!("id=\"{anchor}\""); + let span_anchor_single = format!("id='{anchor}'"); + assert!( + active_mdx.contains(&heading_anchor) + || active_mdx.contains(&span_anchor_double) + || active_mdx.contains(&span_anchor_single), + "DocLink::{link:?} anchor '#{anchor}' not found in {}", + mdx_path.display() + ); + } + } + } + + fn make_test_batch() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from_iter_values(0..10))]).unwrap() + } + + #[tokio::test] + async fn test_small_fragments_warning_and_rate_limit() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_table("small_frags_tbl", make_test_batch()) + .execute() + .await + .unwrap(); + + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + assert!( + check_small_fragments_warning(&dataset, "test://small_frags_below").is_none(), + "1 small fragment must not trigger the compaction warning" + ); + + let existing_frag = dataset.manifest().fragments[0].clone(); + let extra_fragments: Vec = (0..SMALL_FRAGMENT_WARN_COUNT_THRESHOLD) + .map(|i| { + let mut frag = existing_frag.clone(); + frag.id = (i + 1) as u64; + frag.physical_rows = Some(100); + frag + }) + .collect(); + let read_version = dataset.version().version; + let updated = Dataset::commit( + WriteDestination::Dataset(dataset), + Operation::Append { + fragments: extra_fragments, + }, + Some(read_version), + None, + None, + Arc::new(Default::default()), + false, + ) + .await + .unwrap(); + + let warning = check_small_fragments_warning(&updated, "test://small_frags_table_a") + .expect("101 small fragments should trigger compaction warning"); + assert!(warning.contains(&DocLink::Compaction.url())); + assert!(!warning.contains("small_frags_table_a")); + assert!( + check_small_fragments_warning(&updated, "test://small_frags_table_a").is_none(), + "same table must be rate-limited to once per process" + ); + assert!( + check_small_fragments_warning(&updated, "test://small_frags_table_b").is_some(), + "a different table must still emit its own warning once" + ); + } + + #[tokio::test] + async fn test_unindexed_rows_warning_and_rate_limit() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_table("unindexed_rows_tbl", make_test_batch()) + .execute() + .await + .unwrap(); + table + .create_index(&["id"], Index::Auto) + .execute() + .await + .unwrap(); + + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + assert!( + check_unindexed_rows_warning(&dataset, "test://unindexed_below") + .await + .is_none(), + "fully indexed table must not trigger the reindexing warning" + ); + + let mut unindexed_frag = dataset.manifest().fragments[0].clone(); + unindexed_frag.id = 99; + unindexed_frag.physical_rows = Some(UNINDEXED_ROWS_WARN_THRESHOLD as usize); + let read_version = dataset.version().version; + let updated = Dataset::commit( + WriteDestination::Dataset(dataset), + Operation::Append { + fragments: vec![unindexed_frag], + }, + Some(read_version), + None, + None, + Arc::new(Default::default()), + false, + ) + .await + .unwrap(); + + let warning = check_unindexed_rows_warning(&updated, "test://unindexed_table_a") + .await + .expect("1,000,000 unindexed rows should trigger reindexing warning"); + assert!(warning.contains(&DocLink::Reindexing.url())); + assert!(!warning.contains("unindexed_table_a")); + assert!( + check_unindexed_rows_warning(&updated, "test://unindexed_table_a") + .await + .is_none(), + "same table must be rate-limited to once per process" + ); + assert!( + check_unindexed_rows_warning(&updated, "test://unindexed_table_b") + .await + .is_some(), + "a different table must still emit its own warning once" + ); + } + + #[tokio::test] + async fn test_unindexed_rows_warning_never_reads_index_or_data_files() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + + let dim = 4_i32; + let num_rows = 32_usize; + let values = + Float32Array::from_iter_values((0..(num_rows * dim as usize)).map(|v| v as f32)); + let vec_field = Arc::new(Field::new("item", DataType::Float32, true)); + let vec_col = FixedSizeListArray::try_new(vec_field, dim, Arc::new(values), None).unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "vec", + DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), dim), + false, + ), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from_iter_values(0..num_rows as i32)), + Arc::new(vec_col), + ], + ) + .unwrap(); + + let table = conn + .create_table("vec_no_io_tbl", batch) + .execute() + .await + .unwrap(); + table + .create_index( + &["vec"], + Index::IvfFlat(IvfFlatIndexBuilder::default().num_partitions(1)), + ) + .execute() + .await + .unwrap(); + + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + let mut unindexed_frag = dataset.manifest().fragments[0].clone(); + unindexed_frag.id = 99; + unindexed_frag.physical_rows = Some(UNINDEXED_ROWS_WARN_THRESHOLD as usize); + let read_version = dataset.version().version; + let updated = Dataset::commit( + WriteDestination::Dataset(dataset), + Operation::Append { + fragments: vec![unindexed_frag], + }, + Some(read_version), + None, + None, + Arc::new(Default::default()), + false, + ) + .await + .unwrap(); + + let table_uri = tmp_dir + .path() + .join("vec_no_io_tbl.lance") + .to_string_lossy() + .to_string(); + + // 1. Modern vector index: warns using only manifest metadata, with zero + // `_indices/` or `data/` file reads. + let reopened = DatasetBuilder::from_uri(&table_uri).load().await.unwrap(); + let store = reopened.object_store(None).await.unwrap(); + let _ = store.io_tracker().incremental_stats(); + let warning = check_unindexed_rows_warning(&reopened, "test://vec_modern_no_io").await; + assert!( + warning.is_some(), + "modern vector index with 1M unindexed rows should trigger warning" + ); + let stats = store.io_tracker().incremental_stats(); + for req in &stats.requests { + let path = req.path.as_ref(); + assert!( + !path.contains("_indices/") && !path.contains("/data/"), + "unexpected index or data I/O during warning check: {path}" + ); + } + + // 2. Legacy vector index without `index_details`: skipped cleanly without + // opening `_indices//index.idx` to infer details. + let mut indices = read_manifest_indexes( + store.as_ref(), + updated.manifest_location(), + updated.manifest(), + ) + .await + .unwrap(); + for idx in &mut indices { + idx.index_details = None; + } + let mut legacy_manifest = (*updated.manifest()).clone(); + write_manifest_file_to_path( + store.as_ref(), + &mut legacy_manifest, + Some(indices), + &reopened.manifest_location().path, + None, + ) + .await + .unwrap(); + + let reopened_legacy = DatasetBuilder::from_uri(&table_uri).load().await.unwrap(); + let legacy_store = reopened_legacy.object_store(None).await.unwrap(); + let _ = legacy_store.io_tracker().incremental_stats(); + let legacy_warning = + check_unindexed_rows_warning(&reopened_legacy, "test://vec_legacy_no_io").await; + assert!( + legacy_warning.is_none(), + "legacy index missing index_details must be skipped without disk inference" + ); + let legacy_stats = legacy_store.io_tracker().incremental_stats(); + for req in &legacy_stats.requests { + let path = req.path.as_ref(); + assert!( + !path.contains("_indices/") && !path.contains("/data/"), + "unexpected index or data I/O for legacy index: {path}" + ); + } + } + + #[tokio::test] + async fn test_enterprise_only_errors_contain_utm_doc_links() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_table("err_tbl", make_test_batch()) + .execute() + .await + .unwrap(); + + let sql_err = conn + .database() + .execute_query_async(ExecuteQueryRequest::new("SELECT 1")) + .await + .unwrap_err() + .to_string(); + assert!(sql_err.contains(&DocLink::Sql.url()), "{sql_err}"); + + let job_err = conn.open_job("job-1").await.unwrap_err().to_string(); + assert!(job_err.contains(&DocLink::Jobs.url()), "{job_err}"); + + let gpu_err = conn.list_gpu_classes().await.unwrap_err().to_string(); + assert!(gpu_err.contains(&DocLink::GpuClasses.url()), "{gpu_err}"); + + let secret_err = conn + .create_secret("my_secret", "val", &[]) + .await + .unwrap_err() + .to_string(); + assert!(secret_err.contains(&DocLink::Secrets.url()), "{secret_err}"); + + let view_err = conn + .create_view("v", "SELECT 1", &[]) + .await + .unwrap_err() + .to_string(); + assert!(view_err.contains(&DocLink::Views.url()), "{view_err}"); + + let diff_err = table.diff_branch("feature").await.unwrap_err().to_string(); + assert!(diff_err.contains(&DocLink::BranchDiff.url()), "{diff_err}"); + + let cp_err = table + .cherry_pick("feature", false) + .await + .unwrap_err() + .to_string(); + assert!( + cp_err.contains(&DocLink::BranchCherryPick.url()), + "{cp_err}" + ); + + let prewarm_err = table.prewarm_data(None).await.unwrap_err().to_string(); + assert!( + prewarm_err.contains(&DocLink::PrewarmData.url()), + "{prewarm_err}" + ); + + let fn_err = table + .function_errors(FunctionErrorsRequest::new()) + .await + .unwrap_err() + .to_string(); + assert!(fn_err.contains(&DocLink::FunctionErrors.url()), "{fn_err}"); + } +} diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 1b1f5b0a5..7499641fc 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -6,10 +6,186 @@ use std::sync::{Arc, PoisonError}; use arrow_schema::ArrowError; use datafusion_common::DataFusionError; +#[cfg(feature = "remote")] +use serde::Deserialize; use snafu::Snafu; pub(crate) type BoxError = Box; +/// Stable resource details carried by a structured remote HTTP error. +#[cfg(feature = "remote")] +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct HttpErrorDetails { + /// Machine-readable error code from the server. + pub error_code: String, + /// The kind of resource named by the error. + pub resource_kind: String, + /// The leaf name of the resource. + pub resource_name: String, + /// The parent namespace path of the resource. + pub namespace_path: Vec, +} + +/// Stable resource identity reported with a remote Flight SQL failure. +#[cfg(feature = "remote")] +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct RemoteResourceIdentity { + /// The kind of resource named by the error. + pub kind: String, + /// The leaf name of the resource. + pub name: String, + /// The parent namespace path of the resource. + pub namespace_path: Vec, +} + +#[cfg(feature = "remote")] +impl RemoteResourceIdentity { + /// Construct a resource identity as reported by a remote service. + pub fn new( + kind: impl Into, + name: impl Into, + namespace_path: Vec, + ) -> Self { + Self { + kind: kind.into(), + name: name.into(), + namespace_path, + } + } +} + +/// Correlation and classification metadata reported by a remote server. +/// +/// Fields are absent when the server did not supply them. Diagnostic text is +/// never used to infer an error code or a job identity. +#[cfg(feature = "remote")] +#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct RemoteErrorMetadata { + /// Machine-readable input error code, when available. + pub error_code: Option, + /// SQL job that failed, when the request ran in an isolated job. + pub job_id: Option, + /// Request executed by the isolated SQL worker. + pub job_request_id: Option, + /// Structured resource identity supplied by the server, when available. + pub resource: Option, +} + +#[cfg(feature = "remote")] +impl RemoteErrorMetadata { + pub(crate) fn from_headers(headers: &reqwest::header::HeaderMap) -> Self { + let header = |name| { + headers + .get(name) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned) + }; + Self { + error_code: header("x-lancedb-error-code"), + job_id: header("x-lancedb-sql-job-id"), + job_request_id: header("x-job-request-id"), + resource: header("x-lancedb-resource") + .as_deref() + .and_then(parse_flight_resource_identity), + } + } +} + +#[cfg(feature = "remote")] +#[derive(Deserialize)] +struct FlightResourceIdentity { + kind: String, + name: String, + namespace_path: Vec, +} + +/// Decode the ASCII-safe structured resource metadata used by Flight SQL. +#[cfg(feature = "remote")] +pub(crate) fn parse_flight_resource_identity(value: &str) -> Option { + use base64::Engine as _; + + let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(value) + .ok()?; + let identity = serde_json::from_slice::(&bytes).ok()?; + Some(RemoteResourceIdentity { + kind: identity.kind, + name: identity.name, + namespace_path: identity.namespace_path, + }) +} + +#[cfg(feature = "remote")] +#[derive(Debug)] +pub(crate) struct HttpErrorSource { + message: String, + details: Option, + metadata: RemoteErrorMetadata, +} + +#[cfg(feature = "remote")] +impl HttpErrorSource { + pub(crate) fn new( + message: String, + response_body: Option<&str>, + metadata: RemoteErrorMetadata, + ) -> Self { + let details = response_body.and_then(parse_http_error_details); + let message = if metadata.error_code.is_some() { + response_body + .and_then(|body| serde_json::from_str::(body).ok()) + .and_then(|body| body.get("error")?.as_str().map(str::to_owned)) + .unwrap_or(message) + } else { + message + }; + Self { + message, + details, + metadata, + } + } +} + +#[cfg(feature = "remote")] +impl Display for HttpErrorSource { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +#[cfg(feature = "remote")] +impl std::error::Error for HttpErrorSource {} + +#[cfg(feature = "remote")] +#[derive(Deserialize)] +struct HttpResponseBody { + error_code: String, + resource: HttpResponseResource, +} + +#[cfg(feature = "remote")] +#[derive(Deserialize)] +struct HttpResponseResource { + kind: String, + name: String, + namespace_path: Vec, +} + +#[cfg(feature = "remote")] +fn parse_http_error_details(response_body: &str) -> Option { + let body: HttpResponseBody = serde_json::from_str(response_body).ok()?; + Some(HttpErrorDetails { + error_code: body.error_code, + resource_kind: body.resource.kind, + resource_name: body.resource.name, + namespace_path: body.resource.namespace_path, + }) +} + // reqwest's Display omits the timeout cause. Add guidance at display time so // callers still receive the original typed source and its full error chain. #[cfg(feature = "remote")] @@ -29,6 +205,48 @@ fn http_timeout_hint(source: &(dyn std::error::Error + 'static)) -> &'static str } } +/// The error that ended a streamed response. +/// +/// It is shared so that a copy of [`Error::ResponseInterrupted`] keeps it: +/// DataFusion hands one error to every partition that reads the failed input. +/// It dereferences to the underlying error, which is also the next error in the +/// source chain. +#[cfg(feature = "remote")] +#[derive(Debug, Clone)] +pub struct InterruptionSource(Arc); + +#[cfg(feature = "remote")] +impl From for InterruptionSource { + fn from(source: BoxError) -> Self { + Self(source.into()) + } +} + +#[cfg(feature = "remote")] +impl std::ops::Deref for InterruptionSource { + type Target = dyn std::error::Error + Send + Sync; + + fn deref(&self) -> &Self::Target { + self.0.as_ref() + } +} + +#[cfg(feature = "remote")] +impl Display for InterruptionSource { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +// Not `Error`: an `Arc` in the source chain hides the error it holds from +// `downcast_ref`, and so would a wrapper that implements `Error`. +#[cfg(feature = "remote")] +impl snafu::AsErrorSource for InterruptionSource { + fn as_error_source(&self) -> &(dyn std::error::Error + 'static) { + self.0.as_ref() + } +} + /// Why a job failed, to whatever precision the backend provides. /// /// A job run in this process carries the error it failed with in [`Self::source`]. @@ -41,9 +259,15 @@ pub struct JobFailure { pub phase: Option, /// A human-readable reason, when known. pub message: Option, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, /// Whether a retry could clear the failure, when known. pub retryable: Option, - /// The error the job failed with, when it ran in this process. + /// Isolated SQL job that raised this failure, when the server supplies + /// one across the Flight SQL boundary. + pub sql_job_id: Option, + /// The underlying error from a job run in this process or a structured + /// remote Flight SQL failure. pub source: Option>, } @@ -92,6 +316,13 @@ pub enum Error { EmbeddingFunctionNotFound { name: String, reason: String }, #[snafu(display("Column '{name}' was not found"))] ColumnNotFound { name: String }, + /// A missing query field with schema-qualified candidate paths. + #[snafu(display("{message}"))] + FieldNotFound { + name: String, + message: String, + source: BoxError, + }, #[snafu(display("Column '{name}' already exists"))] ColumnAlreadyExists { name: String }, #[snafu(display("Column '{name}' is not a computed column"))] @@ -110,6 +341,15 @@ pub enum Error { }, #[snafu(display("Schema Error: {message}"))] Schema { message: String }, + /// A SQL response retaining its gRPC status and server metadata. + #[cfg(feature = "remote")] + #[snafu(display("{message} (request_id={request_id})"))] + Sql { + message: String, + request_id: String, + grpc_code: i32, + metadata: Box, + }, #[snafu(display("Runtime error: {message}"))] Runtime { message: String }, #[snafu(display("Timeout error: {message}"))] @@ -117,7 +357,7 @@ pub enum Error { #[snafu(display("Job{} failed{failure}", job_id.as_ref().map(|id| format!(" {id}")).unwrap_or_default()))] JobFailed { job_id: Option, - failure: JobFailure, + failure: Box, }, #[snafu(display("Job{} was cancelled", job_id.as_ref().map(|id| format!(" {id}")).unwrap_or_default()))] JobCancelled { job_id: Option }, @@ -164,6 +404,27 @@ pub enum Error { source: Box, status_code: Option, }, + /// A streamed response stopped before the server signalled that it was complete. + /// + /// The batches already returned are valid, but the result is incomplete. The + /// request is not retried, because re-issuing it would return those batches + /// again. `table_version` is the table version the response reflected, when + /// the server reported one, so a caller can re-issue the request against it. + #[cfg(feature = "remote")] + #[snafu(display( + "Response for request_id={request_id} interrupted after {batches} batches \ + ({rows} rows): {source}{}", + http_timeout_hint(&**source) + ))] + ResponseInterrupted { + request_id: String, + /// Batches returned before the interruption. + batches: u64, + /// Rows in those batches. + rows: u64, + table_version: Option, + source: InterruptionSource, + }, #[snafu(display("Arrow error: {source}"))] Arrow { source: ArrowError }, #[snafu(display("LanceDBError: not supported: {message}"))] @@ -195,6 +456,20 @@ impl From for Error { match source { DataFusionError::ArrowError(source, _) => (*source).into(), DataFusionError::External(source) => Self::from_box_error(source), + // DataFusion adds context to an error, and shares one error between + // the partitions that read a failed input. An error of ours beneath + // either keeps its type; other errors keep the wrapper's message. + DataFusionError::Context(_, inner) if find_error(inner.as_ref()).is_some() => { + (*inner).into() + } + DataFusionError::Shared(shared) => match Arc::try_unwrap(shared) { + Ok(inner) => inner.into(), + Err(shared) => find_error(shared.as_ref()) + .and_then(Self::clone_shared) + .unwrap_or_else(|| Self::External { + source: Box::new(DataFusionError::Shared(shared)), + }), + }, other => Self::External { source: Box::new(other), }, @@ -202,6 +477,12 @@ impl From for Error { } } +/// The first error of ours in an error's source chain. +fn find_error<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a Error> { + std::iter::successors(Some(error), |error| error.source()) + .find_map(|error| error.downcast_ref::()) +} + impl From for Error { fn from(source: lance::Error) -> Self { if has_unsupported_local_filesystem_source(&source) { @@ -214,9 +495,27 @@ impl From for Error { match source { lance::Error::Wrapped { error, .. } => Self::from_box_error(error), lance::Error::External { source } => Self::from_box_error(source), - lance::Error::InvalidInput { source, .. } => Self::InvalidInput { - message: source.to_string(), - }, + lance::Error::InvalidInput { + source, location, .. + } => { + if let Some(DataFusionError::SchemaError(error, _)) = source + .downcast_ref::() + .map(|error| error.find_root()) + && let datafusion_common::SchemaError::FieldNotFound { field, .. } = + error.as_ref() + { + // Preserve the known field identity before this boundary + // turns other input diagnostics into plain messages. + log::info!("Query input rejected at {location}: {source}"); + Self::ColumnNotFound { + name: field.name.clone(), + } + } else { + Self::InvalidInput { + message: source.to_string(), + } + } + } _ => Self::Lance { source }, } } @@ -244,6 +543,78 @@ fn has_unsupported_local_filesystem_source(error: &(dyn std::error::Error + 'sta } impl Error { + /// Structured resource details reported by a remote HTTP error. + /// + /// Older servers do not include these fields, in which case this returns + /// `None` and callers should treat the error as a generic HTTP failure. + #[cfg(feature = "remote")] + pub fn http_error_details(&self) -> Option<&HttpErrorDetails> { + match self { + Self::Http { source, .. } => source + .downcast_ref::() + .and_then(|source| source.details.as_ref()), + Self::Retry { source, .. } => source + .downcast_ref::() + .and_then(Self::http_error_details), + _ => None, + } + } + + /// Classification and correlation metadata supplied by a remote server. + /// + /// Unlike parsing [`Self::to_string`], this preserves absence and does not + /// mistake a user-provided identifier for an error classification. + /// + /// ``` + /// # #[cfg(feature = "remote")] + /// fn reported_job(error: &lancedb::Error) -> Option<&str> { + /// error.remote_error_metadata()?.job_id.as_deref() + /// } + /// ``` + #[cfg(feature = "remote")] + pub fn remote_error_metadata(&self) -> Option<&RemoteErrorMetadata> { + match self { + Self::Http { source, .. } => source + .downcast_ref::() + .map(|source| &source.metadata), + Self::Retry { source, .. } => source + .downcast_ref::() + .and_then(Self::remote_error_metadata), + Self::TableNotFound { source, .. } => source + .downcast_ref::() + .and_then(Self::remote_error_metadata), + Self::JobFailed { failure, .. } => failure + .source + .as_deref() + .and_then(Self::remote_error_metadata), + Self::Sql { metadata, .. } => Some(metadata), + _ => None, + } + } + + /// A copy of an error that other partitions of a DataFusion plan still hold. + /// Only an interrupted response can be copied, because it shares its source. + fn clone_shared(&self) -> Option { + #[cfg(feature = "remote")] + if let Self::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = self + { + return Some(Self::ResponseInterrupted { + request_id: request_id.clone(), + batches: *batches, + rows: *rows, + table_version: *table_version, + source: source.clone(), + }); + } + None + } + fn from_box_error(mut source: Box) -> Self { source = match source.downcast::() { Ok(e) => match *e { @@ -337,6 +708,84 @@ impl From for Error { mod tests { use super::*; + #[test] + fn missing_filter_column_retains_its_type_across_lance_conversion() { + let field_error = DataFusionError::SchemaError( + Box::new(datafusion_common::SchemaError::FieldNotFound { + field: Box::new(datafusion_common::Column::from_name("missing")), + valid_fields: vec![datafusion_common::Column::from_name("id")], + }), + Box::new(None), + ); + let source = + lance::Error::invalid_input_source(Box::new(field_error.context("binding filter"))); + assert!(matches!(Error::from(source), Error::ColumnNotFound { name } if name == "missing")); + + let source = lance::Error::invalid_input("No field named missing"); + assert!(matches!(Error::from(source), Error::InvalidInput { .. })); + } + + /// DataFusion shares an error between the partitions that read a failed + /// input, and may add context to it. Whether or not another partition still + /// holds it, an interrupted response keeps its fields and its source. + #[cfg(feature = "remote")] + #[rstest::rstest] + fn shared_interruption_keeps_its_type_and_source( + #[values(false, true)] still_held: bool, + #[values(false, true)] with_context: bool, + ) { + let reset = BoxError::from(std::io::Error::from(std::io::ErrorKind::ConnectionReset)); + let interrupted = Error::ResponseInterrupted { + request_id: "req-1".into(), + batches: 2, + rows: 2048, + table_version: Some(7), + source: reset.into(), + }; + let shared = Arc::new(DataFusionError::External(Box::new(interrupted))); + let held = still_held.then(|| shared.clone()); + let mut error = DataFusionError::Shared(shared); + if with_context { + error = error.context("merging query results"); + } + + let error = Error::from(error); + + assert!( + matches!( + &error, + Error::ResponseInterrupted { + request_id, + batches: 2, + rows: 2048, + table_version: Some(7), + .. + } if request_id == "req-1" + ), + "{error:?}" + ); + let source = std::error::Error::source(&error).unwrap(); + assert_eq!( + source.downcast_ref::().map(|e| e.kind()), + Some(std::io::ErrorKind::ConnectionReset) + ); + drop(held); + } + + #[test] + fn other_shared_errors_keep_their_message() { + let shared = Arc::new(DataFusionError::Execution("boom".into())); + let _held = shared.clone(); + + let error = Error::from(DataFusionError::Shared(shared).context("merging")); + + assert!(matches!(error, Error::External { .. }), "{error:?}"); + assert_eq!( + error.to_string(), + "merging\ncaused by\nExecution error: boom" + ); + } + #[cfg(feature = "remote")] #[test] fn non_timeout_http_error_message_is_unchanged() { diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 128a7efdf..41a683c54 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -16,9 +16,53 @@ use serde_json::Value; use crate::secrets::SecretBinding; use crate::{Error, Result}; +mod retry; +pub use retry::{FunctionErrorPolicy, FunctionRetryPolicy}; + /// Semantic Function type for a Blob v2 value. pub const FUNCTION_BLOB_V2_TYPE: &str = "blob_v2"; +/// Configured placement-independent hardware and worker limits of a Function +/// GPU class. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct GpuClass { + /// Stable class name accepted by Function registration and refresh options. + pub name: String, + /// Kubernetes extended resource requested by this class. + pub resource_name: String, + /// Human-readable GPU model, when configured by the operator. + pub gpu_model: Option, + /// Usable memory of one GPU in the class, in bytes. + pub gpu_memory_bytes: Option, + /// Maximum GPUs one worker in this class may request. + pub max_gpu_count_per_worker: Option, + /// CPU limit for a worker in this class, in millicores. + pub cpu_millis: Option, + /// Memory limit for a worker in this class, in bytes. + pub memory_bytes: Option, + /// Ephemeral-storage limit for a worker in this class, in bytes. + pub ephemeral_storage_bytes: Option, +} + +pub(crate) const GPU_CLASS_NAME_ERROR: &str = "gpu_class must be a lowercase name of at most 63 letters, digits, or hyphens, and cannot start or end with a hyphen"; + +pub(crate) fn validate_gpu_class_name(name: &str) -> Result<()> { + if name.is_empty() + || name.len() > 63 + || name.starts_with('-') + || name.ends_with('-') + || !name + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') + { + return Err(Error::InvalidInput { + message: GPU_CLASS_NAME_ERROR.to_string(), + }); + } + Ok(()) +} + fn invalid_json(error: impl std::fmt::Display) -> Error { Error::InvalidInput { message: format!("invalid remote Function JSON: {error}"), @@ -260,6 +304,7 @@ pub enum PythonRuntimeSpec { /// system_packages: Vec::new(), /// }, /// env: BTreeMap::new(), + /// gpu_class: Some("a10g".to_string()), /// }; /// assert!(runtime.requires_gpu()); /// ``` @@ -267,6 +312,8 @@ pub enum PythonRuntimeSpec { python_version: String, environment: PythonEnvironmentSpec, env: BTreeMap, + /// Operator-defined GPU class; absent uses the deployment default. + gpu_class: Option, }, /// A runtime kind introduced by a newer server. /// @@ -317,6 +364,14 @@ impl PythonRuntimeSpec { pub fn requires_gpu(&self) -> bool { matches!(self, Self::PythonV2 { .. }) } + + /// Operator-defined GPU class, or `None` to use the deployment default. + pub fn gpu_class(&self) -> Option<&str> { + match self { + Self::PythonV2 { gpu_class, .. } => gpu_class.as_deref(), + _ => None, + } + } } #[derive(Deserialize)] @@ -327,6 +382,8 @@ struct PythonRuntimeV1Wire { env: BTreeMap, #[serde(default)] gpu: Option, + #[serde(default)] + gpu_class: Option, } #[derive(Deserialize)] @@ -336,6 +393,8 @@ struct PythonRuntimeV2Wire { #[serde(default)] env: BTreeMap, gpu: bool, + #[serde(default)] + gpu_class: Option, } impl<'de> Deserialize<'de> for PythonRuntimeSpec { @@ -356,6 +415,11 @@ impl<'de> Deserialize<'de> for PythonRuntimeSpec { "python runtime with gpu requires kind='python_v2'", )); } + if wire.gpu_class.is_some() { + return Err(de::Error::custom( + "python runtime with gpu_class requires kind='python_v2'", + )); + } Ok(Self::Python { python_version: wire.python_version, environment: wire.environment, @@ -368,10 +432,14 @@ impl<'de> Deserialize<'de> for PythonRuntimeSpec { if !wire.gpu { return Err(de::Error::custom("runtime.gpu must be true")); } + if let Some(gpu_class) = wire.gpu_class.as_deref() { + validate_gpu_class_name(gpu_class).map_err(de::Error::custom)?; + } Ok(Self::PythonV2 { python_version: wire.python_version, environment: wire.environment, env: wire.env, + gpu_class: wire.gpu_class, }) } _ => Ok(Self::Unrecognized { kind }), @@ -390,6 +458,8 @@ impl Serialize for PythonRuntimeSpec { env: &'a BTreeMap, #[serde(skip_serializing_if = "Option::is_none")] gpu: Option, + #[serde(skip_serializing_if = "Option::is_none")] + gpu_class: Option<&'a str>, } #[derive(Serialize)] @@ -408,18 +478,21 @@ impl Serialize for PythonRuntimeSpec { environment, env, gpu: None, + gpu_class: None, } .serialize(serializer), Self::PythonV2 { python_version, environment, env, + gpu_class, } => PythonRuntimeRef { kind: "python_v2", python_version, environment, env, gpu: Some(true), + gpu_class: gpu_class.as_deref(), } .serialize(serializer), Self::Unrecognized { kind } => UnrecognizedRuntimeRef { kind }.serialize(serializer), @@ -427,12 +500,36 @@ impl Serialize for PythonRuntimeSpec { } } +/// An immutable Hugging Face model snapshot required by a Function. +/// +/// The service prepares this snapshot before user code runs. `revision` is a +/// full 40-character lowercase commit SHA, not a branch or tag. +/// +/// ``` +/// use lancedb::function::HuggingFaceModel; +/// +/// let model = HuggingFaceModel { +/// repo: "sentence-transformers/all-MiniLM-L6-v2".into(), +/// revision: "1110a243fdf4706b3f48f1d95db1a4f5529b4d41".into(), +/// }; +/// ``` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HuggingFaceModel { + /// Hugging Face repository in `owner/name` form. + pub repo: String, + /// Exact repository commit containing the model snapshot. + pub revision: String, +} + /// A complete OCI Function image. Its digest is independent of catalog names. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionImage { pub manifest_digest: String, pub descriptor: Value, pub source: bool, + /// Immutable snapshots declared by this Function version. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub models: Vec, } fn deserialize_object_version<'de, D: Deserializer<'de>>( @@ -447,10 +544,41 @@ fn deserialize_object_version<'de, D: Deserializer<'de>>( } } +/// A positive, finite per-call deadline reported by the catalog. +#[derive(Debug, Clone, Copy, PartialEq, Serialize)] +#[serde(transparent)] +struct RowTimeoutSeconds(f64); + +impl Eq for RowTimeoutSeconds {} + +impl RowTimeoutSeconds { + fn get(self) -> f64 { + self.0 + } +} + +impl<'de> Deserialize<'de> for RowTimeoutSeconds { + fn deserialize>(deserializer: D) -> std::result::Result { + let seconds = f64::deserialize(deserializer)?; + if !seconds.is_finite() || seconds <= 0.0 { + return Err(de::Error::custom( + "row_timeout_seconds must be positive and finite", + )); + } + Ok(Self(seconds)) + } +} + /// One immutable Function object revision and its executable artifact. /// /// The Function is named by its parts, `name` and `namespace_path`, the way a /// [`SecretReference`](crate::secrets::SecretReference) names a Secret. +/// +/// Unknown top-level fields from newer servers are accepted for forward +/// decoding, but they are not part of this value and are omitted from +/// canonical JSON. Known fields retain their complete values, while unknown +/// fields inside the open [`FunctionImage::descriptor`] JSON object remain +/// available. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionVersion { name: String, @@ -473,6 +601,22 @@ pub struct FunctionVersion { created_at_millis: i64, metadata: BTreeMap, disabled: bool, + /// Operator-defined GPU class declared at registration. + #[serde(default, skip_serializing_if = "Option::is_none")] + gpu_class: Option, + /// Default maximum rows in one callable batch. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_batch_size" + )] + batch_size: Option, + /// Per-call deadline in seconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + row_timeout_seconds: Option, + /// Result-stability value declared at registration. + #[serde(default, skip_serializing_if = "Option::is_none")] + result_stability: Option, } impl FunctionVersion { @@ -527,6 +671,26 @@ impl FunctionVersion { self.source_digest.as_deref() } + /// Operator-defined GPU class declared at registration. + pub fn gpu_class(&self) -> Option<&str> { + self.gpu_class.as_deref() + } + + /// Default maximum rows in one callable batch, when declared. + pub fn batch_size(&self) -> Option { + self.batch_size + } + + /// Per-call deadline in seconds, when declared. + pub fn row_timeout_seconds(&self) -> Option { + self.row_timeout_seconds.map(RowTimeoutSeconds::get) + } + + /// Result-stability value declared at registration, when present. + pub fn result_stability(&self) -> Option<&str> { + self.result_stability.as_deref() + } + pub fn signature(&self) -> &FunctionSignature { &self.signature } @@ -559,9 +723,12 @@ pub struct FunctionArtifactContent { /// Internal execution adapter selected for a Python callable artifact. /// -/// The adapter converts the public scalar callable to the Arrow batch ABI -/// used by the remote executor. It is part of the request envelope, not a -/// public batch-UDF authoring mode. +/// This is part of the executor request envelope, not the user-facing Function +/// authoring mode. For version 1, the executor selects vectorized execution +/// when every callable parameter is annotated as `pyarrow.Array`; it passes one +/// Arrow array per declared input and requires an Arrow array matching the +/// declared output. Other callables are invoked row by row. Both modes use the +/// same internal adapter kind. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PythonAdapterSpec { pub kind: String, @@ -582,25 +749,105 @@ pub struct FunctionArtifactRequest { pub adapter: PythonAdapterSpec, } +fn deserialize_batch_size<'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!("batch_size: {error}")))?; + validate_batch_size_value(value).map_err(de::Error::custom)?; + Ok(value) +} + +fn deserialize_row_timeout<'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!("row_timeout_seconds: {error}")))?; + validate_row_timeout_value(value).map_err(de::Error::custom)?; + Ok(value) +} + +fn validate_batch_size_value(value: Option) -> std::result::Result<(), &'static str> { + if value == Some(0) { + return Err("batch_size must be between 1 and u32::MAX"); + } + Ok(()) +} + +fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'static str> { + if value.is_some_and(|seconds| !seconds.is_finite() || seconds <= 0.0) { + return Err("row_timeout_seconds must be positive and finite"); + } + Ok(()) +} + /// Stable request envelope for remote immutable Function registration. /// /// Credential values deliberately have no field here. The only secret-shaped /// thing a client sends is `secret_bindings`: the name of a Secret the /// database already holds, which Sophon resolves inside the remote runtime. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FunctionRegistrationRequest { + /// Default retries of failed user-code calls. Enterprise only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub retry_policy: Option, pub name: String, pub artifact: FunctionArtifactRequest, pub signature: FunctionSignature, pub runtime: PythonRuntimeSpec, + /// Maximum rows in one execution batch; the executor may use fewer. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_batch_size" + )] + pub batch_size: 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. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_row_timeout" + )] + pub row_timeout_seconds: Option, /// Declared environment variable name to the Secret it binds. A binding is /// a reference: whether the Secret exists is answered when a column is /// declared against this version, not here. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub secret_bindings: Vec, + /// Model snapshots prepared by the service before user code runs. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub models: Vec, } -impl_json!(FunctionRegistrationRequest); +impl FunctionRegistrationRequest { + /// Decode a registration request supplied by an SDK language binding. + pub fn from_json(json: &str) -> Result { + from_json(json) + } + + /// Encode the known client contract with bytewise-sorted JSON keys. + pub fn to_canonical_json(&self) -> Result { + self.validate()?; + canonical_json(self) + } + + /// Reject explicit execution controls that cannot be submitted safely. + pub fn validate(&self) -> Result<()> { + let invalid_input = |message: &'static str| Error::InvalidInput { + message: message.to_string(), + }; + validate_batch_size_value(self.batch_size).map_err(invalid_input)?; + validate_row_timeout_value(self.row_timeout_seconds).map_err(invalid_input)?; + if let Some(policy) = &self.retry_policy { + policy.validate()?; + } + Ok(()) + } +} /// Exact FunctionVersion reference embedded in applications and bindings. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -796,7 +1043,7 @@ impl_json!(FunctionBinding); /// refresh [`crate::Job`]. /// /// LanceDB Embedded refresh jobs produce this value in process. LanceDB -/// Distributed decodes the same value from the durable job's terminal payload. +/// Enterprise decodes the same value from the durable job's terminal payload. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RefreshColumnResult { /// Rows assigned a value by this refresh. @@ -856,6 +1103,9 @@ impl FunctionErrorsRequest { /// read access to the table. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionErrorRecord { + /// Number of user-code calls for this failed invocation, when recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub attempts: Option, /// The refresh job that recorded the error. pub job_id: String, /// The fragment holding the row. @@ -864,6 +1114,19 @@ pub struct FunctionErrorRecord { /// detail was capped and only the fragment summary remains. #[serde(default)] pub row_offset: Option, + /// Stable row identity at the table version the refresh read. + /// + /// Present only when that version used stable row IDs. It remains valid + /// across later compaction and rewrite, unlike `row_address`. `None` on + /// legacy tables and on records written before the server reported it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub row_id: Option, + /// Portable physical row address, `(fragment_id << 32) | row_offset`. + /// + /// `None` when the record covers a fragment rather than one row, or when + /// an older server does not report row addresses. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub row_address: Option, /// The column being computed. pub column: String, /// The Function that failed. @@ -876,6 +1139,9 @@ pub struct FunctionErrorRecord { pub error_type: String, /// The error's text. pub error_message: String, + /// User-code traceback, possibly truncated by the server. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub traceback: Option, /// When the error was recorded, in milliseconds since the epoch. pub created_at_millis: i64, } @@ -976,14 +1242,26 @@ mod conda_environment_tests { super::canonical_json(&runtime).unwrap(), r#"{"environment":{"kind":"pip"},"gpu":true,"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":"a10g"}"#, + ) + .unwrap(); + assert_eq!(runtime.gpu_class(), Some("a10g")); + assert_eq!( + super::canonical_json(&runtime).unwrap(), + r#"{"environment":{"kind":"pip"},"gpu":true,"gpu_class":"a10g","kind":"python_v2","python_version":"3.12"}"# + ); for invalid in [ r#"{"kind":"python","python_version":"3.12","environment":{"kind":"pip"},"gpu":true}"#, + r#"{"kind":"python","python_version":"3.12","environment":{"kind":"pip"},"gpu_class":"a10g"}"#, r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"}}"#, r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":1}"#, r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":false}"#, r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":"true"}"#, r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":"H100"}"#, + r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":true,"gpu_class":"H100"}"#, + r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":true,"gpu_class":"-bad"}"#, ] { assert!(serde_json::from_str::(invalid).is_err()); } @@ -1034,6 +1312,12 @@ mod tests { } assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); } + + document["gpu_class"] = serde_json::json!("a10g"); + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.gpu_class(), Some("a10g")); + let encoded: Value = serde_json::from_str(&version.to_canonical_json().unwrap()).unwrap(); + assert_eq!(encoded["gpu_class"], "a10g"); } #[test] diff --git a/rust/lancedb/src/function/retry.rs b/rust/lancedb/src/function/retry.rs new file mode 100644 index 000000000..b52d59d2b --- /dev/null +++ b/rust/lancedb/src/function/retry.rs @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Client configuration for retries inside an Enterprise Function invocation. + +use serde::{Deserialize, Serialize}; + +use crate::{Error, Result}; + +/// Retry selected user-code errors without consuming a worker retry attempt. +/// +/// A retry repeats the entire failed call, so opt in only when repeating its +/// partial work is safe. Matchers are alternatives. With a batch Function and +/// `skip`, an exhausted call skips the whole batch rather than bisecting it. +/// +/// ``` +/// use lancedb::function::FunctionRetryPolicy; +/// let policy = FunctionRetryPolicy::transient(); +/// policy.validate().unwrap(); +/// ``` +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(default, deny_unknown_fields)] +#[non_exhaustive] +pub struct FunctionRetryPolicy { + /// Total calls, including the first; 1 disables retries, maximum 100. + pub max_attempts: u32, + /// Initial exponential-backoff ceiling, with full jitter; default 0.2 seconds. + pub initial_backoff_seconds: f64, + /// Maximum backoff, including Retry-After; default 30 seconds, maximum 3600. + pub max_backoff_seconds: f64, + /// Exception class names, preferably qualified; subclasses also match. + pub exception_types: Vec, + /// Regular expression matched against the exception class and message. + pub message_pattern: Option, + /// Structured provider error codes or HTTP status codes, represented as strings. + pub error_codes: Vec, + /// Match connection/timeouts, HTTP 429/503, SlowDown and ServiceUnavailable. + pub transient: bool, + /// Honor Retry-After within the configured maximum; default true. + pub honor_retry_after: bool, +} + +impl Default for FunctionRetryPolicy { + fn default() -> Self { + Self { + max_attempts: 3, + initial_backoff_seconds: 0.2, + max_backoff_seconds: 30.0, + exception_types: Vec::new(), + message_pattern: None, + error_codes: Vec::new(), + transient: false, + honor_retry_after: true, + } + } +} + +impl FunctionRetryPolicy { + /// Retry known transient errors up to three calls with bounded backoff. + pub fn transient() -> Self { + Self { + transient: true, + ..Self::default() + } + } + + /// Validate before registration or refresh submission. + pub fn validate(&self) -> Result<()> { + let invalid = |message: String| Error::InvalidInput { message }; + if !(1..=100).contains(&self.max_attempts) { + return Err(invalid(format!( + "retry_policy.max_attempts must be between 1 and 100, got {}", + self.max_attempts + ))); + } + for (name, value) in [ + ("initial_backoff_seconds", self.initial_backoff_seconds), + ("max_backoff_seconds", self.max_backoff_seconds), + ] { + if !value.is_finite() || !(0.0..=3600.0).contains(&value) { + return Err(invalid(format!( + "retry_policy.{name} must be finite and between 0 and 3600, got {value}" + ))); + } + } + if self.initial_backoff_seconds > self.max_backoff_seconds { + return Err(invalid( + "retry_policy.initial_backoff_seconds exceeds max_backoff_seconds".into(), + )); + } + if self + .exception_types + .iter() + .chain(&self.error_codes) + .any(String::is_empty) + { + return Err(invalid( + "retry_policy exception_types and error_codes must contain non-empty strings" + .into(), + )); + } + if let Some(pattern) = &self.message_pattern { + regex::Regex::new(pattern).map_err(|error| { + invalid(format!("invalid retry_policy.message_pattern: {error}")) + })?; + } + if self.max_attempts > 1 + && !self.transient + && self.message_pattern.is_none() + && self.exception_types.is_empty() + && self.error_codes.is_empty() + { + return Err(invalid( + "retry_policy requires at least one error matcher".into(), + )); + } + Ok(()) + } +} + +/// What a Function refresh does after a call fails or exhausts retries. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionErrorPolicy { + /// Fail the refresh job. + Fail, + /// Write null and record the error, subject to the server's failure limits. + Skip, +} + +#[cfg(test)] +mod tests { + use super::*; + use rstest::rstest; + use serde_json::json; + + #[rstest] + #[case(json!({"max_attempts": 0, "transient": true}))] + #[case(json!({"max_attempts": 101, "transient": true}))] + #[case(json!({"max_attempts": 3}))] + #[case(json!({"initial_backoff_seconds": -1, "transient": true}))] + #[case(json!({"max_backoff_seconds": 0, "transient": true}))] + #[case(json!({"exception_types": [""]}))] + #[case(json!({"message_pattern": "["}))] + fn reject_invalid_policy(#[case] value: serde_json::Value) { + let policy: FunctionRetryPolicy = serde_json::from_value(value).unwrap(); + assert!(policy.validate().is_err()); + } + + #[test] + fn policy_defaults_and_disabled_policy() { + assert!(FunctionRetryPolicy::transient().validate().is_ok()); + let policy: FunctionRetryPolicy = + serde_json::from_value(json!({"max_attempts":1})).unwrap(); + assert!(policy.validate().is_ok()); + let mut invalid = policy; + invalid.initial_backoff_seconds = f64::NAN; + assert!(invalid.validate().is_err()); + } +} diff --git a/rust/lancedb/src/graph.rs b/rust/lancedb/src/graph.rs new file mode 100644 index 000000000..510fd780d --- /dev/null +++ b/rust/lancedb/src/graph.rs @@ -0,0 +1,281 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Property graphs: a graph defined over tables a database already holds. +//! +//! A property graph stores no rows. Its definition says which tables of its +//! namespace hold nodes and which hold edges -- each node table's key and +//! label, each edge table's label and the node keys its source and destination +//! columns reference -- the shape of SQL/PGQ's `CREATE PROPERTY GRAPH`. A query +//! reads the tables through SQL `GRAPH_TABLE`, as they are when it runs. +//! +//! The verbs live on [`crate::connection::Connection`]. A graph is read +//! through SQL, by name, so there is no handle returning its rows. + +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; + +/// A property graph's node and edge tables. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PropertyGraphDefinition { + /// The node tables, one per label. + pub nodes: Vec, + /// The edge tables, one per label. + #[serde(default)] + pub edges: Vec, +} + +impl PropertyGraphDefinition { + /// Parse a definition from its JSON form. + pub fn from_json(json: &str) -> Result { + serde_json::from_str(json).map_err(|source| Error::InvalidInput { + message: format!("invalid property graph definition: {source}"), + }) + } +} + +/// A table whose rows are the nodes of one label. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct NodeTable { + /// The table, in the graph's namespace. + pub table: String, + /// The column that identifies a node. + pub key: String, + /// The label its nodes carry. + pub label: String, + /// The columns exposed as node properties; every column when absent. A + /// created graph reports the list it resolved to, the key among them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub properties: Option>, +} + +impl NodeTable { + /// The nodes labeled `label` are the rows of `table`, each identified by + /// its `key` column, with every column a property. + pub fn new(table: impl Into, key: impl Into, label: impl Into) -> Self { + Self { + table: table.into(), + key: key.into(), + label: label.into(), + properties: None, + } + } + + /// Expose only these columns as node properties. + pub fn properties(mut self, properties: impl IntoIterator>) -> Self { + self.properties = Some(properties.into_iter().map(Into::into).collect()); + self + } +} + +/// A table whose rows are the edges of one label. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct EdgeTable { + /// The table, in the graph's namespace. + pub table: String, + /// The label its edges carry. + pub label: String, + /// The column naming each edge's source node. + pub source: Endpoint, + /// The column naming each edge's destination node. + pub destination: Endpoint, + /// The columns exposed as edge properties; every column when absent. A + /// created graph reports the list it resolved to, both endpoint columns + /// among them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub properties: Option>, +} + +impl EdgeTable { + /// The edges labeled `label` are the rows of `table`, running from the + /// node `source` names to the node `destination` names, with every column + /// a property. + pub fn new( + table: impl Into, + label: impl Into, + source: Endpoint, + destination: Endpoint, + ) -> Self { + Self { + table: table.into(), + label: label.into(), + source, + destination, + properties: None, + } + } + + /// Expose only these columns as edge properties. + pub fn properties(mut self, properties: impl IntoIterator>) -> Self { + self.properties = Some(properties.into_iter().map(Into::into).collect()); + self + } +} + +/// One end of an edge: a column of the edge table and the node key it holds. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Endpoint { + /// The edge table's column. + pub column: String, + /// The node table and key column its values match. + pub references: EndpointReference, +} + +impl Endpoint { + /// The edge table's `column`, holding keys of the node table `table`, + /// whose key column is `key`. + pub fn new( + column: impl Into, + table: impl Into, + key: impl Into, + ) -> Self { + Self { + column: column.into(), + references: EndpointReference { + table: table.into(), + column: key.into(), + }, + } + } +} + +/// The node table and key column an endpoint's values match. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct EndpointReference { + /// A node table of the same graph. + pub table: String, + /// That node table's key column. + pub column: String, +} + +/// What a database records about one property graph: its node and edge +/// tables, with each table's properties as create resolved them. +/// +/// Returned by [`crate::connection::Connection::describe_property_graph`], and +/// by `create_property_graph` so a caller has the resolved properties without +/// a second call. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PropertyGraphDescription { + /// The graph's name within its namespace. + pub name: String, + /// The namespace holding the graph; empty is the root namespace. + #[serde(rename = "namespace", default)] + pub namespace_path: Vec, + /// The graph's node and edge tables. + #[serde(flatten)] + pub definition: PropertyGraphDefinition, +} + +impl PropertyGraphDescription { + /// The description in its JSON form. + pub fn to_json(&self) -> Result { + serde_json::to_string(self).map_err(|source| Error::Runtime { + message: format!("could not encode a property graph description: {source}"), + }) + } +} + +#[cfg(test)] +mod tests { + use futures::TryStreamExt; + + use super::*; + + fn social() -> PropertyGraphDefinition { + PropertyGraphDefinition { + nodes: vec![NodeTable::new("person", "person_id", "Person").properties(["name"])], + edges: vec![EdgeTable::new( + "knows", + "KNOWS", + Endpoint::new("src_id", "person", "person_id"), + Endpoint::new("dst_id", "person", "person_id"), + )], + } + } + + #[test] + fn test_a_definition_is_the_sql_pgq_shape() { + let json = serde_json::to_value(social()).unwrap(); + // Properties left out are left out of the body too: absent means every + // column, which an empty list would not. + assert_eq!( + json, + serde_json::json!({ + "nodes": [{"table": "person", "key": "person_id", "label": "Person", + "properties": ["name"]}], + "edges": [{"table": "knows", "label": "KNOWS", + "source": {"column": "src_id", + "references": {"table": "person", "column": "person_id"}}, + "destination": {"column": "dst_id", + "references": {"table": "person", + "column": "person_id"}}}] + }) + ); + assert_eq!( + PropertyGraphDefinition::from_json(&json.to_string()).unwrap(), + social() + ); + assert_eq!( + PropertyGraphDefinition::from_json(r#"{"nodes": []}"#).unwrap(), + PropertyGraphDefinition { + nodes: vec![], + edges: vec![], + } + ); + assert!(matches!( + PropertyGraphDefinition::from_json(r#"{"edges": []}"#), + Err(Error::InvalidInput { .. }) + )); + } + + #[test] + fn test_a_description_carries_its_definition_at_the_top_level() { + let description = PropertyGraphDescription { + name: "social".to_string(), + namespace_path: vec!["analytics".to_string()], + definition: social(), + }; + let json: serde_json::Value = + serde_json::from_str(&description.to_json().unwrap()).unwrap(); + assert_eq!(json["name"], "social"); + assert_eq!(json["namespace"], serde_json::json!(["analytics"])); + assert_eq!(json["nodes"][0]["table"], "person"); + assert_eq!(json["edges"][0]["label"], "KNOWS"); + let decoded: PropertyGraphDescription = serde_json::from_value(json).unwrap(); + assert_eq!(decoded, description); + } + + #[tokio::test] + async fn test_local_databases_refuse_property_graphs() { + let dir = tempfile::tempdir().unwrap(); + let conn = crate::connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let refused = |error: Error| { + assert!( + matches!(error, Error::NotSupported { ref message } + if message.contains("Property graph operations")), + "{error}" + ); + }; + refused( + conn.create_property_graph("social", &social(), &[]) + .await + .unwrap_err(), + ); + refused( + conn.describe_property_graph("social", &[]) + .await + .unwrap_err(), + ); + refused(conn.drop_property_graph("social", &[]).await.unwrap_err()); + refused( + conn.list_property_graphs(&[], Default::default()) + .try_collect::>() + .await + .unwrap_err(), + ); + } +} diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index e9056863a..87eff864d 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -49,7 +49,7 @@ pub enum Index { Bitmap(BitmapIndexBuilder), /// [LabelListIndexBuilder] is a scalar index that can be used on `List` columns to - /// support queries with `array_contains_all` and `array_contains_any` + /// support queries with `array_has_all` and `array_has_any` /// using an underlying bitmap index. LabelList(LabelListIndexBuilder), @@ -482,47 +482,47 @@ pub struct IndexConfig { /// /// An index may be made up of multiple segments, each with their own UUID. /// This is the UUID of the first segment. `None` if it could not be - /// determined (e.g. in LanceDB Distributed, which does not yet surface this). + /// determined (e.g. in LanceDB Enterprise, which does not yet surface this). pub index_uuid: Option, /// The protobuf type URL, a precise type identifier for the index. /// - /// `None` if unavailable (e.g. in LanceDB Distributed). + /// `None` if unavailable (e.g. in LanceDB Enterprise). pub type_url: Option, /// When the index was created, taken as the minimum creation time across /// all segments. /// /// `None` if unavailable, such as for indices created before creation - /// timestamps were tracked, or in LanceDB Distributed. + /// timestamps were tracked, or in LanceDB Enterprise. pub created_at: Option>, /// The number of rows indexed, across all segments. /// /// This is approximate and may include rows that have since been deleted. - /// `None` if unavailable (e.g. in LanceDB Distributed when the server + /// `None` if unavailable (e.g. in LanceDB Enterprise when the server /// does not report it). pub num_indexed_rows: Option, /// The number of rows in the table that are not yet covered by this index. /// /// Computed as the table's total row count minus [`Self::num_indexed_rows`]. /// Optimizing the index will fold these rows into it. `None` if unavailable - /// (e.g. in LanceDB Distributed when the server does not report it). + /// (e.g. in LanceDB Enterprise when the server does not report it). pub num_unindexed_rows: Option, /// The total size in bytes of all index files across all segments. /// /// `None` if size information is unavailable, such as for indices created - /// before file sizes were tracked, or in LanceDB Distributed. + /// before file sizes were tracked, or in LanceDB Enterprise. pub size_bytes: Option, /// The number of segments that make up the index. /// - /// `None` if unavailable (e.g. in LanceDB Distributed). + /// `None` if unavailable (e.g. in LanceDB Enterprise). pub num_segments: Option, /// The on-disk index format version, taken from the first segment. /// - /// `None` if unavailable (e.g. in LanceDB Distributed). + /// `None` if unavailable (e.g. in LanceDB Enterprise). pub index_version: Option, /// Index-type-specific details, serialized as JSON. /// /// The shape of this JSON varies by index type. `None` if the details - /// could not be produced (e.g. no plugin available) or in LanceDB Distributed. + /// could not be produced (e.g. no plugin available) or in LanceDB Enterprise. pub index_details: Option, } diff --git a/rust/lancedb/src/index/scalar.rs b/rust/lancedb/src/index/scalar.rs index 5d2256381..2555c1439 100644 --- a/rust/lancedb/src/index/scalar.rs +++ b/rust/lancedb/src/index/scalar.rs @@ -45,7 +45,7 @@ pub struct BitmapIndexBuilder {} /// Builder for LabelList index. /// /// [LabeListIndexBuilder] is a scalar index that can be used on `List` columns to -/// support queries with `array_contains_all` and `array_contains_any` +/// support queries with `array_has_all` and `array_has_any` /// using an underlying bitmap index. /// #[derive(Debug, Clone, Default, serde::Serialize)] diff --git a/rust/lancedb/src/io/object_store.rs b/rust/lancedb/src/io/object_store.rs index c4a9a4f7e..3c0c0fe58 100644 --- a/rust/lancedb/src/io/object_store.rs +++ b/rust/lancedb/src/io/object_store.rs @@ -15,9 +15,6 @@ use object_store::{ use async_trait::async_trait; -#[cfg(test)] -pub mod io_tracking; - #[derive(Debug)] struct MirroringObjectStore { primary: Arc, @@ -348,11 +345,6 @@ mod test { )); } - // This test is ignored because lance 3.0 introduced LocalWriter optimization - // that bypasses the object store wrapper for local writes. The mirroring feature - // still works for remote/cloud storage, but can't be tested with local storage. - // See lance commit c878af433 "perf: create local writer for efficient local writes" - #[ignore] #[tokio::test] async fn test_e2e() { let dir1 = tempfile::tempdir().unwrap().keep().canonicalize().unwrap(); @@ -363,7 +355,13 @@ mod test { secondary: Arc::new(secondary_store), }); - let db = connect(dir1.to_str().unwrap()).execute().await.unwrap(); + // Lance writes `file://` tables through LocalWriter, which skips object store + // wrappers. `file-object-store://` writes the same local files through the + // wrapped store. + let db = connect(&format!("file-object-store://{}", dir1.display())) + .execute() + .await + .unwrap(); let mut param = WriteParams::default(); let store_params = ObjectStoreParams { @@ -416,7 +414,7 @@ mod test { || path_str.contains("_transactions") }; - let primary_files: Vec<_> = WalkDir::new(&primary_location) + let mut primary_files: Vec<_> = WalkDir::new(&primary_location) .into_iter() .filter_entry(|e| !should_skip(e.path())) .filter_map(|e| e.ok()) @@ -427,8 +425,9 @@ mod test { .to_path_buf() }) .collect(); + primary_files.sort(); - let secondary_files: Vec<_> = WalkDir::new(&secondary_location) + let mut secondary_files: Vec<_> = WalkDir::new(&secondary_location) .into_iter() .filter_entry(|e| !should_skip(e.path())) .filter_map(|e| e.ok()) @@ -439,6 +438,7 @@ mod test { .to_path_buf() }) .collect(); + secondary_files.sort(); assert_eq!(primary_files, secondary_files, "File lists should match"); } diff --git a/rust/lancedb/src/io/object_store/io_tracking.rs b/rust/lancedb/src/io/object_store/io_tracking.rs deleted file mode 100644 index 7f9750216..000000000 --- a/rust/lancedb/src/io/object_store/io_tracking.rs +++ /dev/null @@ -1,250 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright The LanceDB Authors - -use std::{ - fmt::{Display, Formatter}, - sync::{Arc, Mutex}, -}; - -use bytes::Bytes; -use futures::stream::BoxStream; -use lance::io::WrappingObjectStore; -use object_store::{ - CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, - PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions, Result as OSResult, - UploadPart, list::PaginatedListStore, path::Path, -}; - -#[derive(Debug, Default)] -pub struct IoStats { - pub read_iops: u64, - pub read_bytes: u64, - pub write_iops: u64, - pub write_bytes: u64, -} - -impl Display for IoStats { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:#?}", self) - } -} - -#[derive(Debug, Clone)] -pub struct IoTrackingStore { - target: Arc, - stats: Arc>, -} - -impl Display for IoTrackingStore { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:#?}", self) - } -} - -#[derive(Debug, Default, Clone)] -pub struct IoStatsHolder(Arc>); - -impl IoStatsHolder { - pub fn incremental_stats(&self) -> IoStats { - std::mem::take(&mut self.0.lock().expect("failed to lock IoStats")) - } -} - -impl WrappingObjectStore for IoStatsHolder { - fn wrap(&self, _store_prefix: &str, target: Arc) -> Arc { - Arc::new(IoTrackingStore { - target, - stats: self.0.clone(), - }) - } - - fn wrap_paginated( - &self, - _store_prefix: &str, - original: Arc, - ) -> Option> { - Some(original) - } -} - -impl IoTrackingStore { - pub fn new_wrapper() -> (Arc, Arc>) { - let stats = Arc::new(Mutex::new(IoStats::default())); - (Arc::new(IoStatsHolder(stats.clone())), stats) - } - - fn record_read(&self, num_bytes: u64) { - let mut stats = self.stats.lock().unwrap_or_else(|e| e.into_inner()); - stats.read_iops += 1; - stats.read_bytes += num_bytes; - } - - fn record_write(&self, num_bytes: u64) { - let mut stats = self.stats.lock().unwrap_or_else(|e| e.into_inner()); - stats.write_iops += 1; - stats.write_bytes += num_bytes; - } -} - -#[async_trait::async_trait] -#[deny(clippy::missing_trait_methods)] -impl ObjectStore for IoTrackingStore { - async fn put_opts( - &self, - location: &Path, - bytes: PutPayload, - opts: PutOptions, - ) -> OSResult { - self.record_write(bytes.content_length() as u64); - self.target.put_opts(location, bytes, opts).await - } - - async fn put_multipart_opts( - &self, - location: &Path, - opts: PutMultipartOptions, - ) -> OSResult> { - let target = self.target.put_multipart_opts(location, opts).await?; - Ok(Box::new(IoTrackingMultipartUpload { - target, - stats: self.stats.clone(), - })) - } - - async fn get_opts(&self, location: &Path, options: GetOptions) -> OSResult { - let result = self.target.get_opts(location, options).await; - if let Ok(result) = &result { - let num_bytes = result.range.end - result.range.start; - self.record_read(num_bytes); - } - result - } - - async fn get_ranges( - &self, - location: &Path, - ranges: &[std::ops::Range], - ) -> OSResult> { - let result = self.target.get_ranges(location, ranges).await; - if let Ok(result) = &result { - self.record_read(result.iter().map(|b| b.len() as u64).sum()); - } - result - } - - fn delete_stream( - &self, - locations: BoxStream<'static, OSResult>, - ) -> BoxStream<'static, OSResult> { - self.record_write(0); - self.target.delete_stream(locations) - } - - fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, OSResult> { - self.record_read(0); - self.target.list(prefix) - } - - fn list_with_offset( - &self, - prefix: Option<&Path>, - offset: &Path, - ) -> BoxStream<'static, OSResult> { - self.record_read(0); - self.target.list_with_offset(prefix, offset) - } - - async fn list_with_delimiter(&self, prefix: Option<&Path>) -> OSResult { - self.record_read(0); - self.target.list_with_delimiter(prefix).await - } - - async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> OSResult<()> { - self.record_write(0); - self.target.copy_opts(from, to, options).await - } - - async fn rename_opts(&self, from: &Path, to: &Path, options: RenameOptions) -> OSResult<()> { - self.record_write(0); - self.target.rename_opts(from, to, options).await - } -} - -#[derive(Debug)] -struct IoTrackingMultipartUpload { - target: Box, - stats: Arc>, -} - -#[async_trait::async_trait] -impl MultipartUpload for IoTrackingMultipartUpload { - async fn abort(&mut self) -> OSResult<()> { - self.target.abort().await - } - - async fn complete(&mut self) -> OSResult { - self.target.complete().await - } - - fn put_part(&mut self, payload: PutPayload) -> UploadPart { - { - let mut stats = self.stats.lock().unwrap_or_else(|e| e.into_inner()); - stats.write_iops += 1; - stats.write_bytes += payload.content_length() as u64; - } - self.target.put_part(payload) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Helper: poison a Mutex by panicking while holding the lock. - fn poison_stats(stats: &Arc>) { - let stats_clone = stats.clone(); - let handle = std::thread::spawn(move || { - let _guard = stats_clone.lock().unwrap(); - panic!("intentional panic to poison stats mutex"); - }); - let _ = handle.join(); - assert!(stats.lock().is_err(), "mutex should be poisoned"); - } - - #[test] - fn test_record_read_recovers_from_poisoned_lock() { - let stats = Arc::new(Mutex::new(IoStats::default())); - let store = IoTrackingStore { - target: Arc::new(object_store::memory::InMemory::new()), - stats: stats.clone(), - }; - - poison_stats(&stats); - - // record_read should not panic - store.record_read(1024); - - // Verify the stats were updated despite poisoning - let s = stats.lock().unwrap_or_else(|e| e.into_inner()); - assert_eq!(s.read_iops, 1); - assert_eq!(s.read_bytes, 1024); - } - - #[test] - fn test_record_write_recovers_from_poisoned_lock() { - let stats = Arc::new(Mutex::new(IoStats::default())); - let store = IoTrackingStore { - target: Arc::new(object_store::memory::InMemory::new()), - stats: stats.clone(), - }; - - poison_stats(&stats); - - // record_write should not panic - store.record_write(2048); - - let s = stats.lock().unwrap_or_else(|e| e.into_inner()); - assert_eq!(s.write_iops, 1); - assert_eq!(s.write_bytes, 2048); - } -} diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 0e88a7432..8644c6a48 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -5,7 +5,7 @@ use std::future::Future; use std::pin::Pin; -use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; +use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; use arrow_array::RecordBatch; use async_trait::async_trait; @@ -16,8 +16,14 @@ use tokio::task::{AbortHandle, JoinHandle}; use uuid::Uuid; use crate::database::JobDescription; +use crate::docs::DocLink; use crate::error::{Error, JobFailure, Result}; +/// 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>; + /// Which of a job's events [`Job::events`] returns. /// /// The handle already knows which job to ask about, so this narrows the @@ -49,7 +55,7 @@ impl JobEventsRequest { fn job_detail_not_supported(what: &str) -> Result { Err(Error::NotSupported { - message: format!("{what} is only available for server-side jobs"), + message: DocLink::Jobs.append_to(format!("{what} is only available for server-side jobs")), }) } @@ -65,6 +71,14 @@ pub(crate) trait JobHandle: Send + Sync { } async fn status(&self) -> Result; async fn wait(&self) -> Result; + /// Wait while observing descriptions from the same backend poller. + /// Backends without a server-side record keep the default behavior. + async fn wait_with_progress( + &self, + _progress: Option, + ) -> Result { + self.wait().await + } async fn cancel(&self) -> Result<()>; /// The job's full server-side record. Backends that run the operation in /// this process have none and keep the default. @@ -104,6 +118,11 @@ impl TerminalResult { self.value.as_ref() } + pub(crate) fn with_value(mut self, value: Value) -> Self { + self.value = Some(value); + self + } + fn decode(self) -> Result { let value = self.value.ok_or_else(|| match &self.request_id { Some(request_id) => remote_job_error( @@ -366,6 +385,15 @@ where self.refresh_state().await } + /// The current structured progress snapshot, or `None` for an in-process + /// operation. This refreshes the server-side record once, matching + /// [`Job::status`]; older servers return lifecycle and queue fields without + /// job-type-specific counters. + pub async fn progress(&self) -> Result> { + self.refresh_state().await?; + Ok(self.with_description(JobDescription::progress_snapshot)) + } + /// The last lifecycle state this handle observed, without contacting the /// backend. `None` until the handle has. pub fn state(&self) -> Option { @@ -447,9 +475,25 @@ 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 + } + + /// Wait for the operation while observing progress from the backend's + /// existing wait poller. The callback is called once for each description + /// the poller fetches, including the terminal observation when the server + /// supplies one. It does not create another lifecycle or retry loop. + pub async fn wait_with_progress(&self, progress: F) -> Result + where + F: FnMut(&JobDescription) + Send + 'static, + { + self.wait_with_progress_opt(Some(Arc::new(Mutex::new(progress)))) + .await + } + + async fn wait_with_progress_opt(&self, progress: Option) -> Result { match &self.inner { JobInner::Handle { handle, decode } => { - let settled = handle.wait().await; + let settled = handle.wait_with_progress(progress).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) { @@ -536,10 +580,13 @@ impl Outcome { fn into_result(self) -> Result { match self { Self::Succeeded(result) => Ok(result), - Self::Failed(source) => Err(Error::JobFailed { - job_id: None, - failure: JobFailure::from_source(source), - }), + Self::Failed(source) => { + let (job_id, failure) = match source.as_ref() { + Error::JobFailed { job_id, failure } => (job_id.clone(), failure.clone()), + _ => (None, Box::new(JobFailure::from_source(source))), + }; + Err(Error::JobFailed { job_id, failure }) + } Self::Cancelled => Err(Error::JobCancelled { job_id: None }), } } diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index fa6850f14..0f02d90cf 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -39,7 +39,7 @@ //! - `experimental-functions` - Opt in to local SQL computed-column declarations //! and refresh, and local materialized-view creation and refresh. Disabled by //! default, including in published Python and TypeScript packages. LanceDB -//! Distributed operations, reading existing data, metadata protections, +//! Enterprise operations, reading existing data, metadata protections, //! and ordinary eager `add_columns` transforms do not require this feature. //! - `huggingface` - Enable HuggingFace Hub integration for loading datasets from the Hub. //! - `fp16kernels` - Enable FP16 kernels for faster vector search on CPU. @@ -195,10 +195,12 @@ pub mod connection; pub mod data; pub mod database; pub mod dataloader; +pub mod docs; pub mod embeddings; pub mod error; pub mod expr; pub mod function; +pub mod graph; pub mod index; pub mod io; pub mod ipc; @@ -215,6 +217,7 @@ pub mod remote; pub mod rerankers; pub mod secrets; pub mod sql; +pub mod storage_integration; pub mod table; #[cfg(test)] pub mod test_utils; @@ -331,8 +334,9 @@ impl Display for DistanceType { /// Controls the speed / accuracy tradeoff for approximate vector search. /// -/// This currently only affects RQ-quantized vector indexes, such as IVF_RQ. -/// Other index types ignore this setting. +/// This currently affects RQ-quantized vector indexes (such as IVF_RQ) and +/// prefiltered search on HNSW sub-indexes, where `Fast` enables the ACORN +/// traversal. Other index types ignore this setting. #[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] #[non_exhaustive] #[serde(rename_all = "lowercase")] diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index fa51cbf25..c263dc001 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -171,7 +171,7 @@ pub(crate) fn physical_unnest( return Err(Error::NotSupported { message: format!( "'{name}' in FROM position is a Function; views over Function rows are \ - supported only in LanceDB Distributed" + supported only in LanceDB Enterprise" ), }); } @@ -1665,7 +1665,7 @@ impl CreateMaterializedViewBuilder { self } - /// Enable or disable automatic refresh in LanceDB Distributed. + /// Enable or disable automatic refresh in LanceDB Enterprise. /// When omitted, the server determines whether automatic refresh is enabled. /// LanceDB Embedded does not support automatic refresh. pub fn auto_refresh_enabled(mut self, enabled: bool) -> Self { @@ -1673,7 +1673,7 @@ impl CreateMaterializedViewBuilder { self } - /// Set a positive, finite refresh interval in seconds in LanceDB Distributed. + /// Set a positive, finite refresh interval in seconds in LanceDB Enterprise. /// When omitted, the server determines when to refresh. /// /// ```no_run @@ -1766,7 +1766,7 @@ impl CreateMaterializedViewBuilder { crate::require_experimental_functions()?; if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { return Err(Error::NotSupported { - message: "automatic materialized-view refresh requires LanceDB Distributed" + message: "automatic materialized-view refresh requires LanceDB Enterprise" .to_string(), }); } @@ -1863,18 +1863,119 @@ impl MaterializedView { view: self.clone(), source_version: None, full: false, + options: Default::default(), } } } +/// Per-execution resource caps and GPU placement for Enterprise MV refreshes. +/// +/// CPU is in millicores (1000 = one core), memory is bytes, and GPUs are a +/// simultaneous cap across the refresh, not a per-Function allocation. CPU or +/// memory requires all three budget fields. Embedded refreshes reject 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 gpu_class: 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.gpu_class.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) { + 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", + )); + } + if let Some(class) = &self.gpu_class { + crate::function::validate_gpu_class_name(class)?; + if self.gpu_count == Some(0) { + return Err(invalid("gpu_class requires a positive GPU budget")); + } + } + Ok(()) + } + + pub(crate) fn sql_clause(&self, full: bool) -> Result { + self.validate()?; + let mut values = Vec::new(); + if full { + values.push("full = true".to_string()); + } + if let Some(cpu) = self.cpu_millis { + values.push(format!("cpu_millis = {cpu}")); + } + if let Some(memory) = self.memory_bytes { + values.push(format!("memory_bytes = {memory}")); + } + if let Some(gpu) = self.gpu_count { + values.push(format!("gpu_count = {gpu}")); + } + if let Some(class) = &self.gpu_class { + values.push(format!("gpu_class = '{class}'")); + } + Ok(if values.is_empty() { + String::new() + } else { + format!(" WITH ({})", values.join(", ")) + }) + } +} + /// Builds a refresh. Created by [`MaterializedView::refresh`]. pub struct RefreshMaterializedViewBuilder { view: MaterializedView, source_version: Option, full: bool, + options: RefreshMaterializedViewOptions, } impl RefreshMaterializedViewBuilder { + /// 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); + 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); + 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); + self + } + + /// Select an operator-configured GPU class for this execution only. + pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { + self.options.gpu_class = Some(gpu_class.into()); + self + } + /// Force a complete rebuild instead of letting the server choose /// the refresh mode. Defaults to `false`. LanceDB Embedded views always rebuild. /// @@ -1900,14 +2001,22 @@ impl RefreshMaterializedViewBuilder { /// Submit the refresh and return a job that settles with its result. pub async fn execute_async(self) -> Result> { + self.options.validate()?; if self.view.table.as_native().is_none() { return self .view .table .base_table() - .refresh_materialized_view_async(self.source_version, self.full) + .refresh_materialized_view_async_with_options( + self.source_version, + self.full, + self.options, + ) .await; } + if !self.options.is_empty() { + return Err(Error::NotSupported { message: "resource budgets and GPU placement require an Enterprise materialized-view refresh".into() }); + } crate::require_experimental_functions()?; Ok(Job::spawned(tokio::spawn(async move { refresh::execute_refresh(&self.view.table, self.source_version).await @@ -1916,6 +2025,10 @@ impl RefreshMaterializedViewBuilder { /// Refresh the view, waiting for the job to finish. pub async fn execute(self) -> Result { + self.options.validate()?; + if self.view.table.as_native().is_some() && !self.options.is_empty() { + return Err(Error::NotSupported { message: "resource budgets and GPU placement require an Enterprise materialized-view refresh".into() }); + } if self.view.table.as_native().is_some() { return refresh::execute_refresh(&self.view.table, self.source_version).await; } @@ -2015,7 +2128,7 @@ impl Connection { /// Start dropping a materialized view and return its job. /// /// This validates that the named resource is a materialized view rather - /// than an ordinary table. In LanceDB Distributed the job has type `query` + /// than an ordinary table. In LanceDB Enterprise the job has type `query` /// and its ID identifies the SQL query. Waiting completes once the catalog /// binding is removed; physical cleanup continues in the background. /// @@ -2051,10 +2164,52 @@ impl Connection { #[cfg(test)] mod tests { - use arrow_array::{RecordBatch, record_batch}; + use arrow_array::{FixedSizeListArray, Float32Array, Int32Array, RecordBatch, record_batch}; + use futures::TryStreamExt; + use lance_arrow::FixedSizeListArrayExt; use super::*; use crate::connect; + use crate::index::vector::IvfFlatIndexBuilder; + use crate::index::{Index, IndexType}; + use crate::query::{ExecutableQuery, QueryBase}; + + /// A source of `rows` 4-d vectors. Hand-rolled rather than `record_batch!` + /// because the macro has no fixed-size-list form. + async fn db_with_vectors(rows: i32) -> (Connection, Table) { + const DIM: i32 = 4; + let vectors = FixedSizeListArray::try_new_from_values( + Float32Array::from((0..rows * DIM).map(|v| v as f32).collect::>()), + DIM, + ) + .unwrap(); + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int32, true), + ArrowField::new( + "vec", + DataType::FixedSizeList( + Arc::new(ArrowField::new("item", DataType::Float32, true)), + DIM, + ), + true, + ), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from_iter_values(0..rows)), + Arc::new(vectors), + ], + ) + .unwrap(); + let conn = connect("memory://").execute().await.unwrap(); + let table = conn + .create_table("src", vec![batch]) + .execute() + .await + .unwrap(); + (conn, table) + } #[test] fn remote_source_namespace_uses_one_sql_schema_position() { @@ -2109,6 +2264,15 @@ mod tests { .await .unwrap(); + assert!(matches!( + view.refresh().gpu_count(0).execute().await, + Err(Error::NotSupported { .. }) + )); + assert!(matches!( + view.refresh().gpu_class("h100").execute_async().await, + Err(Error::NotSupported { .. }) + )); + assert_eq!(view.table().count_rows(None).await.unwrap(), 2); assert!( view.table() @@ -2398,6 +2562,102 @@ mod tests { ); } + /// The fragment-swap rebuild replaces every fragment the vector index was + /// trained over. Its definition must survive, and search must still answer + /// over the replacement rows before maintenance indexes them again. + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn test_rebuild_retains_vector_index() { + let (conn, source) = db_with_vectors(256).await; + let view = conn + .create_materialized_view("vecs", "src") + .select([("id", "id"), ("vec", "vec")]) + .execute() + .await + .unwrap(); + view.table() + .create_index( + &["vec"], + Index::IvfFlat( + IvfFlatIndexBuilder::default() + .num_partitions(1) + .sample_rate(1) + .max_iterations(1), + ), + ) + .execute() + .await + .unwrap(); + + let indices = view.table().list_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + let index_name = indices[0].name.clone(); + assert_eq!(indices[0].index_type, IndexType::IvfFlat); + assert_eq!(indices[0].columns, vec!["vec".to_string()]); + let stats = view + .table() + .index_stats(&index_name) + .await + .unwrap() + .unwrap(); + assert_eq!(stats.num_unindexed_rows, 0); + + source + .update() + .column("id", "id + 1000") + .execute() + .await + .unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, Some(RefreshMode::Rebuild)); + assert_eq!(result.rows_written, Some(256)); + + let indices = view.table().list_indices().await.unwrap(); + assert_eq!(indices.len(), 1, "the rebuild dropped the vector index"); + assert_eq!(indices[0].name, index_name); + assert_eq!(indices[0].index_type, IndexType::IvfFlat); + assert_eq!(indices[0].columns, vec!["vec".to_string()]); + + // The definition survives, but the retained index covers none of the + // replacement rows until it is rebuilt. + let stats = view + .table() + .index_stats(&index_name) + .await + .unwrap() + .unwrap(); + assert_eq!(stats.num_unindexed_rows, 256); + + let batches = view + .table() + .query() + .nearest_to(vec![0.0f32; 4]) + .unwrap() + .limit(5) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut ids = Vec::new(); + for batch in &batches { + ids.extend( + batch["id"] + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied(), + ); + } + assert_eq!(ids, vec![1000, 1001, 1002, 1003, 1004]); + } + #[tokio::test] #[cfg_attr( not(feature = "experimental-functions"), diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 2cff72fc5..13b8debf4 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -17,12 +17,15 @@ use arrow_schema::{DataType, SchemaRef}; use datafusion_common::{DataFusionError, Result as DataFusionResult}; use datafusion_execution::TaskContext; use datafusion_expr::{Expr, col, lit}; -use datafusion_physical_expr::{EquivalenceProperties, Partitioning}; +use datafusion_physical_expr::{ + EquivalenceProperties, Partitioning, expressions::col as physical_col, +}; use datafusion_physical_plan::{ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, coalesce_partitions::CoalescePartitionsExec, execution_plan::{Boundedness, EmissionType}, limit::GlobalLimitExec, + projection::ProjectionExec, stream::RecordBatchStreamAdapter, }; use futures::{FutureExt, StreamExt, TryFutureExt, TryStreamExt, stream, try_join}; @@ -444,8 +447,8 @@ pub trait QueryBase { /// # } /// ``` /// - /// Note: Expression filters are not supported for LanceDB Distributed queries. - /// Use [`QueryBase::only_if`] with SQL strings in LanceDB Distributed. + /// Note: Expression filters are not supported for LanceDB Enterprise queries. + /// Use [`QueryBase::only_if`] with SQL strings in LanceDB Enterprise. /// /// Calling this multiple times combines the expressions with a logical AND /// rather than replacing the previous filter. @@ -658,6 +661,10 @@ pub struct QueryExecutionOptions { /// By default, this is 1024 pub max_batch_length: u32, /// Max duration to wait for the query to execute before timing out. + /// + /// The timeout also covers reading the results, so a caller that consumes + /// the stream slowly can exceed it. For a remote table it counts from when + /// the query is sent, and the server is given the same timeout. pub timeout: Option, /// How distributed worker metrics should be displayed by /// [`ExecutableQuery::analyze_plan`]. @@ -744,6 +751,11 @@ pub trait ExecutableQuery { /// stream is consumed slowly (this constrains the maximum memory used by a /// single query. /// + /// A remote table decodes batches as they arrive when the server streams + /// query results. If the response stops partway, the stream ends with + /// `Error::ResponseInterrupted`. The batches already returned are valid but + /// incomplete, and the query is not retried. + /// /// For simpler access or row-based access we recommend creating extension traits /// to convert Arrow data into your internal data model. fn execute_with_options( @@ -850,6 +862,11 @@ pub struct QueryRequest { #[doc(hidden)] pub take_offsets: Option>, + /// Row IDs whose requested order and multiplicity are restored after lookup. + /// This is client-side metadata, not part of the remote query protocol. + #[doc(hidden)] + pub take_row_ids: Option>, + /// Apply filter to the returned rows. pub filter: Option, @@ -919,6 +936,7 @@ impl Default for QueryRequest { limit: None, offset: None, take_offsets: None, + take_row_ids: None, filter: None, filter_error: None, full_text_search: None, @@ -936,6 +954,10 @@ impl Default for QueryRequest { } impl QueryRequest { + pub(crate) fn has_take(&self) -> bool { + self.take_offsets.is_some() || self.take_row_ids.is_some() + } + /// Add a filter, combining it with any existing filter using a logical AND. /// /// If the new filter cannot be combined with the existing one (because they @@ -1025,7 +1047,7 @@ impl Query { /// By default, there is no embedding model, and the input should be /// vector/slice of floats. /// NaN and infinite components are rejected with [`Error::InvalidInput`] - /// after conversion to Float32, in both LanceDB Embedded and LanceDB Distributed. + /// after conversion to Float32, in both LanceDB Embedded and LanceDB Enterprise. /// /// If there is only one vector column (a column whose data type is a /// fixed size list of floats) then the column does not need to be specified. @@ -1269,7 +1291,7 @@ impl VectorQuery { /// result. /// /// NaN and infinite components are rejected with [`Error::InvalidInput`] - /// after conversion to Float32, in both LanceDB Embedded and LanceDB Distributed. + /// after conversion to Float32, in both LanceDB Embedded and LanceDB Enterprise. pub fn add_query_vector(mut self, vector: impl IntoQueryVector) -> Result { self.request.add_query_vector(vector)?; Ok(self) @@ -1316,7 +1338,11 @@ impl VectorQuery { /// /// None (the default) resolves to 0.5, preserving Auto probing. At 0 the /// search starts at the caller minimum; at 1 it searches all partitions - /// within the caller maximum. Intermediate values interpolate around Auto. + /// within the caller maximum. Efforts 0.1 and 0.25 target empirical mean + /// partition-routing recall of 80% and 90%, respectively, for L2, cosine + /// and dot with k up to 100,000. The budget adapts to the metric and k; + /// this is a calibration boundary, not a limit on k. Hamming and larger k + /// retain uncalibrated behavior. Other values interpolate between tiers. /// Later probing may continue when too few candidates are found. /// Any explicit value, including 0.5, overrides [`Self::nprobes`] regardless /// of setter order. Explicit minimum and maximum bounds still apply. @@ -1476,8 +1502,10 @@ impl VectorQuery { /// Set the speed / accuracy tradeoff for approximate vector search. /// - /// This setting is currently only used by RQ-quantized indexes, such as - /// IVF_RQ. Other index types ignore this setting. + /// This setting is currently used by RQ-quantized indexes (such as IVF_RQ) + /// and by prefiltered search on HNSW sub-indexes, where + /// [`ApproxMode::Fast`] enables the ACORN traversal. Other index types + /// ignore this setting. pub fn approx_mode(mut self, approx_mode: ApproxMode) -> Self { self.request.approx_mode = Some(approx_mode); self @@ -1674,42 +1702,42 @@ impl HasQuery for VectorQuery { } } -fn take_occurrences(offsets: &[u64]) -> HashMap { - let mut occurrences = HashMap::with_capacity(offsets.len()); - for offset in offsets { - *occurrences.entry(*offset).or_insert(0) += 1; +fn take_occurrences(indices: &[u64]) -> HashMap { + let mut occurrences = HashMap::with_capacity(indices.len()); + for index in indices { + *occurrences.entry(*index).or_insert(0) += 1; } occurrences } fn restore_take_batch_with_occurrences( batch: RecordBatch, - offsets: &[u64], + indices: &[u64], occurrences: &HashMap, ordering_column: &str, drop_ordering_column: bool, preserve_order: bool, ) -> Result { - let actual_offsets = batch + let actual_indices = batch .column_by_name(ordering_column) .ok_or_else(|| Error::Schema { message: format!( "take query result did not include ordering column '{ordering_column}'" ), })?; - let actual_offsets = match actual_offsets.data_type() { - DataType::UInt64 => actual_offsets + let actual_indices = match actual_indices.data_type() { + DataType::UInt64 => actual_indices .as_primitive::() .values() .to_vec(), - DataType::Int64 => actual_offsets + DataType::Int64 => actual_indices .as_primitive::() .values() .iter() - .map(|offset| { - u64::try_from(*offset).map_err(|_| Error::Schema { + .map(|index| { + u64::try_from(*index).map_err(|_| Error::Schema { message: format!( - "take query ordering column '{ordering_column}' contained a negative offset" + "take query ordering column '{ordering_column}' contained a negative index" ), }) }) @@ -1723,26 +1751,26 @@ fn restore_take_batch_with_occurrences( } }; - let mut desired_order = Vec::with_capacity(offsets.len()); + let mut desired_order = Vec::with_capacity(indices.len()); if preserve_order { - let ordering = actual_offsets + let ordering = actual_indices .iter() .copied() .enumerate() - .map(|(index, offset)| (offset, index as u64)) + .map(|(position, index)| (index, position as u64)) .collect::>(); - // Missing offsets retain the filter-based behavior of returning no row. + // Missing indices retain the filter-based behavior of returning no row. desired_order.extend( - offsets + indices .iter() - .filter_map(|offset| ordering.get(offset).copied()), + .filter_map(|index| ordering.get(index).copied()), ); } else { - // Public take queries do not guarantee output order. Preserve the lookup's - // existing order and only restore the multiplicity of each matching row. - for (index, offset) in actual_offsets.iter().enumerate() { - if let Some(count) = occurrences.get(offset) { - desired_order.extend(std::iter::repeat_n(index as u64, *count)); + // Unordered offset takes and explicitly sorted queries retain the lookup's + // order while restoring the multiplicity of each matching row. + for (position, index) in actual_indices.iter().enumerate() { + if let Some(count) = occurrences.get(index) { + desired_order.extend(std::iter::repeat_n(position as u64, *count)); } } } @@ -1759,7 +1787,15 @@ fn restore_take_batch_with_occurrences( }; if drop_ordering_column { - ordered_batch = ordered_batch.drop_column(ordering_column)?; + // Project preserves the row count even when no user columns were selected. + let columns = ordered_batch + .schema() + .fields() + .iter() + .enumerate() + .filter_map(|(i, field)| (field.name() != ordering_column).then_some(i)) + .collect::>(); + ordered_batch = ordered_batch.project(&columns)?; } Ok(ordered_batch) @@ -1768,32 +1804,32 @@ fn restore_take_batch_with_occurrences( #[cfg(test)] fn restore_take_batch( batch: RecordBatch, - offsets: &[u64], + indices: &[u64], ordering_column: &str, drop_ordering_column: bool, preserve_order: bool, ) -> Result { restore_take_batch_with_occurrences( batch, - offsets, - &take_occurrences(offsets), + indices, + &take_occurrences(indices), ordering_column, drop_ordering_column, preserve_order, ) } -/// Restores the logical offset occurrence sequence above the physical lookup plan. +/// Restores the logical index occurrence sequence above the physical lookup plan. /// /// The lookup plan returns each matching row at most once. For ordinary unordered /// takes this operator expands each input batch incrementally and preserves the -/// lookup's partitioning. The explicitly ordered reader path collects one coalesced +/// lookup's partitioning. Ordered takes collect one coalesced /// input before restoring requested order. Pagination must remain above this operator /// so it applies to occurrences. #[derive(Debug)] struct TakeRestoreExec { input: Arc, - offsets: Vec, + indices: Vec, occurrences: Arc>, ordering_column: String, drop_ordering_column: bool, @@ -1805,15 +1841,20 @@ struct TakeRestoreExec { impl TakeRestoreExec { fn try_new( input: Arc, - offsets: Vec, + indices: Vec, ordering_column: String, drop_ordering_column: bool, preserve_order: bool, ) -> Result { let schema = if drop_ordering_column { - RecordBatch::new_empty(input.schema()) - .drop_column(&ordering_column)? - .schema() + let schema = input.schema(); + let columns = schema + .fields() + .iter() + .enumerate() + .filter_map(|(i, field)| (field.name() != &ordering_column).then_some(i)) + .collect::>(); + Arc::new(schema.project(&columns)?) } else { input.schema() }; @@ -1836,8 +1877,8 @@ impl TakeRestoreExec { Ok(Self { input, - occurrences: Arc::new(take_occurrences(&offsets)), - offsets, + occurrences: Arc::new(take_occurrences(&indices)), + indices, ordering_column, drop_ordering_column, preserve_order, @@ -1856,7 +1897,7 @@ impl DisplayAs for TakeRestoreExec { write!( formatter, "TakeRestoreExec: occurrences={}", - self.offsets.len() + self.indices.len() ) } } @@ -1905,7 +1946,7 @@ impl ExecutionPlan for TakeRestoreExec { let child = children.into_iter().next().unwrap(); let plan = Self::try_new( child, - self.offsets.clone(), + self.indices.clone(), self.ordering_column.clone(), self.drop_ordering_column, self.preserve_order, @@ -1928,7 +1969,7 @@ impl ExecutionPlan for TakeRestoreExec { let input = self.input.execute(partition, context)?; let output_schema = self.schema.clone(); - let offsets = self.offsets.clone(); + let indices = self.indices.clone(); let occurrences = self.occurrences.clone(); let ordering_column = self.ordering_column.clone(); let drop_ordering_column = self.drop_ordering_column; @@ -1945,7 +1986,7 @@ impl ExecutionPlan for TakeRestoreExec { }; restore_take_batch_with_occurrences( batch, - &offsets, + &indices, &occurrences, &ordering_column, drop_ordering_column, @@ -1958,7 +1999,7 @@ impl ExecutionPlan for TakeRestoreExec { batch.and_then(|batch| { restore_take_batch_with_occurrences( batch, - &offsets, + &indices, &occurrences, &ordering_column, drop_ordering_column, @@ -1996,10 +2037,20 @@ impl ExecutionPlan for TakeRestoreExec { pub struct TakeQuery { parent: Arc, request: QueryRequest, - offsets: Option>, preserve_order: bool, } +struct TakeLookup { + request: QueryRequest, + indices: Vec, + ordering_column: String, + drop_ordering_column: bool, + output_offset: usize, + output_limit: Option, + preserve_order: bool, + output_projection: Option>, +} + impl TakeQuery { /// Create a new `TakeQuery` that will return rows at the given offsets. /// @@ -2018,10 +2069,9 @@ impl TakeQuery { filter: Some(QueryFilter::Datafusion( col("_rowoffset").in_list(in_list, false), )), - take_offsets: Some(offsets.clone()), + take_offsets: Some(offsets), ..Default::default() }, - offsets: Some(offsets), preserve_order: false, } } @@ -2030,14 +2080,20 @@ impl TakeQuery { /// /// See [`crate::Table::take_row_ids`] for more details. pub fn from_row_ids(parent: Arc, row_ids: Vec) -> Self { - let in_list: Vec = row_ids.iter().map(|id| lit(*id)).collect(); + let mut seen = HashSet::with_capacity(row_ids.len()); + let in_list = row_ids + .iter() + .copied() + .filter(|id| seen.insert(*id)) + .map(lit) + .collect(); Self { parent, request: QueryRequest { filter: Some(QueryFilter::Datafusion(col(ROW_ID).in_list(in_list, false))), + take_row_ids: Some(row_ids), ..Default::default() }, - offsets: None, preserve_order: false, } } @@ -2046,7 +2102,7 @@ impl TakeQuery { /// /// This is reserved for readers whose API explicitly guarantees ordering. pub(crate) fn preserve_order(mut self) -> Self { - debug_assert!(self.offsets.is_some()); + debug_assert!(self.request.take_offsets.is_some()); self.preserve_order = true; self } @@ -2104,29 +2160,124 @@ impl TakeQuery { Ok((request, ordering_column, drop_ordering_column)) } - async fn prepare_offsets_lookup( + async fn prepare_take_lookup( parent: &dyn BaseTable, request: &QueryRequest, - ) -> Result<(QueryRequest, String, bool, usize, Option)> { - let (mut request, ordering_column, drop_ordering_column) = - Self::request_with_row_offset(parent, request).await?; + preserve_order: bool, + ) -> Result { + let (indices, by_row_id) = match (&request.take_offsets, &request.take_row_ids) { + (Some(indices), None) => (indices.clone(), false), + (None, Some(indices)) => (indices.clone(), true), + _ => { + return Err(Error::InvalidInput { + message: "take lookup requires exactly one of take_offsets or take_row_ids" + .to_string(), + }); + } + }; + let preserve_order = + preserve_order || (by_row_id && request.order_by.as_ref().is_none_or(Vec::is_empty)); + let (mut request, ordering_column, drop_ordering_column, output_projection) = if by_row_id { + let mut request = request.clone(); + let with_row_id = request.with_row_id; + let mut names = match &request.select { + Select::All => None, + Select::Columns(names) => Some(names.clone()), + Select::Dynamic(pairs) => { + Some(pairs.iter().map(|(name, _)| name.clone()).collect()) + } + Select::Expr(pairs) => Some(pairs.iter().map(|(name, _)| name.clone()).collect()), + }; + let selected_row_id = names + .as_ref() + .is_some_and(|names| names.iter().any(|name| name == ROW_ID)); + // with_row_id appends the metadata column, but Lance leaves an + // existing projection alias named _rowid untouched. Rename that + // alias during lookup so it cannot be mistaken for the real ID. + let alias = if selected_row_id + && matches!(request.select, Select::Dynamic(_) | Select::Expr(_)) + { + let mut alias = "__lancedb_take_row_id".to_string(); + while names.as_ref().is_some_and(|names| names.contains(&alias)) { + alias.push('_'); + } + Some(alias) + } else { + None + }; + match &mut request.select { + // Remote tables expose metadata through with_row_id, not + // through the ordinary selected-column list. + Select::Columns(columns) => columns.retain(|name| name != ROW_ID), + Select::Dynamic(pairs) => { + if let Some(alias) = &alias { + for (name, _) in pairs.iter_mut().filter(|(name, _)| name == ROW_ID) { + *name = alias.clone(); + } + } + } + Select::Expr(pairs) => { + if let Some(alias) = &alias { + for (name, _) in pairs.iter_mut().filter(|(name, _)| name == ROW_ID) { + *name = alias.clone(); + } + } + } + Select::All => {} + } + if with_row_id && let Some(names) = &mut names { + if let Some(position) = names.iter().position(|name| name == ROW_ID) { + names.remove(position); + } + names.push(ROW_ID.to_string()); + } + let output_projection = if selected_row_id { + names.map(|names| { + names + .into_iter() + .map(|name| { + let input_name = if name == ROW_ID { + alias.as_ref().unwrap_or(&name).clone() + } else { + name.clone() + }; + (input_name, name) + }) + .collect() + }) + } else { + None + }; + let drop_row_id = alias.is_some() || (!with_row_id && !selected_row_id); + request.with_row_id = true; + (request, ROW_ID.to_string(), drop_row_id, output_projection) + } else { + let (request, column, drop_column) = + Self::request_with_row_offset(parent, request).await?; + (request, column, drop_column, None) + }; + request.take_offsets = None; + request.take_row_ids = None; // The lookup operates on distinct physical rows. Pagination is a logical // operation over occurrences and must be applied only after restoration. let output_offset = request.offset.take().unwrap_or_default(); let output_limit = request.limit.take(); - Ok(( + Ok(TakeLookup { request, + indices, ordering_column, drop_ordering_column, output_offset, output_limit, - )) + preserve_order, + output_projection, + }) } - fn wrap_offsets_plan( + fn wrap_take_plan( lookup: Arc, - offsets: &[u64], + indices: &[u64], ordering_column: String, drop_ordering_column: bool, output_offset: usize, @@ -2140,7 +2291,7 @@ impl TakeQuery { }; let restored: Arc = Arc::new(TakeRestoreExec::try_new( lookup, - offsets.to_vec(), + indices.to_vec(), ordering_column, drop_ordering_column, preserve_order, @@ -2157,7 +2308,7 @@ impl TakeQuery { } } - fn wrap_offsets_explanation( + fn wrap_take_explanation( lookup: &str, occurrence_count: usize, output_offset: usize, @@ -2197,21 +2348,6 @@ impl TakeQuery { } } - async fn create_offsets_plan( - &self, - offsets: &[u64], - options: QueryExecutionOptions, - ) -> Result> { - create_take_offsets_plan( - self.parent.as_ref(), - &self.request, - offsets, - options, - self.preserve_order, - ) - .await - } - /// Convert the `TakeQuery` into a `QueryRequest`. pub fn into_request(self) -> QueryRequest { self.request @@ -2256,15 +2392,22 @@ impl TakeQuery { } } -pub(crate) async fn create_take_offsets_plan( +pub(crate) async fn create_take_plan( parent: &dyn BaseTable, request: &QueryRequest, - offsets: &[u64], options: QueryExecutionOptions, preserve_order: bool, ) -> Result> { - let (request, ordering_column, drop_ordering_column, output_offset, output_limit) = - TakeQuery::prepare_offsets_lookup(parent, request).await?; + let TakeLookup { + request, + indices, + ordering_column, + drop_ordering_column, + output_offset, + output_limit, + preserve_order, + output_projection, + } = TakeQuery::prepare_take_lookup(parent, request, preserve_order).await?; let lookup_options = if preserve_order { options.without_output_batch_length_limit() } else { @@ -2274,43 +2417,73 @@ pub(crate) async fn create_take_offsets_plan( .create_plan(&AnyQuery::Query(request), lookup_options) .await?; - TakeQuery::wrap_offsets_plan( + let plan = TakeQuery::wrap_take_plan( lookup, - offsets, + &indices, ordering_column, drop_ordering_column, output_offset, output_limit, preserve_order, - ) + )?; + if let Some(projection) = output_projection { + let schema = plan.schema(); + let expressions = projection + .into_iter() + .map(|(input, output)| Ok((physical_col(&input, &schema)?, output))) + .collect::>>()?; + Ok(Arc::new(ProjectionExec::try_new(expressions, plan)?)) + } else { + Ok(plan) + } } -pub(crate) async fn explain_take_offsets_plan( +pub(crate) async fn explain_take_plan( parent: &dyn BaseTable, request: &QueryRequest, - offsets: &[u64], verbose: bool, + preserve_order: bool, ) -> Result { - let (request, _, _, output_offset, output_limit) = - TakeQuery::prepare_offsets_lookup(parent, request).await?; + let TakeLookup { + request, + indices, + output_offset, + output_limit, + preserve_order, + output_projection, + .. + } = TakeQuery::prepare_take_lookup(parent, request, preserve_order).await?; let lookup = parent .explain_plan(&AnyQuery::Query(request), verbose) .await?; - Ok(TakeQuery::wrap_offsets_explanation( + let explanation = TakeQuery::wrap_take_explanation( &lookup, - offsets.len(), + indices.len(), output_offset, output_limit, - false, - )) + preserve_order, + ); + if output_projection.is_some() { + Ok(format!( + "ProjectionExec\n{}", + explanation + .lines() + .map(|line| format!(" {line}")) + .collect::>() + .join("\n") + )) + } else { + Ok(explanation) + } } -pub(crate) async fn prepare_take_offsets_request( +pub(crate) async fn prepare_take_request( parent: &dyn BaseTable, request: &QueryRequest, ) -> Result { - let (request, _, _, _, _) = TakeQuery::prepare_offsets_lookup(parent, request).await?; - Ok(request) + Ok(TakeQuery::prepare_take_lookup(parent, request, false) + .await? + .request) } impl HasQuery for TakeQuery { @@ -2321,8 +2494,14 @@ impl HasQuery for TakeQuery { impl ExecutableQuery for TakeQuery { async fn create_plan(&self, options: QueryExecutionOptions) -> Result> { - if let Some(offsets) = &self.offsets { - return self.create_offsets_plan(offsets, options).await; + if self.request.has_take() { + return create_take_plan( + self.parent.as_ref(), + &self.request, + options, + self.preserve_order, + ) + .await; } let req = AnyQuery::Query(self.request.clone()); @@ -2333,7 +2512,7 @@ impl ExecutableQuery for TakeQuery { &self, options: QueryExecutionOptions, ) -> Result { - if self.offsets.is_some() { + if self.request.has_take() { let plan = self.create_plan(options.clone()).await?; let inner = execute_plan(plan, Default::default())?; let inner = MaxBatchLengthStream::new_boxed(inner, options.max_batch_length as usize); @@ -2352,23 +2531,14 @@ impl ExecutableQuery for TakeQuery { } async fn explain_plan(&self, verbose: bool) -> Result { - if let Some(offsets) = &self.offsets { - let (request, _, _, output_offset, output_limit) = - Self::prepare_offsets_lookup(self.parent.as_ref(), &self.request).await?; - // Ask the backend to explain only the distinct-row lookup. This keeps - // remote explanation non-executing while still showing the client-side - // operators that create_plan and execution place above that lookup. - let lookup = self - .parent - .explain_plan(&AnyQuery::Query(request), verbose) - .await?; - return Ok(Self::wrap_offsets_explanation( - &lookup, - offsets.len(), - output_offset, - output_limit, + if self.request.has_take() { + return explain_take_plan( + self.parent.as_ref(), + &self.request, + verbose, self.preserve_order, - )); + ) + .await; } let query = AnyQuery::Query(self.request.clone()); @@ -2376,10 +2546,9 @@ impl ExecutableQuery for TakeQuery { } async fn analyze_plan_with_options(&self, options: QueryExecutionOptions) -> Result { - if self.offsets.is_some() { + if self.request.has_take() { if self.parent.analyze_plan_is_remote() { - let (request, _, _, _, _) = - Self::prepare_offsets_lookup(self.parent.as_ref(), &self.request).await?; + let request = prepare_take_request(self.parent.as_ref(), &self.request).await?; // Remote analysis is owned by the service. The current wire // request represents only the distinct-row lookup, so return // the service report unchanged instead of fabricating metrics @@ -3720,10 +3889,13 @@ mod tests { let texts = texts.iter().map(|e| e.unwrap()).collect::>(); assert!(texts.contains("cat")); // should be close by vector search assert!(texts.contains("b")); // should be close by fts search + // Both rows rank first in one of the two search results. + let scores = batch["_relevance_score"].as_primitive::(); + assert_eq!(scores.values().as_ref(), &[1.0 / 61.0, 1.0 / 61.0]); // ensure that this works correctly if there are no matching FTS results let fts_query = FullTextSearchQuery::new("z".to_string()); - table + let results = table .query() .full_text_search(fts_query) .limit(2) @@ -3735,6 +3907,12 @@ mod tests { .try_collect::>() .await .unwrap(); + let batch = &results[0]; + let texts = batch["text"].as_string::(); + assert_eq!(texts.value(0), "cat"); + assert_eq!(texts.value(1), "dog"); + let scores = batch["_relevance_score"].as_primitive::(); + assert_eq!(scores.values().as_ref(), &[1.0 / 61.0, 1.0 / 62.0]); } #[tokio::test] @@ -4183,13 +4361,17 @@ mod tests { assert!(!analyzed.contains("CoalescePartitionsExec")); } + #[rstest::rstest] + #[case::unsorted(vec![5, 1, 17], vec![5, 1, 17])] + #[case::duplicate_and_missing(vec![17, 5, 17, u64::MAX, 1], vec![17, 5, 17, 1])] + #[case::empty(vec![], vec![])] #[tokio::test] - async fn test_take_row_ids() { + async fn test_take_row_ids(#[case] requested: Vec, #[case] expected: Vec) { let tmp_dir = tempdir().unwrap(); let table = make_test_table(&tmp_dir).await; let results = table - .take_row_ids(vec![5, 1, 17]) + .take_row_ids(requested) .execute() .await .unwrap() @@ -4198,18 +4380,226 @@ mod tests { .unwrap(); assert_eq!(results.len(), 1); - assert_eq!(results[0].num_rows(), 3); + assert_eq!(results[0].num_rows(), expected.len()); assert_eq!(results[0].num_columns(), 2); - let mut ids = results[0] + let ids = results[0] .column_by_name("id") .unwrap() .as_primitive::() .values() .to_vec(); - ids.sort(); + assert_eq!(ids, expected); + } - assert_eq!(ids, vec![1, 5, 17]); + #[rstest::rstest] + #[case::stable(true)] + #[case::physical(false)] + #[tokio::test] + async fn test_take_row_ids_deleted_and_pagination(#[case] stable: bool) { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = arrow_array::record_batch!( + ("id", Int32, [0, 1, 2, 3]), + ("label", Utf8, ["a", "b", "c", "d"]) + ) + .unwrap(); + let table = conn + .create_table("rows", vec![batch]) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(lance::dataset::WriteParams { + max_rows_per_file: 2, + max_rows_per_group: 2, + enable_stable_row_ids: stable, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let batches = table + .query() + .select(Select::columns(&["id"])) + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let batch = concat_batches(&batches[0].schema(), &batches).unwrap(); + let row_ids: HashMap<_, _> = batch["id"] + .as_primitive::() + .values() + .iter() + .copied() + .zip( + batch[ROW_ID] + .as_primitive::() + .values() + .iter() + .copied(), + ) + .collect(); + table.delete("id = 1").await.unwrap(); + let take = table + .take_row_ids(vec![ + row_ids[&3], + row_ids[&1], + row_ids[&3], + u64::MAX, + row_ids[&0], + ]) + .select(Select::columns(&["label"])) + .with_row_id() + .offset(1) + .limit(2); + let batches = take + .execute_with_options(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert!(batches.iter().all(|batch| batch.num_rows() <= 1)); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["label"] + .as_string::() + .iter() + .collect::>(), + vec![Some("d"), Some("a")] + ); + assert_eq!( + actual[ROW_ID] + .as_primitive::() + .values() + .as_ref(), + &[row_ids[&3], row_ids[&0]] + ); + let request = take.clone().into_request(); + let direct = table + .base_table() + .query(&AnyQuery::Query(request), QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + concat_batches(&direct[0].schema(), &direct).unwrap(), + actual + ); + let plan = take + .create_plan(QueryExecutionOptions::default()) + .await + .unwrap(); + let planned = execute_plan(plan, Default::default()) + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + concat_batches(&planned[0].schema(), &planned).unwrap(), + actual + ); + } + + #[rstest::rstest] + #[case::empty(Select::Columns(vec![]), vec![], vec![])] + #[case::explicit_row_id(Select::columns(&[ROW_ID, "id"]), vec![ROW_ID, "id"], vec![5, 1, 17])] + #[case::dynamic_alias(Select::dynamic(&[(ROW_ID, "20 - id"), ("__lancedb_take_row_id", "id")]), vec![ROW_ID, "__lancedb_take_row_id"], vec![15, 19, 3])] + #[case::expr_alias(Select::expr_projection(&[(ROW_ID, lit(20) - col("id"))]), vec![ROW_ID], vec![15, 19, 3])] + #[tokio::test] + async fn test_take_row_ids_projection( + #[case] selection: Select, + #[case] names: Vec<&str>, + #[case] values: Vec, + #[values(false, true)] with_row_id: bool, + #[values(false, true)] order_by: bool, + ) { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let mut take = table.take_row_ids(vec![5, 1, 17]).select(selection); + if with_row_id { + take = take.with_row_id(); + } + if order_by { + take = take.order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "id".to_string(), + )])); + } + let batches = take + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!(actual.num_rows(), 3); + let mut expected_names = names.clone(); + if with_row_id { + expected_names.retain(|name| *name != ROW_ID); + expected_names.push(ROW_ID); + } + assert_eq!( + actual + .schema() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>(), + expected_names + ); + if !values.is_empty() { + let row_ids = actual.column_by_name(ROW_ID).unwrap(); + if row_ids.data_type() == &DataType::UInt64 { + assert_eq!( + row_ids.as_primitive::().values().as_ref(), + if order_by { &[1, 5, 17] } else { &[5, 1, 17] } + ); + } else { + let mut expected = values; + if order_by { + expected.swap(0, 1); + } + assert_eq!( + row_ids.as_primitive::().values().as_ref(), + expected.as_slice() + ); + } + } + } + + #[tokio::test] + async fn test_take_row_ids_explicit_order_by() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let batches = table + .take_row_ids(vec![17, 5, 1, 5]) + .order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "id".to_string(), + )])) + .offset(1) + .limit(2) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["id"].as_primitive::().values().as_ref(), + &[5, 5] + ); } } diff --git a/rust/lancedb/src/remote.rs b/rust/lancedb/src/remote.rs index 5abe4dcf7..dc8431638 100644 --- a/rust/lancedb/src/remote.rs +++ b/rust/lancedb/src/remote.rs @@ -14,6 +14,7 @@ pub(crate) mod job; pub mod oauth; mod retry; pub(crate) mod sql; +mod storage_integration; pub(crate) mod table; pub(crate) mod token_cache; pub(crate) mod util; @@ -35,7 +36,8 @@ fn extract_job_id(body: &str) -> Option { pub use client::{ClientConfig, HeaderProvider, RetryConfig, TimeoutConfig, TlsConfig}; pub use db::{RemoteDatabaseOptions, RemoteDatabaseOptionsBuilder}; pub use oauth::{ - AuthorizationCodeOptions, ClientAuthMethod, OAuthConfig, OAuthFlow, OAuthHeaderProvider, + AuthorizationCodeOptions, ClientAuthMethod, DeviceCodeOptions, OAuthConfig, OAuthFlow, + OAuthHeaderProvider, }; pub use token_cache::{OAuthSession, SessionLogout, SessionStatus, TokenCacheOptions}; diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index ae4c1aaa5..e0722bfbc 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -10,7 +10,7 @@ use reqwest::{ use std::{collections::HashMap, future::Future, str::FromStr, sync::Arc, time::Duration}; use tokio::sync::Semaphore; -use crate::error::{Error, Result}; +use crate::error::{Error, HttpErrorSource, RemoteErrorMetadata, Result}; use crate::remote::db::RemoteOptions; use crate::remote::retry::{ResolvedRetryConfig, RetryCounter}; use crate::utils::validate_database_name; @@ -824,6 +824,11 @@ impl RestfulLanceDbClient { self.client.post(full_uri) } + pub fn put(&self, uri: &str) -> RequestBuilder { + let full_uri = format!("{}{}", self.host, uri); + self.client.put(full_uri) + } + /// Apply dynamic headers from the header provider if configured pub(crate) async fn apply_dynamic_headers(&self, mut request: Request) -> Result { if let Some(ref provider) = self.header_provider { @@ -952,6 +957,11 @@ impl RestfulLanceDbClient { .check_response(&retry_counter.request_id, response) .await .unwrap_err(); + // A structured resource error is a domain result, not a + // transient failure. Retrying it would hide the typed error. + if source.http_error_details().is_some() { + return Err(source); + } retry_counter.increment_request_failures(source)?; } Err(err) if err.is_connect() => { @@ -1027,14 +1037,18 @@ impl RestfulLanceDbClient { if status.is_success() { Ok(response) } else { + let metadata = RemoteErrorMetadata::from_headers(response.headers()); let response_text = response.text().await.ok(); - let message = if let Some(response_text) = response_text { - format!("{}: {}", status, response_text) - } else { - status.to_string() + let source = match response_text { + Some(response_text) => HttpErrorSource::new( + format!("{}: {}", status, response_text), + Some(&response_text), + metadata, + ), + None => HttpErrorSource::new(status.to_string(), None, metadata), }; Err(Error::Http { - source: message.into(), + source: Box::new(source), request_id: request_id.into(), status_code: Some(status), }) @@ -1210,6 +1224,120 @@ pub mod test_utils { #[cfg(test)] mod tests { + #[tokio::test] + async fn check_response_extracts_structured_resource_error() { + use crate::remote::client::test_utils::client_with_handler; + + let client = + client_with_handler(|_| http::Response::builder().status(404).body("").unwrap()); + let cases = [ + (404, "not_found", "secret", "openai"), + (404, "not_found", "function", "embed"), + (404, "not_found", "namespace", "child"), + (409, "already_exists", "namespace", "analytics"), + ]; + + for (status, error_code, resource_kind, resource_name) in cases { + let body = serde_json::json!({ + "code": if error_code == "not_found" { 5 } else { 6 }, + "error": format!("{resource_kind} {resource_name} error"), + "error_code": error_code, + "resource": { + "kind": resource_kind, + "name": resource_name, + "namespace_path": ["analytics"], + }, + }) + .to_string(); + let response = http::Response::builder() + .status(status) + .body(body.clone()) + .unwrap() + .into(); + + let error = client + .check_response("request-1", response) + .await + .unwrap_err(); + let details = error + .http_error_details() + .expect("structured HTTP error details"); + assert_eq!(details.error_code, error_code); + assert_eq!(details.resource_kind, resource_kind); + assert_eq!(details.resource_name, resource_name); + assert_eq!(details.namespace_path, ["analytics"]); + assert!(error.to_string().contains(&body)); + } + } + + #[tokio::test] + async fn check_response_keeps_legacy_body_as_generic_http_error() { + use crate::remote::client::test_utils::client_with_handler; + + let client = + client_with_handler(|_| http::Response::builder().status(404).body("").unwrap()); + let body = serde_json::json!({ + "code": 4, + "error": "Not found: Secret \"openai\" does not exist", + }) + .to_string(); + let response = http::Response::builder() + .status(404) + .body(body.clone()) + .unwrap() + .into(); + + let error = client + .check_response("request-1", response) + .await + .unwrap_err(); + assert!(error.http_error_details().is_none()); + assert!(error.to_string().contains(&body)); + } + + #[tokio::test] + async fn send_with_retry_does_not_retry_structured_resource_error() { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use crate::remote::client::test_utils::client_with_handler; + + let attempts = Arc::new(AtomicUsize::new(0)); + let handler_attempts = Arc::clone(&attempts); + let client = client_with_handler(move |_| { + handler_attempts.fetch_add(1, Ordering::Relaxed); + http::Response::builder() + .status(409) + .body( + serde_json::json!({ + "code": 6, + "error": "already exists", + "error_code": "already_exists", + "resource": { + "kind": "namespace", + "name": "analytics", + "namespace_path": [], + }, + }) + .to_string(), + ) + .unwrap() + }); + + let request = client.client.post("http://localhost/"); + let error = client + .send_with_retry(request, None, true) + .await + .unwrap_err(); + + assert_eq!(attempts.load(Ordering::Relaxed), 1); + let details = error + .http_error_details() + .expect("structured HTTP error details"); + assert_eq!(details.error_code, "already_exists"); + assert_eq!(details.resource_kind, "namespace"); + } + #[tokio::test] async fn test_http_timeout_error_is_actionable() { use super::*; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 5c85d0792..c33c7267d 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use crate::storage_integration::{CreateStorageIntegrationRequest, StorageIntegrationInfo}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -14,8 +15,8 @@ use reqwest::header::CONTENT_TYPE; use lance_namespace::models::{ CreateNamespaceRequest, CreateNamespaceResponse, DescribeNamespaceRequest, - DescribeNamespaceResponse, DropNamespaceRequest, DropNamespaceResponse, JsonArrowSchema, - ListNamespacesRequest, ListNamespacesResponse, ListTablesRequest, ListTablesResponse, + DescribeNamespaceResponse, DropNamespaceRequest, DropNamespaceResponse, ListNamespacesRequest, + ListNamespacesResponse, ListTablesRequest, ListTablesResponse, }; use crate::Error; @@ -24,21 +25,18 @@ use crate::database::{ ExecuteQueryRequest, JobInfo, OpenTableRequest, ReadConsistency, TableNamesRequest, }; use crate::error::Result; -use crate::function::{ - FunctionArtifactRequest, FunctionRegistrationRequest, FunctionSignature, FunctionVersion, - PythonRuntimeSpec, -}; +use crate::function::{FunctionRegistrationRequest, FunctionVersion, GpuClass}; +use crate::graph::{PropertyGraphDefinition, PropertyGraphDescription}; use crate::job::Job; use crate::listing::{ListingOptions, ListingPage}; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::job::{PauseJobResponse, RemoteJob, ResumeJobResponse, job_state_to_client}; use crate::remote::util::stream_as_body; -use crate::secrets::SecretBinding; use crate::secrets::SecretInfo; use crate::table::BaseTable; use crate::utils::{ - validate_database_name, validate_function_name, validate_namespace, validate_secret_name, - validate_table_name, validate_view_name, + validate_database_name, validate_function_name, validate_namespace, + validate_property_graph_name, validate_table_name, validate_view_name, }; use crate::view::ViewDescription; @@ -48,9 +46,39 @@ use super::client::{ }; use super::sql::SqlClient; use super::sql::materialized_view::quote_identifier; +use super::storage_integration as integration_sql; use super::table::RemoteTable; use super::util::parse_server_version; use super::{ARROW_STREAM_CONTENT_TYPE, extract_job_id}; +use futures::TryStreamExt; + +#[cfg(feature = "remote")] +fn direct_catalog_resource_error(error: Error) -> Error { + let Error::JobFailed { failure, .. } = &error else { + return error; + }; + let Some(Error::Sql { + message, + request_id, + grpc_code, + metadata, + }) = failure.source.as_deref() + else { + return error; + }; + let named_catalog_resource = metadata.resource.as_ref().is_some_and(|resource| { + matches!(resource.kind.as_str(), "function" | "namespace" | "secret") + }); + if !named_catalog_resource { + return error; + } + Error::Sql { + message: message.clone(), + request_id: request_id.clone(), + grpc_code: *grpc_code, + metadata: metadata.clone(), + } +} // Request structure for the remote clone table API #[derive(serde::Serialize)] @@ -220,9 +248,10 @@ impl RemoteDatabaseOptionsBuilder { #[derive(Debug)] pub struct RemoteDatabase { - client: RestfulLanceDbClient, + pub(super) client: RestfulLanceDbClient, // Cache existence and server capabilities, not mutable per-handle table state. table_cache: Cache, + db_name: String, uri: String, /// Headers to pass to the namespace client for authentication namespace_headers: HashMap, @@ -435,6 +464,7 @@ impl RemoteDatabase { Ok(Self { client, table_cache, + db_name: parsed.db_name, uri: uri.to_owned(), namespace_headers, namespace_context_provider, @@ -472,22 +502,10 @@ impl RemoteDatabase { } } - /// Post a request whose body carries a credential. - /// - /// Shared by the create and alter verbs, which declare their own request - /// types: the two mean different things to the service and are free to - /// diverge, so what they share is the posting and not the shape. - /// - /// The value is a request field and never a path segment or query - /// parameter, which keeps it out of access logs and proxy traces. - async fn post_secret_write(&self, route: &str, body: &T) -> Result<()> { - let req = self.client.post(route).json(body); - // This call is what says the body is a credential. Nothing downstream - // can tell from the bytes, and a route list in the transport would have - // to be kept in step with endpoints declared here. - let (request_id, response) = self.client.send_suppressing_body(req).await?; - self.client.check_response(&request_id, response).await?; - Ok(()) + fn sql_client(&self) -> Result<&SqlClient> { + self.sql_client.as_ref().ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".into(), + }) } async fn submit_drop_table( @@ -577,6 +595,7 @@ mod test_utils { Self { client, table_cache: Cache::new(0), + db_name: "default".to_string(), uri: "http://localhost".to_string(), namespace_headers: HashMap::new(), namespace_context_provider: None, @@ -606,6 +625,7 @@ mod test_utils { Self { client, table_cache: Cache::new(0), + db_name: "default".to_string(), uri: "http://localhost".to_string(), namespace_headers: config.extra_headers.clone(), namespace_context_provider, @@ -665,27 +685,11 @@ fn build_namespace_identifier(namespace: &[String]) -> Result { } } -/// Build a full path to a function. Note that we do not need to percent-encode -/// this when using it in a URL because the validation functions ensure that -/// only URL-safe characters are present. -fn build_function_identifier(name: &str, namespace: &[String]) -> Result { - validate_function_name(name)?; - build_compound_identifier(name, namespace) -} - -/// Build a full path to a secret. Note that we do not need to percent-encode -/// this when using it in a URL because the validation functions ensure that -/// only URL-safe characters are present. -fn build_secret_identifier(name: &str, namespace: &[String]) -> Result { - validate_secret_name(name)?; - build_compound_identifier(name, namespace) -} - -/// Build a full path to a view. Note that we do not need to percent-encode -/// this when using it in a URL because the validation functions ensure that -/// only URL-safe characters are present. -fn build_view_identifier(name: &str, namespace: &[String]) -> Result { - validate_view_name(name)?; +/// Build a full path to a property graph. Note that we do not need to +/// percent-encode this when using it in a URL because the validation functions +/// ensure that only URL-safe characters are present. +fn build_property_graph_identifier(name: &str, namespace: &[String]) -> Result { + validate_property_graph_name(name)?; build_compound_identifier(name, namespace) } @@ -723,6 +727,12 @@ struct RemoteListJobRow { state: String, #[serde(default)] created_at_millis: i64, + #[serde(default)] + progress: Option, + #[serde(default)] + phase: Option, + #[serde(default)] + paused: bool, } #[derive(serde::Deserialize)] @@ -734,131 +744,9 @@ struct RemoteListJobsResponse { } #[derive(serde::Deserialize)] -struct RemoteListedFunctionVersion { - definition: FunctionVersion, -} - -#[derive(serde::Deserialize)] -struct RemoteListFunctionsResponse { +struct RemoteListPropertyGraphsResponse { #[serde(default)] - functions: Vec, - #[serde(default)] - page_token: Option, -} - -#[derive(serde::Deserialize)] -struct RemoteDropFunctionResponse { - dropped: bool, -} - -/// The create body: every field of [`FunctionRegistrationRequest`] except the -/// name, which is the path identifier. -/// -/// A struct rather than a literal listing the fields, so that the compiler -/// decides what reaches the service. A field the registration request grows is -/// a build error here until it is handled; a literal would simply not send it. -#[derive(serde::Serialize)] -struct RemoteCreateFunctionRequest<'a> { - artifact: &'a FunctionArtifactRequest, - signature: &'a FunctionSignature, - runtime: &'a PythonRuntimeSpec, - /// Absent when the Function binds nothing, so such a client sends what a - /// client without bindings sends. - /// - /// A service that does not know the field ignores it: registration - /// succeeds, the returned version carries no bindings, and the Function - /// fails at execution with the variable unset. [`ServerVersion`] is how - /// this codebase refuses a feature the service is too old for; it is held - /// per table, so gating a database-level call is follow-up work. - /// - /// [`ServerVersion`]: super::db::ServerVersion - #[serde(skip_serializing_if = "<[SecretBinding]>::is_empty")] - secret_bindings: &'a [SecretBinding], -} - -/// Create a Secret under a name the database does not yet hold. -/// -/// Declared separately from the alter request although the two are identical -/// today: they are different operations to the service -- one refuses an -/// existing name, the other requires it -- and either may grow a field the -/// other has no meaning for. -/// -/// The name and its namespace are the path identifier, so neither appears here. -#[derive(serde::Serialize)] -struct RemoteCreateSecretRequest<'a> { - value: &'a str, -} - -/// Replace the credential behind a Secret the database already holds. -#[derive(serde::Serialize)] -struct RemoteAlterSecretRequest<'a> { - value: &'a str, -} - -#[derive(serde::Deserialize)] -struct RemoteListSecretsResponse { - #[serde(default)] - secrets: Vec, - #[serde(default)] - page_token: Option, -} - -/// An object rather than a bare name so a later listing can carry a Secret's -/// type or last-updated time without breaking this one. -#[derive(serde::Deserialize)] -struct RemoteListedSecret { - name: String, -} - -/// Define a view from a query. The name and its namespace are the path -/// identifier, so neither appears here. -#[derive(serde::Serialize)] -struct RemoteCreateViewRequest<'a> { - query: &'a str, -} - -/// What the service reports about one view. The schema arrives as the -/// namespace spec's JSON encoding, which is what `describe_table` uses too. -#[derive(serde::Deserialize)] -struct RemoteViewDescription { - name: String, - #[serde(default)] - namespace: Vec, - query: String, - default_database: String, - /// A path, like `namespace`: the root is the absent field rather than a - /// spelling of its own. - #[serde(default)] - default_namespace: Vec, - schema: JsonArrowSchema, -} - -impl RemoteViewDescription { - fn into_description(self, request_id: String) -> Result { - let schema = - lance_namespace::schema::convert_json_arrow_schema(&self.schema).map_err(|source| { - Error::Http { - source: format!("View '{}' has an undecodable schema: {source}", self.name) - .into(), - request_id, - status_code: None, - } - })?; - Ok(ViewDescription { - name: self.name, - namespace_path: self.namespace, - query: self.query, - default_database: self.default_database, - default_namespace_path: self.default_namespace, - schema: Arc::new(schema), - }) - } -} - -#[derive(serde::Deserialize)] -struct RemoteListViewsResponse { - #[serde(default)] - views: Vec, + property_graphs: Vec, #[serde(default)] page_token: Option, } @@ -871,7 +759,7 @@ impl Database for RemoteDatabase { async fn read_consistency(&self) -> Result { Err(Error::NotSupported { - message: "Getting the read consistency is not yet supported in LanceDB Distributed" + message: "Getting the read consistency is not yet supported in LanceDB Enterprise" .to_string(), }) } @@ -883,7 +771,7 @@ impl Database for RemoteDatabase { if request.with_no_data { return Err(Error::NotSupported { message: - "materialized views in LanceDB Distributed must be populated during creation" + "materialized views in LanceDB Enterprise must be populated during creation" .to_string(), }); } @@ -915,16 +803,26 @@ impl Database for RemoteDatabase { } else { format!(" WITH ({})", options.join(", ")) }; - client - .submit_as_job( + let submission = client + .submit_materialized_view_job( format!( "CREATE MATERIALIZED VIEW \"{name}\"{options} AS {}", request.query ), request.namespace_path, - || async { Ok(()) }, ) - .await + .await?; + match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { + job_id, + } => Ok(Job::new(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))), + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Query(query) => { + Ok(client.query_job(query, || async { Ok(()) })) + } + } } async fn drop_materialized_view_async( @@ -973,29 +871,11 @@ impl Database for RemoteDatabase { request: FunctionRegistrationRequest, namespace_path: &[String], ) -> Result> { - let function_id = build_function_identifier(&request.name, namespace_path)?; - let req = self - .client - .post(&format!("/v1/function/{function_id}/create")) - .json(&RemoteCreateFunctionRequest { - artifact: &request.artifact, - signature: &request.signature, - runtime: &request.runtime, - secret_bindings: &request.secret_bindings, - }); - let (request_id, response) = self.client.send(req).await?; - let response = self.client.check_response(&request_id, response).await?; - let status = response.status(); - let body = response.text().await.err_to_http(request_id.clone())?; - let job_id = extract_job_id(&body).ok_or_else(|| Error::Http { - source: "Function registration response did not contain a valid job_id".into(), - request_id, - status_code: Some(status), - })?; - Ok(Job::new_typed(Box::new(RemoteJob::new( - self.client.clone(), - job_id, - )))) + validate_function_name(&request.name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .register_function(request, namespace_path) + .await } async fn get_function( @@ -1004,46 +884,23 @@ impl Database for RemoteDatabase { version: &str, namespace_path: &[String], ) -> Result { - let function_id = build_function_identifier(name, namespace_path)?; - let req = self - .client - .post(&format!("/v1/function/{function_id}/describe")) - .json(&serde_json::json!({ - "version": version, - })); - let (request_id, response) = self.client.send(req).await?; - let response = self.client.check_response(&request_id, response).await?; - response.json().await.err_to_http(request_id) + validate_function_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .describe_function(name, version, namespace_path) + .await + .map_err(direct_catalog_resource_error) } async fn list_functions( &self, namespace_path: &[String], options: ListingOptions, - ) -> Result> { - let namespace_id = build_namespace_identifier(namespace_path)?; - let path = format!("/v1/namespace/{namespace_id}/function/list"); - let mut req = self.client.get(&path); - if let Some(token) = options.page_token { - req = req.query(&[("page_token", token)]); - } - if let Some(limit) = options.page_limit { - req = req.query(&[("limit", limit)]); - } - req = req.query(&[("include_definition", true)]); - let (request_id, response) = self.client.send(req).await?; - let response = self.client.check_response(&request_id, response).await?; - let response: RemoteListFunctionsResponse = - response.json().await.err_to_http(request_id)?; - let items = response - .functions - .into_iter() - .map(|listed| listed.definition) - .collect(); - Ok(ListingPage { - items, - page_token: response.page_token, - }) + ) -> Result> { + validate_namespace(namespace_path)?; + self.sql_client()? + .list_functions(namespace_path, options) + .await } async fn drop_function( @@ -1052,10 +909,14 @@ impl Database for RemoteDatabase { version: &str, namespace_path: &[String], ) -> Result { - Ok(self - .drop_function_async(name, version, namespace_path) - .await? - .0) + validate_function_name(name)?; + validate_namespace(namespace_path)?; + let (dropped, job) = self + .sql_client()? + .drop_function(name, version, namespace_path) + .await?; + job.wait().await?; + Ok(dropped) } async fn drop_function_async( @@ -1064,43 +925,105 @@ impl Database for RemoteDatabase { version: &str, namespace_path: &[String], ) -> Result<(bool, Job)> { - let function_id = build_function_identifier(name, namespace_path)?; - let req = self - .client - .post(&format!("/v1/function/{function_id}/drop")) - .json(&serde_json::json!({ - "version": version, - })); - let (request_id, response) = self.client.send(req).await?; - let response = self.client.check_response(&request_id, response).await?; - let status = response.status(); - let body = response.text().await.err_to_http(request_id.clone())?; - let dropped: RemoteDropFunctionResponse = - serde_json::from_str(&body).map_err(|source| Error::Http { - source: Box::new(source), - request_id: request_id.clone(), - status_code: Some(status), - })?; - let job = match status { - StatusCode::OK => Job::new_done(), - StatusCode::ACCEPTED => { - let job_id = extract_job_id(&body).ok_or_else(|| Error::Http { - source: "asynchronous Function drop response did not contain a valid job_id" - .into(), - request_id, - status_code: Some(status), - })?; - Job::new(Box::new(RemoteJob::new(self.client.clone(), job_id))) - } - _ => { - return Err(Error::Http { - source: "Function drop must return 200 OK or 202 Accepted".into(), - request_id, - status_code: Some(status), - }); - } - }; - Ok((dropped.dropped, job)) + validate_function_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .drop_function(name, version, namespace_path) + .await + } + + #[doc(hidden)] + async fn drop_function_with_warnings( + &self, + name: &str, + version: &str, + namespace_path: &[String], + ) -> Result<(bool, Vec)> { + validate_function_name(name)?; + validate_namespace(namespace_path)?; + let (outcome, job) = self + .sql_client()? + .drop_function_outcome(name, version, namespace_path) + .await?; + job.wait().await?; + Ok((outcome.dropped, outcome.warnings)) + } + + async fn create_storage_integration( + &self, + name: &str, + request: CreateStorageIntegrationRequest, + namespace_path: &[String], + ) -> Result { + let sql = integration_sql::create_sql(name, namespace_path, &request)?; + let result = self + .execute_query_async(ExecuteQueryRequest { + query: sql, + default_namespace_path: namespace_path.to_vec(), + parameters: None, + }) + .await?; + integration_sql::decode_info(&result.reader().await?.try_collect::>().await?) + } + + async fn describe_storage_integration( + &self, + name: &str, + namespace_path: &[String], + ) -> Result { + let name = integration_sql::object_name(name, namespace_path)?; + let result = self + .execute_query_async(ExecuteQueryRequest { + query: format!("DESCRIBE STORAGE INTEGRATION {name}"), + default_namespace_path: namespace_path.to_vec(), + parameters: None, + }) + .await?; + integration_sql::decode_info(&result.reader().await?.try_collect::>().await?) + } + + async fn list_storage_integrations( + &self, + namespace_path: &[String], + options: ListingOptions, + ) -> Result> { + validate_namespace(namespace_path)?; + let result = self + .execute_query_async(ExecuteQueryRequest { + query: "SHOW STORAGE INTEGRATIONS".into(), + default_namespace_path: namespace_path.to_vec(), + parameters: None, + }) + .await?; + let mut names = + integration_sql::decode_names(&result.reader().await?.try_collect::>().await?)?; + if let Some(token) = options.page_token { + names.retain(|name| name > &token); + } + let mut page_token = None; + if let Some(limit) = options.page_limit + && names.len() > limit as usize + { + names.truncate(limit as usize); + page_token = names.last().cloned(); + } + Ok(ListingPage { + items: names, + page_token, + }) + } + + async fn drop_storage_integration(&self, name: &str, namespace_path: &[String]) -> Result<()> { + let name = integration_sql::object_name(name, namespace_path)?; + let result = self + .execute_query_async(ExecuteQueryRequest { + query: format!("DROP STORAGE INTEGRATION {name}"), + default_namespace_path: namespace_path.to_vec(), + parameters: None, + }) + .await?; + result.reader().await?.try_collect::>().await?; + Ok(()) } async fn create_secret( @@ -1109,67 +1032,47 @@ impl Database for RemoteDatabase { value: &str, namespace_path: &[String], ) -> Result<()> { - let secret_id = build_secret_identifier(name, namespace_path)?; - self.post_secret_write( - &format!("/v1/secret/{secret_id}/create"), - &RemoteCreateSecretRequest { value }, - ) - .await + crate::utils::validate_secret_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .write_secret(name, value, namespace_path, true) + .await + .map_err(direct_catalog_resource_error) } - async fn alter_secret(&self, name: &str, value: &str, namespace_path: &[String]) -> Result<()> { - let secret_id = build_secret_identifier(name, namespace_path)?; - self.post_secret_write( - &format!("/v1/secret/{secret_id}/alter"), - &RemoteAlterSecretRequest { value }, - ) - .await + crate::utils::validate_secret_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .write_secret(name, value, namespace_path, false) + .await + .map_err(direct_catalog_resource_error) } - async fn list_secrets( &self, namespace_path: &[String], options: ListingOptions, ) -> Result> { - let namespace_id = build_namespace_identifier(namespace_path)?; - let path = format!("/v1/namespace/{namespace_id}/secret/list"); - let mut req = self.client.get(&path); - if let Some(token) = options.page_token { - req = req.query(&[("page_token", token)]); - } - if let Some(limit) = options.page_limit { - req = req.query(&[("limit", limit)]); - } - let (request_id, response) = self.client.send(req).await?; - let response = self.client.check_response(&request_id, response).await?; - let response: RemoteListSecretsResponse = response.json().await.err_to_http(request_id)?; - let items = response - .secrets - .into_iter() - .map(|secret| secret.name) - .collect(); - Ok(ListingPage { - items, - page_token: response.page_token, - }) + validate_namespace(namespace_path)?; + self.sql_client()? + .list_secrets(namespace_path, options) + .await + .map_err(direct_catalog_resource_error) } - async fn drop_secret(&self, name: &str, namespace_path: &[String]) -> Result<()> { - let secret_id = build_secret_identifier(name, namespace_path)?; - let req = self.client.post(&format!("/v1/secret/{secret_id}/drop")); - let (request_id, response) = self.client.send(req).await?; - self.client.check_response(&request_id, response).await?; - Ok(()) + crate::utils::validate_secret_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .drop_secret(name, namespace_path) + .await + .map_err(direct_catalog_resource_error) } - async fn describe_secret(&self, name: &str, namespace_path: &[String]) -> Result { - let secret_id = build_secret_identifier(name, namespace_path)?; - let req = self - .client - .post(&format!("/v1/secret/{secret_id}/describe")); - let (request_id, response) = self.client.send(req).await?; - let response = self.client.check_response(&request_id, response).await?; - response.json().await.err_to_http(request_id) + crate::utils::validate_secret_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .describe_secret(name, namespace_path) + .await + .map_err(direct_catalog_resource_error) } async fn create_view( @@ -1178,42 +1081,94 @@ impl Database for RemoteDatabase { query: &str, namespace_path: &[String], ) -> Result { - let view_id = build_view_identifier(name, namespace_path)?; - let req = self - .client - .post(&format!("/v1/view/{view_id}/create")) - .json(&RemoteCreateViewRequest { query }); - let (request_id, response) = self.client.send(req).await?; - let response = self.client.check_response(&request_id, response).await?; - let description: RemoteViewDescription = - response.json().await.err_to_http(request_id.clone())?; - description.into_description(request_id) + validate_view_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .create_view(name, query, namespace_path) + .await } - async fn describe_view( &self, name: &str, namespace_path: &[String], ) -> Result { - let view_id = build_view_identifier(name, namespace_path)?; - let req = self.client.post(&format!("/v1/view/{view_id}/describe")); - let (request_id, response) = self.client.send(req).await?; - let response = self.client.check_response(&request_id, response).await?; - let description: RemoteViewDescription = - response.json().await.err_to_http(request_id.clone())?; - description.into_description(request_id) + validate_view_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()?.describe_view(name, namespace_path).await } - async fn drop_view(&self, name: &str, namespace_path: &[String]) -> Result<()> { self.drop_view_async(name, namespace_path) .await? .wait() .await } - async fn drop_view_async(&self, name: &str, namespace_path: &[String]) -> Result { - let view_id = build_view_identifier(name, namespace_path)?; - let req = self.client.post(&format!("/v1/view/{view_id}/drop")); + validate_view_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .submit_as_job( + format!("DROP VIEW {}", quote_identifier(name)), + namespace_path.to_vec(), + || async { Ok(()) }, + ) + .await + } + async fn list_views( + &self, + namespace_path: &[String], + options: ListingOptions, + ) -> Result> { + validate_namespace(namespace_path)?; + self.sql_client()?.list_views(namespace_path, options).await + } + + async fn create_property_graph( + &self, + name: &str, + definition: &PropertyGraphDefinition, + namespace_path: &[String], + ) -> Result { + let graph_id = build_property_graph_identifier(name, namespace_path)?; + let req = self + .client + .post(&format!("/v1/property_graph/{graph_id}/create")) + .json(definition); + let (request_id, response) = self.client.send(req).await?; + let response = self.client.check_response(&request_id, response).await?; + response.json().await.err_to_http(request_id) + } + + async fn describe_property_graph( + &self, + name: &str, + namespace_path: &[String], + ) -> Result { + let graph_id = build_property_graph_identifier(name, namespace_path)?; + let req = self + .client + .post(&format!("/v1/property_graph/{graph_id}/describe")) + .json(&serde_json::json!({})); + let (request_id, response) = self.client.send(req).await?; + let response = self.client.check_response(&request_id, response).await?; + response.json().await.err_to_http(request_id) + } + + async fn drop_property_graph(&self, name: &str, namespace_path: &[String]) -> Result<()> { + self.drop_property_graph_async(name, namespace_path) + .await? + .wait() + .await + } + + async fn drop_property_graph_async( + &self, + name: &str, + namespace_path: &[String], + ) -> Result { + let graph_id = build_property_graph_identifier(name, namespace_path)?; + let req = self + .client + .post(&format!("/v1/property_graph/{graph_id}/drop")); let (request_id, response) = self.client.send(req).await?; let response = self.client.check_response(&request_id, response).await?; let status = response.status(); @@ -1223,7 +1178,7 @@ impl Database for RemoteDatabase { StatusCode::OK => Ok(Job::new_done()), StatusCode::ACCEPTED => { let job_id = extract_job_id(&body).ok_or_else(|| Error::Http { - source: "view drop response did not contain a valid job_id".into(), + source: "property graph drop response did not contain a valid job_id".into(), request_id, status_code: Some(status), })?; @@ -1233,20 +1188,20 @@ impl Database for RemoteDatabase { )))) } _ => Err(Error::Http { - source: "view drop must return 200 OK or 202 Accepted".into(), + source: "property graph drop must return 200 OK or 202 Accepted".into(), request_id, status_code: Some(status), }), } } - async fn list_views( + async fn list_property_graphs( &self, namespace_path: &[String], options: ListingOptions, ) -> Result> { let namespace_id = build_namespace_identifier(namespace_path)?; - let path = format!("/v1/namespace/{namespace_id}/view/list"); + let path = format!("/v1/namespace/{namespace_id}/property_graph/list"); let mut req = self.client.get(&path); if let Some(token) = options.page_token { req = req.query(&[("page_token", token)]); @@ -1256,10 +1211,10 @@ impl Database for RemoteDatabase { } let (request_id, response) = self.client.send(req).await?; let response = self.client.check_response(&request_id, response).await?; - let response: RemoteListViewsResponse = response.json().await.err_to_http(request_id)?; - let items = response.views; + let response: RemoteListPropertyGraphsResponse = + response.json().await.err_to_http(request_id)?; Ok(ListingPage { - items, + items: response.property_graphs, page_token: response.page_token, }) } @@ -1278,6 +1233,32 @@ impl Database for RemoteDatabase { } } + async fn list_gpu_classes(&self) -> Result> { + #[derive(serde::Deserialize)] + struct Response { + gpu_classes: Vec, + } + + let req = self.client.get("/v1/gpu/classes"); + let (request_id, response) = self.client.send(req).await?; + let response = match self.client.check_response(&request_id, response).await { + Ok(response) => response, + Err(Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }) => { + return Err(Error::NotSupported { + message: "GPU class discovery requires a newer LanceDB server; \ + GET /v1/gpu/classes returned 404 Not Found" + .to_string(), + }); + } + Err(error) => return Err(error), + }; + let response: Response = response.json().await.err_to_http(request_id)?; + Ok(response.gpu_classes) + } + async fn list_jobs(&self, options: ListingOptions) -> Result> { let mut body = serde_json::json!({}); if let Some(token) = options.page_token { @@ -1299,6 +1280,9 @@ impl Database for RemoteDatabase { job_type: row.job_type, state: job_state_to_client(&row.state), created_at_millis: row.created_at_millis, + progress: row.progress, + phase: row.phase, + paused: row.paused, }) .collect(); Ok(ListingPage { @@ -1488,7 +1472,7 @@ impl Database for RemoteDatabase { if provided { return Err(Error::NotSupported { message: format!( - "{option} is not supported for table creation in LanceDB Distributed" + "{option} is not supported for table creation in LanceDB Enterprise" ), }); } @@ -1562,6 +1546,7 @@ impl Database for RemoteDatabase { let cache_key = build_cache_key(&request.name, &request.namespace_path); let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), + self.db_name.clone(), request.name.clone(), request.namespace_path.clone(), table_identifier, @@ -1605,6 +1590,7 @@ impl Database for RemoteDatabase { let cache_key = build_cache_key(&request.target_table_name, &request.target_namespace_path); let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), + self.db_name.clone(), request.target_table_name.clone(), request.target_namespace_path.clone(), table_identifier, @@ -1631,7 +1617,7 @@ impl Database for RemoteDatabase { if provided { return Err(Error::NotSupported { message: format!( - "{option} is not supported for table access in LanceDB Distributed" + "{option} is not supported for table access in LanceDB Enterprise" ), }); } @@ -1654,6 +1640,7 @@ impl Database for RemoteDatabase { Ok(Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), + self.db_name.clone(), request.name, request.namespace_path, identifier, @@ -1673,6 +1660,7 @@ impl Database for RemoteDatabase { let describe_body = rsp.text().await.ok(); let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), + self.db_name.clone(), request.name.clone(), request.namespace_path.clone(), identifier, @@ -1748,14 +1736,21 @@ impl Database for RemoteDatabase { }) } + #[allow(deprecated)] async fn drop_all_tables(&self, namespace_path: &[String]) -> Result<()> { - // TODO: Implement namespace-aware drop_all_tables - let _namespace_path = namespace_path; // Suppress unused warning for now - Err(crate::Error::NotSupported { - message: "Dropping all tables is not currently supported in the remote API. \ - List tables and call drop_table for each table instead." - .to_string(), - }) + let tables = self + .table_names(TableNamesRequest { + namespace_path: namespace_path.to_vec(), + start_after: None, + limit: None, + }) + .await?; + + for table in tables { + self.drop_table(&table, namespace_path).await?; + } + + Ok(()) } async fn list_namespaces( @@ -1959,7 +1954,7 @@ mod tests { use futures::TryStreamExt; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::{Arc, OnceLock}; + use std::sync::{Arc, Mutex, OnceLock}; use arrow_array::{Int32Array, RecordBatch}; use arrow_schema::{DataType, Field, Schema}; @@ -1968,6 +1963,8 @@ mod tests { use crate::connection::ConnectBuilder; use crate::database::Database; + use crate::error::{JobFailure, RemoteErrorMetadata, RemoteResourceIdentity}; + use crate::graph::{EdgeTable, Endpoint, NodeTable, PropertyGraphDefinition}; use crate::materialized_view::CreateMaterializedViewRequest; use crate::{ Connection, Error, @@ -1976,6 +1973,53 @@ mod tests { remote::{ARROW_STREAM_CONTENT_TYPE, ClientConfig, HeaderProvider, JSON_CONTENT_TYPE}, }; + #[test] + fn catalog_helpers_unwrap_only_a_named_resource_job_failure() { + let job_failed = |source: Error| Error::JobFailed { + job_id: Some("job-1".into()), + failure: Box::new(JobFailure { + sql_job_id: Some("job-1".into()), + source: Some(Arc::new(source)), + ..Default::default() + }), + }; + + for (kind, name) in [ + ("function", "missing"), + ("namespace", "missing_ns"), + ("secret", "missing_secret"), + ] { + let resource = RemoteResourceIdentity::new(kind, name, vec!["ns".into()]); + let sql = Error::Sql { + message: format!("{kind} '{name}' was not found"), + request_id: "worker-request".into(), + grpc_code: 5, + metadata: Box::new(RemoteErrorMetadata { + error_code: Some("not_found".into()), + job_id: Some("job-1".into()), + resource: Some(resource.clone()), + ..Default::default() + }), + }; + let Error::Sql { metadata, .. } = super::direct_catalog_resource_error(job_failed(sql)) + else { + panic!("catalog helper must surface the {kind} resource failure"); + }; + assert_eq!(metadata.resource, Some(resource)); + } + + let generic = Error::Sql { + message: "query failed".into(), + request_id: "worker-request".into(), + grpc_code: 3, + metadata: Box::new(RemoteErrorMetadata::default()), + }; + assert!(matches!( + super::direct_catalog_resource_error(job_failed(generic)), + Error::JobFailed { .. } + )); + } + #[tokio::test] async fn test_catalog_namespace_identifier_validates_all_namespace_components() { let mut db = super::RemoteDatabase::new_mock(|_| -> http::Response { @@ -2042,77 +2086,6 @@ mod tests { assert_eq!(key1, key6, "Same inputs should produce same cache key"); } - #[tokio::test] - async fn test_create_materialized_view_validates_before_submission() { - let db = super::RemoteDatabase::new_mock(|_| -> http::Response { - panic!("materialized-view creation must not send REST requests") - }); - for seconds in [0.0, -1.0, f64::NAN, f64::INFINITY] { - let result = db - .create_materialized_view_async(CreateMaterializedViewRequest { - name: "adults".into(), - namespace_path: vec![], - query: "SELECT * FROM people".into(), - with_no_data: false, - auto_refresh_enabled: None, - auto_refresh_interval_seconds: Some(seconds), - }) - .await; - assert!(matches!(result, Err(Error::InvalidInput { .. }))); - } - } - - #[tokio::test] - async fn test_drop_function_async_returns_job() { - let db = super::RemoteDatabase::new_mock(|request| { - assert_eq!(request.method(), "POST"); - assert_eq!(request.url().path(), "/v1/function/embed/drop"); - http::Response::builder() - .status(202) - .body(serde_json::json!({"dropped": true, "job_id": "j1-fn-drop"}).to_string()) - .unwrap() - }); - let (dropped, job) = db.drop_function_async("embed", "1", &[]).await.unwrap(); - assert!(dropped); - assert_eq!(job.id(), Some("j1-fn-drop")); - } - - /// An unbound name and an inline deletion both answer `200`: the name is gone and - /// nothing is left to wait for, so the job is already finished. - #[tokio::test] - async fn test_drop_function_async_completed_inline() { - let db = super::RemoteDatabase::new_mock(|_| { - http::Response::builder() - .status(200) - .body(serde_json::json!({"dropped": false}).to_string()) - .unwrap() - }); - let (dropped, job) = db.drop_function_async("embed", "1", &[]).await.unwrap(); - assert!(!dropped); - assert_eq!(job.id(), None); - assert_eq!(job.status().await.unwrap(), "finished"); - job.wait().await.unwrap(); - } - - #[tokio::test] - async fn test_drop_function_async_rejects_incomplete_acceptance() { - for body in [ - r#"{"dropped":true}"#, - r#"{"dropped":true,"job_id":""}"#, - r#"{"dropped":true,"job_id":null}"#, - ] { - let db = super::RemoteDatabase::new_mock(move |_| { - http::Response::builder().status(202).body(body).unwrap() - }); - let error = db - .drop_function_async("embed", "1", &[]) - .await - .err() - .unwrap(); - assert!(error.to_string().contains("valid job_id")); - } - } - #[tokio::test] async fn test_retries() { // We'll record the request_id here, to check it matches the one in the error. @@ -2676,7 +2649,7 @@ mod tests { .execute() .await; assert!(matches!(result, Err(Error::NotSupported { message }) - if message.contains("write_options") && message.contains("LanceDB Distributed"))); + if message.contains("write_options") && message.contains("LanceDB Enterprise"))); } } @@ -2749,7 +2722,7 @@ mod tests { ] { let result = builder.execute().await; assert!(matches!(result, Err(Error::NotSupported { message }) - if message.contains(option) && message.contains("LanceDB Distributed"))); + if message.contains(option) && message.contains("LanceDB Enterprise"))); } } @@ -2767,7 +2740,7 @@ mod tests { ] { let result = builder.api_key("fake").region("us-east-1").execute().await; assert!(matches!(result, Err(Error::NotSupported { message }) - if message.contains(option) && message.contains("LanceDB Distributed"))); + if message.contains(option) && message.contains("LanceDB Enterprise"))); } } @@ -2948,6 +2921,174 @@ mod tests { // NOTE: the API will return 200 even if the table does not exist. So we shouldn't expect 404. } + #[tokio::test] + async fn test_drop_all_tables() { + let dropped_paths = Arc::new(Mutex::new(Vec::new())); + let dropped_paths_in_handler = Arc::clone(&dropped_paths); + let conn = Connection::new_with_handler(move |request| match request.url().path() { + "/v1/table/" => { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().query(), None); + http::Response::builder() + .status(200) + .body(r#"{"tables":["table1","table2"]}"#.to_string()) + .unwrap() + } + "/v1/table/table1/drop/" | "/v1/table/table2/drop/" => { + assert_eq!(request.method(), &reqwest::Method::POST); + assert_eq!(request.url().query(), None); + assert!(request.body().is_none()); + dropped_paths_in_handler + .lock() + .unwrap() + .push(request.url().path().to_string()); + http::Response::builder() + .status(200) + .body(String::new()) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + }); + + conn.drop_all_tables(&[]).await.unwrap(); + + let mut actual = dropped_paths.lock().unwrap().clone(); + actual.sort(); + assert_eq!( + actual, + vec!["/v1/table/table1/drop/", "/v1/table/table2/drop/"] + ); + } + + #[tokio::test] + async fn test_drop_all_tables_with_namespace() { + let dropped_paths = Arc::new(Mutex::new(Vec::new())); + let dropped_paths_in_handler = Arc::clone(&dropped_paths); + let conn = Connection::new_with_handler(move |request| match request.url().path() { + "/v1/namespace/ns1$ns2/table/list" => { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().query(), None); + http::Response::builder() + .status(200) + .body(r#"{"tables":["table1","table2"]}"#.to_string()) + .unwrap() + } + "/v1/table/ns1$ns2$table1/drop/" | "/v1/table/ns1$ns2$table2/drop/" => { + assert_eq!(request.method(), &reqwest::Method::POST); + assert_eq!(request.url().query(), None); + assert!(request.body().is_none()); + dropped_paths_in_handler + .lock() + .unwrap() + .push(request.url().path().to_string()); + http::Response::builder() + .status(200) + .body(String::new()) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + }); + + conn.drop_all_tables(&["ns1".to_string(), "ns2".to_string()]) + .await + .unwrap(); + + let mut actual = dropped_paths.lock().unwrap().clone(); + actual.sort(); + assert_eq!( + actual, + vec![ + "/v1/table/ns1$ns2$table1/drop/", + "/v1/table/ns1$ns2$table2/drop/" + ] + ); + } + + #[tokio::test] + async fn test_drop_all_tables_follows_server_pages() { + let listing_page = Arc::new(AtomicUsize::new(0)); + let listing_page_in_handler = Arc::clone(&listing_page); + let dropped_paths = Arc::new(Mutex::new(Vec::new())); + let dropped_paths_in_handler = Arc::clone(&dropped_paths); + let conn = Connection::new_with_handler(move |request| match request.url().path() { + "/v1/table/" => { + assert_eq!(request.method(), &reqwest::Method::GET); + match listing_page_in_handler.fetch_add(1, Ordering::SeqCst) { + 0 => { + assert_eq!(request.url().query(), None); + http::Response::builder() + .status(200) + .body( + r#"{"tables":["table1"],"page_token":"opaque-token"}"#.to_string(), + ) + .unwrap() + } + 1 => { + let query: HashMap<_, _> = request.url().query_pairs().collect(); + assert_eq!( + query.get("page_token").map(|token| token.as_ref()), + Some("opaque-token") + ); + http::Response::builder() + .status(200) + .body(r#"{"tables":["table2"]}"#.to_string()) + .unwrap() + } + _ => panic!("table listing requested too many pages"), + } + } + "/v1/table/table1/drop/" | "/v1/table/table2/drop/" => { + assert_eq!(request.method(), &reqwest::Method::POST); + dropped_paths_in_handler + .lock() + .unwrap() + .push(request.url().path().to_string()); + http::Response::builder() + .status(200) + .body(String::new()) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + }); + + conn.drop_all_tables(&[]).await.unwrap(); + + assert_eq!(listing_page.load(Ordering::SeqCst), 2); + assert_eq!( + *dropped_paths.lock().unwrap(), + vec!["/v1/table/table1/drop/", "/v1/table/table2/drop/"] + ); + } + + #[tokio::test] + async fn test_drop_all_tables_propagates_listing_error() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/table/"); + http::Response::builder() + .status(500) + .body("internal server error".to_string()) + .unwrap() + }); + + let error = conn.drop_all_tables(&[]).await.unwrap_err(); + assert!(matches!(error, Error::Retry { .. })); + } + + #[tokio::test] + async fn test_drop_all_tables_with_no_tables() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/table/"); + http::Response::builder() + .status(200) + .body(r#"{"tables":[]}"#.to_string()) + .unwrap() + }); + + conn.drop_all_tables(&[]).await.unwrap(); + } + #[tokio::test] async fn test_drop_table_does_not_read_response_body() { let conn = Connection::new_with_handler(|_| { @@ -3794,7 +3935,7 @@ mod tests { assert!(items.try_next().await.unwrap().is_none()); assert!(items.try_next().await.unwrap().is_none()); } - for resource in ["secret", "view", "function", "jobs"] { + for resource in ["property_graph", "jobs"] { let count = Arc::new(AtomicUsize::new(0)); let conn = Connection::new_with_handler({ let count = count.clone(); @@ -3817,20 +3958,14 @@ mod tests { let query = request.url().query_pairs().collect::>(); assert_eq!(query.get("page_token").unwrap(), token); assert_eq!(query.get("limit").unwrap(), "2"); - if resource == "function" { - assert_eq!(query.get("include_definition").unwrap(), "true"); - } } let (key, item) = match resource { "secret" => ("secrets", serde_json::json!({"name": "a"})), + "property_graph" => ("property_graphs", serde_json::json!("a")), "jobs" => ( "jobs", serde_json::json!({"job_id": "a", "table": "t", "job_type": "create_index", "state": "in_progress", "created_at_millis": 1}), ), - "function" => ( - "functions", - serde_json::json!({"name": "embed", "version": "1", "definition": serde_json::from_str::(include_str!("../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json")).unwrap()}), - ), _ => ("views", serde_json::json!("a")), }; let items = if page == 1 { @@ -3848,12 +3983,74 @@ mod tests { match resource { "secret" => check(conn.list_secrets(&namespace, options), count).await, "view" => check(conn.list_views(&namespace, options), count).await, - "function" => check(conn.list_functions(&namespace, options), count).await, + "property_graph" => { + check(conn.list_property_graphs(&namespace, options), count).await + } _ => check(conn.list_jobs(options), count).await, } } } + #[tokio::test] + async fn test_list_gpu_classes_reports_configured_hardware() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/gpu/classes"); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "gpu_classes": [ + { + "name": "default", + "resource_name": "nvidia.com/gpu", + "gpu_model": "NVIDIA A10G", + "gpu_memory_bytes": 25_769_803_776_u64, + "max_gpu_count_per_worker": 1, + "cpu_millis": 4000, + "memory_bytes": 25_769_803_776_u64, + "ephemeral_storage_bytes": 1_073_741_824_u64, + }, + { + "name": "h100", + "resource_name": "nvidia.com/gpu", + "gpu_model": "NVIDIA H100", + "gpu_memory_bytes": 85_899_345_920_u64, + "max_gpu_count_per_worker": 8, + } + ] + }) + .to_string(), + ) + .unwrap() + }); + + let classes = conn.list_gpu_classes().await.unwrap(); + assert_eq!(classes.len(), 2); + assert_eq!(classes[0].name, "default"); + assert_eq!(classes[0].gpu_model.as_deref(), Some("NVIDIA A10G")); + assert_eq!(classes[0].gpu_memory_bytes, Some(25_769_803_776)); + assert_eq!(classes[1].max_gpu_count_per_worker, Some(8)); + assert_eq!(classes[1].cpu_millis, None); + } + + #[tokio::test] + async fn test_list_gpu_classes_explains_older_server_404() { + let conn = Connection::new_with_handler(|_| { + http::Response::builder() + .status(404) + .body("not found") + .unwrap() + }); + let error = conn.list_gpu_classes().await.unwrap_err(); + assert!(matches!( + error, + Error::NotSupported { message } + if message.contains("newer LanceDB server") + && message.contains("/v1/gpu/classes") + )); + } + #[tokio::test] async fn test_list_jobs_does_not_truncate_after_100_pages() { let conn = Connection::new_with_handler(|request| { @@ -3888,7 +4085,7 @@ mod tests { http::Response::builder() .status(200) .body( - r#"{"jobs": [{"job_id": "job-1", "table": "t1", "job_type": "create_index", "state": "in_progress", "created_at_millis": 1000}], "page_token": "next"}"#, + r#"{"jobs": [{"job_id": "job-1", "table": "t1", "job_type": "create_index", "state": "in_progress", "created_at_millis": 1000, "progress": {"rows_planned": 10, "rows_computed": 4}, "phase": "running", "paused": true}], "page_token": "next"}"#, ) .unwrap() } @@ -3912,6 +4109,9 @@ mod tests { assert_eq!(jobs[0].job_id, "job-1"); assert_eq!(jobs[0].table, "t1"); assert_eq!(jobs[0].state, "running"); + 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[1].job_id, "job-2"); assert_eq!(jobs[1].state, "finished"); assert_eq!(jobs[1].created_at_millis, 2000); @@ -4228,29 +4428,6 @@ mod tests { } } - /// An identifier the service accepts is untouched by the encoding, so the - /// route reads like the table and Function routes beside it. - #[tokio::test] - async fn test_an_admissible_identifier_is_not_encoded() { - use std::sync::{Arc, Mutex}; - let seen = Arc::new(Mutex::new(String::new())); - let captured = seen.clone(); - let conn = Connection::new_with_handler(move |request| { - *captured.lock().unwrap() = request.url().path().to_string(); - http::Response::builder().status(200).body("{}").unwrap() - }); - conn.drop_secret( - "openai-prod.v1", - &["prod".to_string(), "vision_2".to_string()], - ) - .await - .unwrap(); - assert_eq!( - *seen.lock().unwrap(), - "/v1/secret/prod$vision_2$openai-prod.v1/drop" - ); - } - /// A table name is joined into the route the same way a Secret's is, so the /// same two failures are reachable: a dot-only name leaves the table route /// entirely, and a name holding the delimiter is indistinguishable from a @@ -4309,684 +4486,6 @@ mod tests { )); } - /// Reject relative segments and their encoded forms before sending a request, - /// so a function name cannot change the route through URL normalization. - #[tokio::test] - async fn test_a_relative_segment_function_name_is_refused() { - use std::sync::{Arc, Mutex}; - for name in [".", "..", "%2E%2E"] { - let reached = Arc::new(Mutex::new(false)); - let flag = reached.clone(); - let conn = Connection::new_with_handler(move |_| { - *flag.lock().unwrap() = true; - http::Response::builder().status(200).body("{}").unwrap() - }); - let error = conn - .drop_function(name, "fv_1", &[]) - .await - .expect_err("a dot-only Function name must be refused"); - assert!(matches!(error, Error::InvalidInput { .. }), "{error}"); - assert!(!*reached.lock().unwrap(), "{name:?} reached the transport"); - } - } - - /// Only `.` and `..` are relative segments. `...` and longer runs are - /// ordinary and address perfectly well, so refusing them would make an - /// object that works today stop working on upgrade. This pins that. - #[tokio::test] - async fn test_a_longer_run_of_periods_is_an_ordinary_name() { - use std::sync::{Arc, Mutex}; - for name in ["...", "....", "a.", ".a", "a..b"] { - let seen = Arc::new(Mutex::new(String::new())); - let captured = seen.clone(); - let conn = Connection::new_with_handler(move |request| { - *captured.lock().unwrap() = request.url().path().to_string(); - http::Response::builder().status(200).body("{}").unwrap() - }); - conn.drop_secret(name, &[]) - .await - .unwrap_or_else(|error| panic!("{name:?} must remain addressable: {error}")); - assert_eq!( - *seen.lock().unwrap(), - format!("/v1/secret/{name}/drop"), - "{name:?} did not reach its own route" - ); - } - } - - #[tokio::test] - async fn test_create_and_alter_secret_send_the_value_in_the_request_body() { - for (route, call) in [ - ("/v1/secret/openai-prod/create", true), - ("/v1/secret/openai-prod/alter", false), - ] { - let conn = Connection::new_with_handler(move |request| { - assert_eq!(request.method(), &reqwest::Method::POST); - assert_eq!(request.url().path(), route); - // Never a path segment or query parameter, which is what keeps - // it out of access logs and proxy traces. - assert!(request.url().query().is_none(), "{:?}", request.url()); - let body: serde_json::Value = - serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - // The name is the path identifier, so the body is the value alone. - assert_eq!(body, serde_json::json!({ "value": "sk-live-0001" })); - http::Response::builder().status(200).body("{}").unwrap() - }); - if call { - conn.create_secret("openai-prod", "sk-live-0001", &[]) - .await - .unwrap(); - } else { - conn.alter_secret("openai-prod", "sk-live-0001", &[]) - .await - .unwrap(); - } - } - } - - #[tokio::test] - async fn test_list_secrets_walks_pages_and_returns_names_only() { - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.method(), &reqwest::Method::GET); - assert_eq!(request.url().path(), "/v1/namespace/$/secret/list"); - let page = request - .url() - .query_pairs() - .find(|(key, _)| key == "page_token") - .map(|(_, value)| value.into_owned()); - let body = match page.as_deref() { - None => r#"{"secrets":[{"name":"openai-prod"}],"page_token":"p2"}"#, - Some("p2") => r#"{"secrets":[{"name":"hf-prod"}]}"#, - Some(other) => panic!("unexpected page token: {other}"), - }; - http::Response::builder().status(200).body(body).unwrap() - }); - assert_eq!( - conn.list_secrets(&[], Default::default()) - .try_collect::>() - .await - .unwrap(), - vec!["openai-prod".to_string(), "hf-prod".to_string()] - ); - } - - /// A server that keeps handing back the same token would otherwise spin - /// forever. - #[tokio::test] - async fn test_list_secrets_rejects_a_repeated_page_token() { - let conn = Connection::new_with_handler(|_| { - http::Response::builder() - .status(200) - .body(r#"{"secrets":[{"name":"openai-prod"}],"page_token":"same"}"#) - .unwrap() - }); - let error = conn - .list_secrets(&[], Default::default()) - .try_collect::>() - .await - .unwrap_err(); - assert!( - error.to_string().contains("repeated a page_token"), - "{error}" - ); - } - - #[tokio::test] - async fn test_drop_and_describe_address_the_secret_in_the_path() { - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.url().path(), "/v1/secret/openai-prod/drop"); - // Nothing is left to say once the path names the Secret. - assert!(request.body().is_none(), "{:?}", request.body()); - http::Response::builder().status(200).body("{}").unwrap() - }); - conn.drop_secret("openai-prod", &[]).await.unwrap(); - - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.url().path(), "/v1/secret/openai-prod/describe"); - assert!(request.body().is_none(), "{:?}", request.body()); - http::Response::builder() - .status(200) - .body(r#"{"name":"openai-prod","created_at_millis":1,"updated_at_millis":2}"#) - .unwrap() - }); - let info = conn.describe_secret("openai-prod", &[]).await.unwrap(); - assert_eq!(info.name, "openai-prod"); - } - - /// The namespace is part of the identifier the path addresses, joined with - /// the client's configured delimiter the way every other object's is. A - /// root Secret is therefore addressed by its bare name, and a namespaced - /// one by the joined path -- there is no body field either way. - #[tokio::test] - async fn test_a_namespace_path_is_addressed_in_the_path() { - let conn = Connection::new_with_handler(|request| { - assert_eq!( - request.url().path(), - "/v1/secret/prod$vision$openai-prod/drop" - ); - http::Response::builder().status(200).body("{}").unwrap() - }); - conn.drop_secret("openai-prod", &["prod".to_string(), "vision".to_string()]) - .await - .unwrap(); - - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.url().path(), "/v1/secret/openai-prod/drop"); - http::Response::builder().status(200).body("{}").unwrap() - }); - conn.drop_secret("openai-prod", &[]).await.unwrap(); - - // Listing is namespace-scoped, so the namespace is the whole identifier. - let conn = Connection::new_with_handler(|request| { - assert_eq!( - request.url().path(), - "/v1/namespace/prod$vision/secret/list" - ); - http::Response::builder() - .status(200) - .body(r#"{"secrets":[]}"#) - .unwrap() - }); - conn.list_secrets( - &["prod".to_string(), "vision".to_string()], - Default::default(), - ) - .try_collect::>() - .await - .unwrap(); - } - - /// A view description carries the schema in the namespace spec's JSON - /// encoding, so the body a test asserts against is the one that encoding - /// produces rather than a hand-written guess at it. - fn view_description_body(name: &str, namespace: &[&str], query: &str) -> String { - let schema = Schema::new(vec![Field::new("id", DataType::Int32, true)]); - serde_json::json!({ - "name": name, - "namespace": namespace, - "query": query, - "default_database": "db", - "default_namespace": namespace, - "schema": lance_namespace::schema::arrow_schema_to_json(&schema).unwrap(), - }) - .to_string() - } - - #[tokio::test] - async fn test_create_view_posts_the_query_and_returns_the_resolved_schema() { - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.method(), &reqwest::Method::POST); - assert_eq!(request.url().path(), "/v1/view/analytics$adults/create"); - let body: serde_json::Value = - serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - // The name and its namespace address the view in the path, so the - // body says only what they cannot. - assert_eq!(body, serde_json::json!({"query": "SELECT id FROM people"})); - http::Response::builder() - .status(200) - .body(view_description_body( - "adults", - &["analytics"], - "SELECT id FROM people", - )) - .unwrap() - }); - let view = conn - .create_view("adults", "SELECT id FROM people", &["analytics".into()]) - .await - .unwrap(); - assert_eq!(view.name, "adults"); - assert_eq!(view.namespace_path, vec!["analytics".to_string()]); - assert_eq!(view.query, "SELECT id FROM people"); - assert_eq!(view.default_database, "db"); - assert_eq!(view.default_namespace_path, vec!["analytics".to_string()]); - assert_eq!(view.schema.field(0).name(), "id"); - } - - #[tokio::test] - async fn test_describe_and_drop_address_the_view_in_the_path() { - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.url().path(), "/v1/view/adults/describe"); - assert!(request.body().is_none(), "{:?}", request.body()); - http::Response::builder() - .status(200) - .body(view_description_body( - "adults", - &[], - "SELECT id FROM people", - )) - .unwrap() - }); - let view = conn.describe_view("adults", &[]).await.unwrap(); - assert!(view.namespace_path.is_empty()); - assert_eq!(view.schema.fields().len(), 1); - - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.method(), &reqwest::Method::POST); - assert_eq!(request.url().path(), "/v1/view/analytics$adults/drop"); - assert!(request.body().is_none(), "{:?}", request.body()); - http::Response::builder().status(200).body("{}").unwrap() - }); - conn.drop_view("adults", &["analytics".into()]) - .await - .unwrap(); - } - - /// An accepted drop hands back the job so a caller can wait on the delete, - /// and the waiting `drop_view` does that for them. - #[tokio::test] - async fn test_drop_view_async_reports_the_cleanup_job() { - let db = super::RemoteDatabase::new_mock(|_| { - http::Response::builder() - .status(202) - .body(r#"{"job_id":"j1-do-abc"}"#) - .unwrap() - }); - let job = db.drop_view_async("adults", &[]).await.unwrap(); - assert_eq!(job.id(), Some("j1-do-abc")); - } - - /// Nothing was bound, so nothing is being deleted and the job is already done. - #[tokio::test] - async fn test_drop_view_async_reports_a_finished_job_when_nothing_was_bound() { - let db = super::RemoteDatabase::new_mock(|_| { - http::Response::builder().status(200).body("{}").unwrap() - }); - let job = db.drop_view_async("adults", &[]).await.unwrap(); - assert_eq!(job.id(), None); - assert_eq!(job.status().await.unwrap(), "finished"); - job.wait().await.unwrap(); - } - - #[tokio::test] - async fn test_drop_view_rejects_incomplete_acceptance() { - for body in ["{}", r#"{"job_id":""}"#, r#"{"job_id":null}"#] { - let db = super::RemoteDatabase::new_mock(move |_| { - http::Response::builder().status(202).body(body).unwrap() - }); - let error = db.drop_view_async("adults", &[]).await.err().unwrap(); - assert!(error.to_string().contains("valid job_id"), "{error}"); - } - } - - #[tokio::test] - async fn test_drop_view_rejects_unexpected_success_status() { - let db = super::RemoteDatabase::new_mock(|_| { - http::Response::builder().status(204).body("").unwrap() - }); - let error = db.drop_view_async("adults", &[]).await.err().unwrap(); - assert!( - error.to_string().contains("200 OK or 202 Accepted"), - "{error}" - ); - } - - /// A schema the client cannot decode is a broken response, not a view - /// with no columns: reporting it as an error keeps a caller from reading - /// an empty schema as the truth about the view. - #[tokio::test] - async fn test_describe_view_rejects_an_undecodable_schema() { - let conn = Connection::new_with_handler(|_| { - http::Response::builder() - .status(200) - .body( - r#"{"name":"adults","query":"SELECT 1","default_database":"db", - "schema":{"fields":[{"name":"id","type":{"type":"nonesuch"}, - "nullable":true}]}}"#, - ) - .unwrap() - }); - let error = conn.describe_view("adults", &[]).await.unwrap_err(); - assert!(error.to_string().contains("undecodable schema"), "{error}"); - } - - #[tokio::test] - async fn test_list_views_walks_pages() { - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.method(), &reqwest::Method::GET); - assert_eq!(request.url().path(), "/v1/namespace/analytics/view/list"); - let page = request - .url() - .query_pairs() - .find(|(key, _)| key == "page_token") - .map(|(_, value)| value.into_owned()); - let body = match page.as_deref() { - None => r#"{"views":[],"page_token":"p2"}"#, - Some("p2") => r#"{"views":["adults"]}"#, - Some(other) => panic!("unexpected page token: {other}"), - }; - http::Response::builder().status(200).body(body).unwrap() - }); - assert_eq!( - conn.list_views(&["analytics".into()], Default::default()) - .try_collect::>() - .await - .unwrap(), - vec!["adults".to_string()] - ); - } - - /// A server that keeps handing back the same token would otherwise spin - /// forever. - #[tokio::test] - async fn test_list_views_rejects_a_repeated_page_token() { - let conn = Connection::new_with_handler(|_| { - http::Response::builder() - .status(200) - .body(r#"{"views":["adults"],"page_token":"same"}"#) - .unwrap() - }); - let error = conn - .list_views(&[], Default::default()) - .try_collect::>() - .await - .unwrap_err(); - assert!( - error.to_string().contains("repeated a page_token"), - "{error}" - ); - } - - /// A name carrying the delimiter would split back apart as a different - /// view, so it is refused before it reaches a route. - #[tokio::test] - async fn test_view_names_that_would_resplit_are_refused() { - let conn = Connection::new_with_handler(|_| -> http::Response { - panic!("an invalid identifier must not reach the service") - }); - for (name, namespace) in [ - ("analytics$adults", vec![]), - ("adults", vec!["ana$lytics".to_string()]), - ("", vec![]), - ("..", vec![]), - ] { - let error = match conn.describe_view(name, &namespace).await { - Ok(_) => panic!("accepted {name:?} in {namespace:?}"), - Err(error) => error.to_string(), - }; - // A view is not a table, so the refusal says so. - assert!( - error.contains("view name") || error.contains("namespace component"), - "{error}" - ); - } - } - - #[tokio::test] - async fn test_create_function_async_sends_canonical_request_and_decodes_typed_job() { - const REQUEST: &str = include_str!( - "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" - ); - const FUNCTION_JOB: &str = - include_str!("../../tests/fixtures/first_class_functions/v1/remote_function_job.json"); - let mut expected: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); - expected.as_object_mut().unwrap().remove("name"); - let conn = Connection::new_with_handler(move |request| match request.url().path() { - "/v1/function/normalize_score/create" => { - assert_eq!(request.method(), &reqwest::Method::POST); - let body: serde_json::Value = - serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - assert_eq!(body, expected); - http::Response::builder() - .status(202) - .body(r#"{"job_id":"job-function-1"}"#) - .unwrap() - } - "/v1/jobs/describe" => http::Response::builder() - .status(200) - .body(FUNCTION_JOB) - .unwrap(), - path => panic!("unexpected path: {path}"), - }); - let request = crate::function::FunctionRegistrationRequest::from_json(REQUEST).unwrap(); - let job = conn.create_function_async(request, &[]).await.unwrap(); - assert_eq!(job.id(), Some("job-function-1")); - let version = job.wait().await.unwrap(); - assert_eq!(version.name(), "embed"); - assert_eq!(version.version(), "1"); - } - - #[tokio::test] - async fn test_get_function_requires_and_sends_exact_version() { - const VERSION: &str = include_str!( - "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" - ); - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.method(), &reqwest::Method::POST); - assert_eq!(request.url().path(), "/v1/function/embed/describe"); - let body: serde_json::Value = - serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - assert_eq!(body, serde_json::json!({"version": "1"})); - http::Response::builder().status(200).body(VERSION).unwrap() - }); - let version = conn.get_function("embed", "1", &[]).await.unwrap(); - assert_eq!(version.name(), "embed"); - assert_eq!(version.version(), "1"); - } - - #[tokio::test] - async fn test_list_functions_requests_definitions_and_paginates() { - const VERSION: &str = include_str!( - "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" - ); - let version: serde_json::Value = serde_json::from_str(VERSION).unwrap(); - let page = Arc::new(AtomicUsize::new(0)); - let conn = Connection::new_with_handler(move |request| { - assert_eq!(request.method(), &reqwest::Method::GET); - assert_eq!(request.url().path(), "/v1/namespace/$/function/list"); - let query = request.url().query_pairs().collect::>(); - assert_eq!(query.get("include_definition").unwrap(), "true"); - match page.fetch_add(1, Ordering::SeqCst) { - 0 => { - assert!(!query.contains_key("page_token")); - http::Response::builder() - .status(200) - .body(r#"{"functions": [], "page_token": "next"}"#.to_string()) - .unwrap() - } - _ => { - assert_eq!(query.get("page_token").unwrap(), "next"); - http::Response::builder() - .status(200) - .body( - serde_json::json!({ - "functions": [{ - "name": "embed", - "version": "1", - "definition": version.clone(), - }], - }) - .to_string(), - ) - .unwrap() - } - } - }); - let functions = conn - .list_functions(&[], Default::default()) - .try_collect::>() - .await - .unwrap(); - assert_eq!(functions.len(), 1); - assert_eq!(functions[0].name(), "embed"); - assert_eq!(functions[0].version(), "1"); - } - - #[tokio::test] - async fn test_list_functions_stops_on_an_empty_page_token() { - let requests = Arc::new(AtomicUsize::new(0)); - let seen = requests.clone(); - let conn = Connection::new_with_handler(move |request| { - seen.fetch_add(1, Ordering::SeqCst); - assert_eq!(request.method(), &reqwest::Method::GET); - assert_eq!(request.url().path(), "/v1/namespace/$/function/list"); - let query = request.url().query_pairs().collect::>(); - assert_eq!(query.get("include_definition").unwrap(), "true"); - assert!(!query.contains_key("page_token")); - http::Response::builder() - .status(200) - .body(r#"{"functions": [], "page_token": ""}"#) - .unwrap() - }); - - let functions = conn - .list_functions(&[], Default::default()) - .try_collect::>() - .await - .unwrap(); - assert!(functions.is_empty()); - assert_eq!(requests.load(Ordering::SeqCst), 1); - } - - #[tokio::test] - async fn test_list_functions_rejects_a_page_token_cycle() { - let page = Arc::new(AtomicUsize::new(0)); - let requests = page.clone(); - let conn = Connection::new_with_handler(move |request| { - assert_eq!(request.method(), &reqwest::Method::GET); - assert_eq!(request.url().path(), "/v1/namespace/$/function/list"); - let query = request.url().query_pairs().collect::>(); - assert_eq!(query.get("include_definition").unwrap(), "true"); - let next_page_token = match page.fetch_add(1, Ordering::SeqCst) { - 0 => { - assert!(!query.contains_key("page_token")); - "one" - } - 1 => { - assert_eq!(query.get("page_token").unwrap(), "one"); - "two" - } - 2 => { - assert_eq!(query.get("page_token").unwrap(), "two"); - "one" - } - page => panic!("unexpected page: {page}"), - }; - http::Response::builder() - .status(200) - .body( - serde_json::json!({ - "functions": [], - "page_token": next_page_token, - }) - .to_string(), - ) - .unwrap() - }); - - let mut items = conn.list_functions(&[], Default::default()); - let error = (&mut items).try_collect::>().await.unwrap_err(); - assert!( - matches!(&error, Error::Runtime { message } if message.contains("repeated a page_token")), - "got {error:?}" - ); - assert!(items.page_token().is_some()); - assert!(items.try_next().await.unwrap().is_none()); - assert_eq!(requests.load(Ordering::SeqCst), 3); - } - - #[tokio::test] - async fn test_drop_function_sends_exact_version_and_decodes_replay() { - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.method(), &reqwest::Method::POST); - assert_eq!(request.url().path(), "/v1/function/embed/drop"); - let body: serde_json::Value = - serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - assert_eq!(body, serde_json::json!({"version": "1"})); - http::Response::builder() - .status(200) - .body(r#"{"dropped":false}"#) - .unwrap() - }); - assert!(!conn.drop_function("embed", "1", &[]).await.unwrap()); - } - - /// A Function's namespace is addressed in the path the way a Secret's is: - /// every route takes the joined identifier and no body carries the - /// namespace, so a namespaced request differs from a root one only in its - /// path. - #[tokio::test] - async fn test_a_function_namespace_path_is_addressed_in_the_path() { - const REQUEST: &str = include_str!( - "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" - ); - const VERSION: &str = include_str!( - "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" - ); - let namespace = ["analytics".to_string(), "features".to_string()]; - let mut expected_create: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); - expected_create.as_object_mut().unwrap().remove("name"); - let conn = Connection::new_with_handler(move |request| { - let body = request - .body() - .and_then(|body| body.as_bytes()) - .map(|bytes| serde_json::from_slice::(bytes).unwrap()); - match request.url().path() { - "/v1/function/analytics$features$normalize_score/create" => { - assert_eq!(body.unwrap(), expected_create); - http::Response::builder() - .status(202) - .body(r#"{"job_id":"job-function-1"}"#.to_string()) - .unwrap() - } - "/v1/function/analytics$features$embed/describe" => { - assert_eq!(body.unwrap(), serde_json::json!({"version": "1"})); - http::Response::builder() - .status(200) - .body(VERSION.to_string()) - .unwrap() - } - "/v1/function/analytics$features$embed/drop" => { - assert_eq!(body.unwrap(), serde_json::json!({"version": "1"})); - http::Response::builder() - .status(200) - .body(r#"{"dropped":true}"#.to_string()) - .unwrap() - } - // Listing is namespace-scoped, so the namespace is the whole - // identifier. - "/v1/namespace/analytics$features/function/list" => http::Response::builder() - .status(200) - .body(r#"{"functions":[]}"#.to_string()) - .unwrap(), - path => panic!("unexpected path: {path}"), - } - }); - let request = crate::function::FunctionRegistrationRequest::from_json(REQUEST).unwrap(); - let job = conn - .create_function_async(request, &namespace) - .await - .unwrap(); - assert_eq!(job.id(), Some("job-function-1")); - conn.get_function("embed", "1", &namespace).await.unwrap(); - assert!( - conn.list_functions(&namespace, Default::default()) - .try_collect::>() - .await - .unwrap() - .is_empty() - ); - assert!(conn.drop_function("embed", "1", &namespace).await.unwrap()); - } - - /// Each namespace segment is checked before a request is built, so an - /// empty segment cannot collapse the identifier onto the parent namespace. - #[tokio::test] - async fn test_an_unaddressable_function_namespace_segment_is_refused() { - let conn = Connection::new_with_handler(|request| -> http::Response { - panic!("reached the transport: {}", request.url().path()) - }); - let namespace = ["analytics".to_string(), String::new()]; - assert!(conn.get_function("embed", "1", &namespace).await.is_err()); - assert!( - conn.list_functions(&namespace, Default::default()) - .try_collect::>() - .await - .is_err() - ); - assert!(conn.drop_function("embed", "1", &namespace).await.is_err()); - } - #[tokio::test] async fn test_conn_job_waits_to_done() { let polls = Arc::new(AtomicUsize::new(0)); @@ -5017,4 +4516,270 @@ mod tests { assert_eq!(job.status().await.unwrap(), "finished"); assert!(polls.load(Ordering::SeqCst) >= 4); } + #[tokio::test] + async fn test_create_materialized_view_validates_before_submission() { + let db = super::RemoteDatabase::new_mock(|_| -> http::Response { + panic!("materialized-view creation must not send REST requests") + }); + for seconds in [0.0, -1.0, f64::NAN, f64::INFINITY] { + let result = db + .create_materialized_view_async(CreateMaterializedViewRequest { + name: "adults".into(), + namespace_path: vec![], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: Some(seconds), + }) + .await; + assert!(matches!(result, Err(Error::InvalidInput { .. }))); + } + } + + /// The node table names its properties and the edge table leaves them + /// out, which means every column. + fn social_graph() -> PropertyGraphDefinition { + PropertyGraphDefinition { + nodes: vec![NodeTable::new("person", "person_id", "Person").properties(["name"])], + edges: vec![EdgeTable::new( + "knows", + "KNOWS", + Endpoint::new("src_id", "person", "person_id"), + Endpoint::new("dst_id", "person", "person_id"), + )], + } + } + + /// `social_graph` as create resolves it: each table's properties listed, + /// the key and endpoint columns among them. + fn resolved_social_graph() -> PropertyGraphDefinition { + let mut graph = social_graph(); + graph.nodes[0].properties = Some(vec!["person_id".into(), "name".into()]); + graph.edges[0].properties = Some(vec!["src_id".into(), "dst_id".into(), "since".into()]); + graph + } + + fn property_graph_body(name: &str, namespace: &[&str]) -> String { + let mut body = serde_json::to_value(resolved_social_graph()).unwrap(); + let fields = body.as_object_mut().unwrap(); + fields.insert("name".into(), name.into()); + fields.insert("namespace".into(), namespace.into()); + body.to_string() + } + + #[tokio::test] + async fn test_create_property_graph_posts_the_definition_and_returns_the_resolved_one() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::POST); + assert_eq!( + request.url().path(), + "/v1/property_graph/analytics$social/create" + ); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + // The name and its namespace address the graph in the path, so the + // body is the definition alone. + assert_eq!( + body, + serde_json::json!({ + "nodes": [{"table": "person", "key": "person_id", "label": "Person", + "properties": ["name"]}], + "edges": [{"table": "knows", "label": "KNOWS", + "source": {"column": "src_id", + "references": {"table": "person", + "column": "person_id"}}, + "destination": {"column": "dst_id", + "references": {"table": "person", + "column": "person_id"}}}] + }) + ); + http::Response::builder() + .status(200) + .body(property_graph_body("social", &["analytics"])) + .unwrap() + }); + let graph = conn + .create_property_graph("social", &social_graph(), &["analytics".into()]) + .await + .unwrap(); + assert_eq!(graph.name, "social"); + assert_eq!(graph.namespace_path, vec!["analytics".to_string()]); + assert_eq!(graph.definition, resolved_social_graph()); + } + + #[tokio::test] + async fn test_describe_and_drop_address_the_property_graph_in_the_path() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::POST); + assert_eq!(request.url().path(), "/v1/property_graph/social/describe"); + assert_eq!(request.body().unwrap().as_bytes().unwrap(), b"{}"); + http::Response::builder() + .status(200) + .body(property_graph_body("social", &[])) + .unwrap() + }); + let graph = conn.describe_property_graph("social", &[]).await.unwrap(); + assert!(graph.namespace_path.is_empty()); + assert_eq!(graph.definition, resolved_social_graph()); + + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::POST); + assert_eq!( + request.url().path(), + "/v1/property_graph/analytics$social/drop" + ); + assert!(request.body().is_none(), "{:?}", request.body()); + http::Response::builder().status(200).body("{}").unwrap() + }); + conn.drop_property_graph("social", &["analytics".into()]) + .await + .unwrap(); + } + + /// An accepted drop hands back the job deleting the definition, and the + /// waiting `drop_property_graph` waits on it. + #[tokio::test] + async fn test_drop_property_graph_waits_for_the_cleanup_job() { + let db = super::RemoteDatabase::new_mock(|_| { + http::Response::builder() + .status(202) + .body(r#"{"job_id":"j1-pg-drop"}"#) + .unwrap() + }); + let job = db.drop_property_graph_async("social", &[]).await.unwrap(); + assert_eq!(job.id(), Some("j1-pg-drop")); + + let requests = Arc::new(AtomicUsize::new(0)); + let conn = Connection::new_with_handler({ + let requests = requests.clone(); + move |request| match ( + requests.fetch_add(1, Ordering::SeqCst), + request.url().path(), + ) { + (0, "/v1/property_graph/social/drop") => http::Response::builder() + .status(202) + .body(r#"{"job_id":"j1-pg-drop"}"#) + .unwrap(), + (1, "/v1/jobs/describe") => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body, serde_json::json!({"job_id": "j1-pg-drop"})); + http::Response::builder() + .status(200) + .body(r#"{"job_id":"j1-pg-drop","job_state":"DONE"}"#) + .unwrap() + } + (n, path) => panic!("unexpected request {n}: {path}"), + } + }); + conn.drop_property_graph("social", &[]).await.unwrap(); + assert_eq!(requests.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_drop_property_graph_rejects_an_unexpected_response() { + let db = super::RemoteDatabase::new_mock(|_| { + http::Response::builder().status(200).body("{}").unwrap() + }); + let job = db.drop_property_graph_async("social", &[]).await.unwrap(); + assert_eq!(job.id(), None); + job.wait().await.unwrap(); + + for (status, body, expected) in [ + (202, "{}", "valid job_id"), + (202, r#"{"job_id":""}"#, "valid job_id"), + (204, "", "200 OK or 202 Accepted"), + ] { + let db = super::RemoteDatabase::new_mock(move |_| { + http::Response::builder().status(status).body(body).unwrap() + }); + let error = db + .drop_property_graph_async("social", &[]) + .await + .err() + .unwrap(); + assert!(error.to_string().contains(expected), "{error}"); + } + } + + /// A graph the database does not hold is the service's 404, kept as the + /// status of the error so a caller can tell it from a refused request. + #[tokio::test] + async fn test_a_missing_property_graph_reports_not_found() { + let conn = Connection::new_with_handler(|_| { + http::Response::builder() + .status(404) + .body("property graph 'social' not found") + .unwrap() + }); + let not_found = |error: Error| { + assert!( + matches!( + error, + Error::Http { + status_code: Some(http::StatusCode::NOT_FOUND), + .. + } + ), + "{error:?}" + ); + }; + not_found( + conn.describe_property_graph("social", &[]) + .await + .unwrap_err(), + ); + not_found(conn.drop_property_graph("social", &[]).await.unwrap_err()); + } + + #[tokio::test] + async fn test_list_property_graphs_walks_pages() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/namespace/$/property_graph/list"); + let page = request + .url() + .query_pairs() + .find(|(key, _)| key == "page_token") + .map(|(_, value)| value.into_owned()); + let body = match page.as_deref() { + None => r#"{"property_graphs":["social"],"page_token":"p2"}"#, + Some("p2") => r#"{"property_graphs":["payments"]}"#, + Some(other) => panic!("unexpected page token: {other}"), + }; + http::Response::builder().status(200).body(body).unwrap() + }); + assert_eq!( + conn.list_property_graphs(&[], Default::default()) + .try_collect::>() + .await + .unwrap(), + vec!["social".to_string(), "payments".to_string()] + ); + } + + /// A name carrying the delimiter would split back apart as a different + /// graph, so it is refused before it reaches a route. + #[tokio::test] + async fn test_property_graph_names_that_would_resplit_are_refused() { + let conn = Connection::new_with_handler(|_| -> http::Response { + panic!("an invalid identifier must not reach the service") + }); + for (name, namespace) in [ + ("analytics$social", vec![]), + ("social", vec!["ana$lytics".to_string()]), + ("", vec![]), + ("..", vec![]), + ] { + let error = match conn.describe_property_graph(name, &namespace).await { + Ok(_) => panic!("accepted {name:?} in {namespace:?}"), + Err(error) => error.to_string(), + }; + assert!( + error.contains("property graph name") || error.contains("namespace component"), + "{error}" + ); + } + } } diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 7d2e70ac9..0c652a3ae 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -13,7 +13,7 @@ use serde::Deserialize; use crate::database::JobDescription; use crate::error::{Error, JobFailure, Result}; -use crate::job::{JobEventsRequest, JobHandle, TerminalResult}; +use crate::job::{JobEventsRequest, JobHandle, JobProgressCallback, TerminalResult}; use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; /// Delay before the second job-state poll; doubles up to [`MAX_POLL_INTERVAL`]. @@ -67,14 +67,18 @@ pub(super) fn job_state_to_client(state: &str) -> String { /// The server's account of why a job failed. Absent from older servers, which /// report only the terminal state. -#[derive(Deserialize)] +#[derive(Clone, Deserialize)] pub(super) struct ReportedFailure { #[serde(default)] phase: Option, #[serde(default)] message: Option, #[serde(default)] + traceback: Option, + #[serde(default)] retryable: Option, + #[serde(default)] + sql_job_id: Option, } /// Forward-compatible `/v1/jobs/pause` wire envelope. @@ -100,7 +104,7 @@ pub(super) struct ResumeJobResponse { } /// Forward-compatible `/v1/jobs/describe` wire envelope. -#[derive(Deserialize)] +#[derive(Clone, Deserialize)] pub(super) struct DescribeJobResponse { #[serde(default)] pub(super) job_id: String, @@ -110,6 +114,16 @@ pub(super) struct DescribeJobResponse { #[serde(default)] pub(super) creation_ms: i64, #[serde(default)] + pub(super) progress: Option, + #[serde(default)] + pub(super) phase: Option, + #[serde(default)] + pub(super) queue_reason: Option, + #[serde(default)] + pub(super) waiting_for_job_id: Option, + #[serde(default)] + pub(super) paused_at_millis: Option, + #[serde(default)] pub(super) spec: serde_json::Value, #[serde(default)] pub(super) result: Option, @@ -122,7 +136,9 @@ impl ReportedFailure { JobFailure { phase: self.phase, message: self.message, + traceback: self.traceback, retryable: self.retryable, + sql_job_id: self.sql_job_id, source: None, } } @@ -144,6 +160,11 @@ impl DescribeJobResponse { job_type: self.job_type, state: JobState::from(self.job_state.as_str()).client_label(), creation_ms: self.creation_ms, + progress: self.progress, + phase: self.phase, + queue_reason: self.queue_reason, + waiting_for_job_id: self.waiting_for_job_id, + paused_at_millis: self.paused_at_millis, spec: self.spec, result: self.result, failure: self.failure.map(ReportedFailure::into_job_failure), @@ -226,18 +247,34 @@ impl JobHandle for RemoteJob { } async fn wait(&self) -> Result { + self.wait_with_progress(None).await + } + + async fn wait_with_progress( + &self, + progress: Option, + ) -> Result { let mut interval = INITIAL_POLL_INTERVAL; loop { let (request_id, description) = self.fetch_description().await?; + if let Some(progress) = &progress { + if let Ok(mut callback) = progress.lock() { + callback(&description.clone().into_description()); + } else { + log::warn!("job {} progress callback lock was poisoned", self.job_id); + } + } match description.state() { JobState::Done => return Ok(description.into_terminal_result(request_id)), JobState::Failed => { return Err(Error::JobFailed { job_id: Some(self.job_id.clone()), - failure: description - .failure - .map(ReportedFailure::into_job_failure) - .unwrap_or_default(), + failure: Box::new( + description + .failure + .map(ReportedFailure::into_job_failure) + .unwrap_or_default(), + ), }); } JobState::Cancelled => { @@ -270,15 +307,15 @@ impl JobHandle for RemoteJob { #[cfg(test)] mod tests { - use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex}; use std::time::Duration; use async_trait::async_trait; use crate::Result; use crate::function::{FunctionVersion, RefreshColumnResult}; - use crate::job::{Job, JobHandle, TerminalResult}; + use crate::job::{Job, JobHandle, JobProgressCallback, TerminalResult}; use crate::remote::client::test_utils::client_with_handler; use super::{DescribeJobResponse, RemoteJob}; @@ -371,4 +408,112 @@ mod tests { serde_json::from_str(FUNCTION_JOB).expect("function job fixture"); assert_eq!(response.job_state, "DONE"); } + + #[test] + fn describe_decodes_progress_queue_and_pause_fields() { + let response: DescribeJobResponse = serde_json::from_str( + r#"{ + "job_id":"job-1", + "job_type":"refresh_column", + "job_state":"IN_PROGRESS", + "creation_ms":10, + "progress":{"rows_planned":10,"rows_computed":4}, + "phase":"initializing", + "queue_reason":"waiting for capacity", + "waiting_for_job_id":"job-0", + "paused_at_millis":20 + }"#, + ) + .expect("progress fields"); + let description = response.into_description(); + let snapshot = description.progress_snapshot(); + assert_eq!(snapshot["state"], "running"); + assert_eq!(snapshot["phase"], "initializing"); + assert_eq!(snapshot["rows_planned"], 10); + assert_eq!(snapshot["rows_computed"], 4); + assert_eq!(snapshot["queue_reason"], "waiting for capacity"); + assert_eq!(snapshot["waiting_for_job_id"], "job-0"); + assert_eq!(snapshot["paused"], true); + assert_eq!(snapshot["paused_at_millis"], 20); + } + + #[test] + fn describe_progress_reports_stable_unpaused_state() { + let response: DescribeJobResponse = serde_json::from_str( + r#"{ + "job_id":"job-1", + "job_type":"refresh_column", + "job_state":"IN_PROGRESS", + "creation_ms":10 + }"#, + ) + .expect("job description"); + let snapshot = response.into_description().progress_snapshot(); + assert_eq!(snapshot["paused"], false); + assert!(snapshot.get("paused_at_millis").is_none()); + } + + #[tokio::test(start_paused = true)] + async fn wait_progress_observes_the_existing_poll_loop() { + let describes = Arc::new(AtomicUsize::new(0)); + let seen = describes.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + let n = seen.fetch_add(1, Ordering::SeqCst); + let body = if n == 0 { + r#"{"job_state":"IN_PROGRESS","job_type":"refresh_column","progress":{"rows_planned":10,"rows_computed":4}}"# + } else { + r#"{"job_state":"DONE","job_type":"refresh_column","progress":{"rows_planned":10,"rows_computed":10},"result":null}"# + }; + http::Response::builder().status(200).body(body).unwrap() + }); + let snapshots = Arc::new(Mutex::new(Vec::new())); + let observed = snapshots.clone(); + let progress: JobProgressCallback = Arc::new(Mutex::new( + move |description: &crate::database::JobDescription| { + observed + .lock() + .expect("snapshot lock") + .push(description.progress_snapshot()); + }, + )); + + RemoteJob::new(client, "job-1".to_string()) + .wait_with_progress(Some(progress)) + .await + .expect("unit job completes"); + + let snapshots = snapshots.lock().expect("snapshot lock"); + assert_eq!(snapshots.len(), 2); + assert_eq!(snapshots[0]["rows_computed"], 4); + assert_eq!(snapshots[1]["state"], "finished"); + assert_eq!(snapshots[1]["rows_computed"], 10); + } + + #[test] + fn reported_failure_fields_are_passed_through() { + let response: DescribeJobResponse = serde_json::from_str( + r#"{ + "job_state":"FAILED", + "failure":{ + "phase":"initialize", + "message":"worker initialization timed out", + "retryable":true, + "sql_job_id":"job-1" + } + }"#, + ) + .expect("failure description"); + let failure = response + .failure + .expect("the wire response has a failure") + .into_job_failure(); + assert_eq!(failure.phase.as_deref(), Some("initialize")); + assert_eq!( + failure.message.as_deref(), + Some("worker initialization timed out") + ); + assert_eq!(failure.retryable, Some(true)); + assert_eq!(failure.sql_job_id.as_deref(), Some("job-1")); + } } diff --git a/rust/lancedb/src/remote/oauth.rs b/rust/lancedb/src/remote/oauth.rs index 95d74274e..e6f7cc37d 100644 --- a/rust/lancedb/src/remote/oauth.rs +++ b/rust/lancedb/src/remote/oauth.rs @@ -157,6 +157,41 @@ impl AuthorizationCodeOptions { } } +/// Options for the OAuth Device Authorization flow. +/// +/// PKCE is disabled by default because it is a provider extension to the device +/// grant. Enable it only when the provider supports and requires S256 PKCE, +/// such as a Keycloak client with a PKCE requirement. There is no automatic +/// fallback to a device request without PKCE. +/// +/// # Example +/// +/// ``` +/// use lancedb::remote::{DeviceCodeOptions, OAuthFlow}; +/// +/// let flow = OAuthFlow::DeviceCode(DeviceCodeOptions::new().use_pkce(true)); +/// ``` +#[derive(Debug, Clone, Default)] +#[non_exhaustive] +pub struct DeviceCodeOptions { + /// Whether to protect the device authorization exchange with S256 PKCE. + /// Defaults to `false`. + pub use_pkce: bool, +} + +impl DeviceCodeOptions { + /// Create device-code options with PKCE disabled. + pub fn new() -> Self { + Self::default() + } + + /// Enable or disable the provider-specific S256 PKCE extension. + pub fn use_pkce(mut self, use_pkce: bool) -> Self { + self.use_pkce = use_pkce; + self + } +} + /// OAuth authentication flow configuration. #[derive(Debug, Clone)] pub enum OAuthFlow { @@ -170,8 +205,9 @@ pub enum OAuthFlow { AuthorizationCode(AuthorizationCodeOptions), /// Device Authorization grant for CLI and headless environments. The - /// verification URI and user code are written to stderr. - DeviceCode, + /// verification URI and user code are written to stderr. PKCE is disabled + /// by default; see [`DeviceCodeOptions`] for provider-specific options. + DeviceCode(DeviceCodeOptions), /// Azure Managed Identity via IMDS. /// Works on Azure VMs, AKS, App Service, and Azure Functions. @@ -763,7 +799,9 @@ impl OidcClient { ) -> Result { Self::validate_issuer_transport(&issuer_url)?; + // Cargo embeds the package version at compile time; no runtime variable is needed. let http_client = Client::builder() + .user_agent(concat!("LanceDB-Rust-Client/", env!("CARGO_PKG_VERSION"))) .timeout(Duration::from_secs(30)) .redirect(reqwest::redirect::Policy::custom(|attempt| { if oauth_url_uses_secure_transport(attempt.url()) { @@ -1244,17 +1282,29 @@ struct OAuthErrorResponse { struct DeviceCodeSource { oidc: OidcClient, + use_pkce: bool, +} + +struct DeviceAuthorization { + response: StandardDeviceAuthorizationResponse, + verifier: Option, } impl std::fmt::Debug for DeviceCodeSource { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("DeviceCodeSource") .field("oidc", &self.oidc) + .field("use_pkce", &self.use_pkce) .finish() } } impl DeviceCodeSource { + fn with_pkce(mut self, use_pkce: bool) -> Self { + self.use_pkce = use_pkce; + self + } + fn new( issuer_url: String, client_id: String, @@ -1274,10 +1324,11 @@ impl DeviceCodeSource { resource, audience, )?, + use_pkce: false, }) } - async fn request_device_authorization(&self) -> Result { + async fn request_device_authorization(&self) -> Result { let endpoint = self .oidc .get_discovery() @@ -1295,7 +1346,14 @@ impl DeviceCodeSource { .oidc .base_client() .set_device_authorization_url(device_url); + // Device-flow PKCE is a provider extension; send it only when selected. + let pkce = self.use_pkce.then(PkceCodeChallenge::new_random_sha256); let mut request = client.exchange_device_code(); + if let Some((challenge, _)) = &pkce { + request = request + .add_extra_param("code_challenge", challenge.as_str()) + .add_extra_param("code_challenge_method", "S256"); + } for scope in &self.oidc.scopes { request = request.add_scope(Scope::new(scope.clone())); } @@ -1313,17 +1371,20 @@ impl DeviceCodeSource { if let Some(uri) = device.verification_uri_complete() { validate_oauth_url(uri.secret(), "verification_uri_complete")?; } - Ok(device) + Ok(DeviceAuthorization { + response: device, + verifier: pkce.map(|(_, verifier)| verifier), + }) } - async fn poll_for_token( - &self, - device: &StandardDeviceAuthorizationResponse, - ) -> Result { + async fn poll_for_token(&self, device: &DeviceAuthorization) -> Result { let (client, _) = self.oidc.token_client().await?; let mut request = client - .exchange_device_access_token(device) + .exchange_device_access_token(&device.response) .set_max_backoff_interval(Duration::from_secs(10)); + if let Some(verifier) = &device.verifier { + request = request.add_extra_param("code_verifier", verifier.secret()); + } for (name, value) in self.oidc.target_params() { request = request.add_extra_param(name, value); } @@ -1345,13 +1406,17 @@ impl TokenSource for DeviceCodeSource { async fn fetch_token(&self) -> Result { let device = self.request_device_authorization().await?; show_oauth_prompt(&device_prompt( - device.verification_uri().as_str(), - device.user_code().secret(), + device.response.verification_uri().as_str(), + device.response.user_code().secret(), )); let (browser_url, name) = device + .response .verification_uri_complete() .map(|uri| (uri.secret().as_str(), "verification_uri_complete")) - .unwrap_or((device.verification_uri().as_str(), "verification_uri")); + .unwrap_or(( + device.response.verification_uri().as_str(), + "verification_uri", + )); launch_browser(validate_oauth_url(browser_url, name)?); self.poll_for_token(&device).await } @@ -1613,15 +1678,18 @@ pub(crate) fn build_token_source(config: &OAuthConfig) -> Result Box::new(DeviceCodeSource::new( - config.issuer_url.clone(), - config.client_id.clone(), - config.client_secret.clone(), - client_auth_method, - config.scopes.clone(), - config.resource.clone(), - config.audience.clone(), - )?), + OAuthFlow::DeviceCode(options) => Box::new( + DeviceCodeSource::new( + config.issuer_url.clone(), + config.client_id.clone(), + config.client_secret.clone(), + client_auth_method, + config.scopes.clone(), + config.resource.clone(), + config.audience.clone(), + )? + .with_pkce(options.use_pkce), + ), OAuthFlow::AzureManagedIdentity { client_id } => Box::new(AzureImdsSource::new( config.scopes.clone(), client_id.clone(), @@ -2080,6 +2148,19 @@ mod tests { assert!(output.contains("ABCD-EFGH")); } + #[test] + fn test_device_code_options_default_and_pkce() { + assert!(!DeviceCodeOptions::default().use_pkce); + assert!(!DeviceCodeOptions::new().use_pkce); + assert!(DeviceCodeOptions::new().use_pkce(true).use_pkce); + assert!( + !DeviceCodeOptions::new() + .use_pkce(true) + .use_pkce(false) + .use_pkce + ); + } + #[test] fn test_authorization_code_options_default_to_pkce() { let options = AuthorizationCodeOptions::new(); @@ -2629,30 +2710,33 @@ mod tests { #[tokio::test] async fn test_device_authorization_polls_until_success() { - let (issuer_url, token_requests, server) = spawn_device_server().await; - let source = DeviceCodeSource::new( - issuer_url, - "client-id".to_string(), - Some("secret".to_string()), - ClientAuthMethod::ClientSecretBasic, - vec!["openid".to_string()], - None, - None, - ) - .unwrap(); + for use_pkce in [false, true] { + let (issuer_url, token_requests, server) = spawn_device_server(use_pkce).await; + let source = DeviceCodeSource::new( + issuer_url, + "client-id".to_string(), + Some("secret".to_string()), + ClientAuthMethod::ClientSecretBasic, + vec!["openid".to_string()], + None, + None, + ) + .unwrap() + .with_pkce(use_pkce); - let device = source.request_device_authorization().await.unwrap(); - let response = source.poll_for_token(&device).await.unwrap(); + let device = source.request_device_authorization().await.unwrap(); + let response = source.poll_for_token(&device).await.unwrap(); - assert_eq!(response.access_token.secret(), "device-token"); - assert_eq!( - response - .refresh_token() - .map(|token| token.secret().as_str()), - Some("device-refresh") - ); - assert_eq!(token_requests.load(Ordering::SeqCst), 3); - server.await.unwrap(); + assert_eq!(response.access_token.secret(), "device-token"); + assert_eq!( + response + .refresh_token() + .map(|token| token.secret().as_str()), + Some("device-refresh") + ); + assert_eq!(token_requests.load(Ordering::SeqCst), 3); + server.await.unwrap(); + } } #[tokio::test] @@ -3318,7 +3402,7 @@ mod tests { (issuer_url, server) } - async fn spawn_device_server() -> (String, Arc, JoinHandle<()>) { + async fn spawn_device_server(use_pkce: bool) -> (String, Arc, JoinHandle<()>) { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let issuer_url = format!("http://{addr}"); @@ -3326,6 +3410,7 @@ mod tests { let server_token_requests = Arc::clone(&token_requests); let server = tokio::spawn(async move { + let mut challenge = None; for _ in 0..5 { let (mut stream, _) = listener.accept().await.unwrap(); let request = read_http_request(&mut stream).await; @@ -3345,6 +3430,18 @@ mod tests { ); assert!(request.body.contains("scope=openid")); assert!(!request.body.contains("client_secret")); + let form: HashMap = + url::form_urlencoded::parse(request.body.as_bytes()) + .into_owned() + .collect(); + if use_pkce { + assert_eq!(form["code_challenge_method"], "S256"); + assert!(!form.contains_key("code_verifier")); + challenge = Some(form["code_challenge"].clone()); + } else { + assert!(!form.contains_key("code_challenge")); + assert!(!form.contains_key("code_challenge_method")); + } let device = format!( r#"{{"device_code":"device-code","user_code":"ABCD-EFGH","verification_uri":"http://{addr}/verify","verification_uri_complete":"http://{addr}/verify?user_code=ABCD-EFGH","expires_in":60,"interval":1}}"# ); @@ -3359,6 +3456,19 @@ mod tests { )); assert!(request.body.contains("device_code=device-code")); assert!(!request.body.contains("client_secret")); + let form: HashMap = + url::form_urlencoded::parse(request.body.as_bytes()) + .into_owned() + .collect(); + if use_pkce { + let verifier = PkceCodeVerifier::new(form["code_verifier"].clone()); + assert_eq!( + PkceCodeChallenge::from_code_verifier_sha256(&verifier).as_str(), + challenge.as_deref().unwrap() + ); + } else { + assert!(!form.contains_key("code_verifier")); + } let request = server_token_requests.fetch_add(1, Ordering::SeqCst); match request { 0 => { @@ -3449,14 +3559,16 @@ mod tests { (issuer_url, token_requests, server) } - fn test_device_authorization_response( - expires_in: u64, - interval: u64, - ) -> StandardDeviceAuthorizationResponse { - serde_json::from_str(&format!( + fn test_device_authorization_response(expires_in: u64, interval: u64) -> DeviceAuthorization { + let response = serde_json::from_str(&format!( r#"{{"device_code":"device-code","user_code":"ABCD-EFGH","verification_uri":"http://127.0.0.1/verify","expires_in":{expires_in},"interval":{interval}}}"# )) - .unwrap() + .unwrap(); + let (_, verifier) = PkceCodeChallenge::new_random_sha256(); + DeviceAuthorization { + response, + verifier: Some(verifier), + } } async fn spawn_device_error_server(error: &'static str) -> (String, JoinHandle<()>) { @@ -3501,6 +3613,12 @@ mod tests { for _ in 0..3 { let (mut stream, _) = listener.accept().await.unwrap(); let request = read_http_request(&mut stream).await; + assert!( + request + .header("user-agent") + .is_some_and(|value| !value.is_empty()), + "OAuth discovery and token requests must identify the client" + ); if request .line diff --git a/rust/lancedb/src/remote/retry.rs b/rust/lancedb/src/remote/retry.rs index 19aa301e4..51c9b2126 100644 --- a/rust/lancedb/src/remote/retry.rs +++ b/rust/lancedb/src/remote/retry.rs @@ -103,7 +103,12 @@ impl<'a> RetryCounter<'a> { pub fn next_sleep_time(&self) -> Duration { let backoff = self.config.backoff_factor * (2.0f32.powi(self.request_failures as i32)); let jitter = rand::random::() * self.config.backoff_jitter; - let sleep_time = Duration::from_secs_f32(backoff + jitter); + // `Duration::from_secs_f32` panics once the exponential exceeds what a + // `Duration` can hold, which the default backoff factor reaches at 66 + // request failures -- within reach of `retries`, a `u8`. Saturate + // instead: a retry sleep this long is indistinguishable from a hang, + // and the panic it replaces was strictly worse. + let sleep_time = Duration::try_from_secs_f32(backoff + jitter).unwrap_or(MAX_RETRY_SLEEP); debug!( "Retrying request {:?} ({}/{} connect, {}/{} request, {}/{} read) in {:?}", self.request_id, @@ -249,6 +254,240 @@ mod tests { } )); } + /// Resolve against a fixed set of "environment" values, touching no + /// process-global state. + fn resolve_with(cfg: RetryConfig, env: &[(&str, &str)]) -> crate::Result { + let env: std::collections::HashMap = env + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + ResolvedRetryConfig::resolve(cfg, |name| env.get(name).cloned()) + } + + #[test] + fn test_resolve_retry_defaults_when_unset() { + let resolved = resolve_with(RetryConfig::default(), &[]).unwrap(); + + assert_eq!(resolved.retries, 3); + assert_eq!(resolved.connect_retries, 3); + assert_eq!(resolved.read_retries, 3); + assert_eq!(resolved.backoff_factor, 0.25); + assert_eq!(resolved.backoff_jitter, 0.25); + assert_eq!( + resolved.statuses, + vec![ + reqwest::StatusCode::CONFLICT, + reqwest::StatusCode::TOO_MANY_REQUESTS, + reqwest::StatusCode::INTERNAL_SERVER_ERROR, + reqwest::StatusCode::BAD_GATEWAY, + reqwest::StatusCode::SERVICE_UNAVAILABLE, + reqwest::StatusCode::GATEWAY_TIMEOUT, + ] + ); + } + + #[test] + fn test_resolve_retry_from_env() { + let resolved = resolve_with( + RetryConfig::default(), + &[ + ("LANCE_CLIENT_MAX_RETRIES", "7"), + ("LANCE_CLIENT_CONNECT_RETRIES", "5"), + ("LANCE_CLIENT_READ_RETRIES", "0"), + ("LANCE_CLIENT_RETRY_BACKOFF_FACTOR", "1.5"), + ("LANCE_CLIENT_RETRY_BACKOFF_JITTER", "0"), + ("LANCE_CLIENT_RETRY_STATUSES", "500,503"), + ], + ) + .unwrap(); + + assert_eq!(resolved.retries, 7); + assert_eq!(resolved.connect_retries, 5); + assert_eq!(resolved.read_retries, 0); + assert_eq!(resolved.backoff_factor, 1.5); + assert_eq!(resolved.backoff_jitter, 0.0); + assert_eq!( + resolved.statuses, + vec![ + reqwest::StatusCode::INTERNAL_SERVER_ERROR, + reqwest::StatusCode::SERVICE_UNAVAILABLE, + ] + ); + } + + #[test] + fn test_resolve_retry_passed_value_wins_over_env() { + let config = RetryConfig { + retries: Some(1), + backoff_factor: Some(0.5), + statuses: Some(vec![429]), + ..Default::default() + }; + let resolved = resolve_with( + config, + &[ + ("LANCE_CLIENT_MAX_RETRIES", "7"), + ("LANCE_CLIENT_RETRY_BACKOFF_FACTOR", "1.5"), + ("LANCE_CLIENT_RETRY_STATUSES", "500,503"), + ], + ) + .unwrap(); + + assert_eq!(resolved.retries, 1); + assert_eq!(resolved.backoff_factor, 0.5); + assert_eq!( + resolved.statuses, + vec![reqwest::StatusCode::TOO_MANY_REQUESTS] + ); + // Fields left unset still fall through to the default. + assert_eq!(resolved.connect_retries, 3); + } + + #[test] + fn test_resolve_retry_statuses_tolerates_spacing_and_blanks() { + let resolved = resolve_with( + RetryConfig::default(), + &[("LANCE_CLIENT_RETRY_STATUSES", " 429 , 503 ,")], + ) + .unwrap(); + + assert_eq!( + resolved.statuses, + vec![ + reqwest::StatusCode::TOO_MANY_REQUESTS, + reqwest::StatusCode::SERVICE_UNAVAILABLE, + ] + ); + } + + #[test] + fn test_resolve_retry_statuses_empty_env_disables() { + let resolved = resolve_with( + RetryConfig::default(), + &[("LANCE_CLIENT_RETRY_STATUSES", "")], + ) + .unwrap(); + + assert!(resolved.statuses.is_empty()); + } + + /// Every invalid value is rejected, and the message names both the + /// variable the user has to fix and the value they set. + #[rstest::rstest] + #[case("LANCE_CLIENT_MAX_RETRIES", "not-a-number")] + #[case("LANCE_CLIENT_MAX_RETRIES", "300")] + #[case("LANCE_CLIENT_CONNECT_RETRIES", "-1")] + #[case("LANCE_CLIENT_READ_RETRIES", "1.5")] + #[case("LANCE_CLIENT_RETRY_BACKOFF_FACTOR", "not-a-number")] + #[case("LANCE_CLIENT_RETRY_BACKOFF_FACTOR", "-1")] + #[case("LANCE_CLIENT_RETRY_BACKOFF_JITTER", "inf")] + #[case("LANCE_CLIENT_RETRY_STATUSES", "500,not-a-number")] + #[case("LANCE_CLIENT_RETRY_STATUSES", "42")] + fn test_resolve_retry_invalid_env(#[case] var: &str, #[case] value: &str) { + let err = resolve_with(RetryConfig::default(), &[(var, value)]) + .expect_err("expected invalid env var to be rejected"); + + let crate::Error::InvalidInput { message } = &err else { + panic!("expected InvalidInput, got {:?}", err); + }; + assert!( + message.contains(var), + "message should name the env var to fix, got '{}'", + message + ); + assert!( + message.contains(value), + "message should echo the offending value, got '{}'", + message + ); + } + + #[test] + fn test_resolve_retry_rejects_invalid_passed_values() { + // A negative backoff would otherwise produce a nonsensical sleep. + let config = RetryConfig { + backoff_factor: Some(-1.0), + ..Default::default() + }; + assert!(matches!( + resolve_with(config, &[]).unwrap_err(), + crate::Error::InvalidInput { .. } + )); + + // An out-of-range status code would otherwise panic on `unwrap`. + let config = RetryConfig { + statuses: Some(vec![42]), + ..Default::default() + }; + assert!(matches!( + resolve_with(config, &[]).unwrap_err(), + crate::Error::InvalidInput { .. } + )); + } + + /// `retries` is a `u8`, so the exponential in `next_sleep_time` can exceed + /// what a `Duration` holds -- at 66 failures with the default backoff + /// factor. That used to panic. + #[test] + fn test_next_sleep_time_saturates_instead_of_panicking() { + let config = ResolvedRetryConfig { + retries: u8::MAX, + connect_retries: u8::MAX, + read_retries: u8::MAX, + backoff_factor: 0.25, + backoff_jitter: 0.25, + statuses: vec![], + }; + let mut counter = RetryCounter::new(&config, "test".to_string()); + + // Below the overflow point the computed backoff is used as-is. + counter.request_failures = 10; + assert_eq!(counter.next_sleep_time().as_secs(), 256); + + // At and beyond it, the sleep saturates rather than panicking. + for failures in [66, 128, u8::MAX] { + counter.request_failures = failures; + assert_eq!( + counter.next_sleep_time(), + MAX_RETRY_SLEEP, + "should saturate at {} failures", + failures + ); + } + } + + // The two tests below are the only ones that touch process-global + // environment state, so they confirm `try_from` is actually wired to the + // environment. Everything else resolves through an injected lookup. + static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + #[test] + fn test_try_from_reads_the_environment() { + let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: This is only called in tests, under `ENV_MUTEX`. + unsafe { + std::env::set_var("LANCE_CLIENT_MAX_RETRIES", "9"); + } + let resolved: crate::Result = RetryConfig::default().try_into(); + // SAFETY: This is only called in tests, under `ENV_MUTEX`. + unsafe { + std::env::remove_var("LANCE_CLIENT_MAX_RETRIES"); + } + + assert_eq!(resolved.unwrap().retries, 9); + } + + #[test] + fn test_try_from_uses_defaults_when_environment_is_unset() { + let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: This is only called in tests, under `ENV_MUTEX`. + unsafe { + std::env::remove_var("LANCE_CLIENT_MAX_RETRIES"); + } + let resolved: ResolvedRetryConfig = RetryConfig::default().try_into().unwrap(); + + assert_eq!(resolved.retries, 3); + } } #[derive(Debug, Clone)] @@ -261,22 +500,192 @@ pub struct ResolvedRetryConfig { pub statuses: Vec, } +const DEFAULT_RETRIES: u8 = 3; +const DEFAULT_CONNECT_RETRIES: u8 = 3; +const DEFAULT_READ_RETRIES: u8 = 3; +const DEFAULT_BACKOFF_FACTOR: f32 = 0.25; +const DEFAULT_BACKOFF_JITTER: f32 = 0.25; +const DEFAULT_RETRY_STATUSES: [u16; 6] = [409, 429, 500, 502, 503, 504]; + +/// Ceiling for a single retry sleep, applied when the exponential backoff +/// overflows what a `Duration` can represent. Far above any sleep a sane +/// configuration produces -- the default factor and retry count peak at a +/// couple of seconds -- so this only engages where the computation would +/// otherwise have panicked. +const MAX_RETRY_SLEEP: Duration = Duration::from_secs(60 * 60); + +/// Resolve a retry count from the config value, the environment, or a default. +/// +/// An explicit config value always wins; `env` is only consulted when the +/// caller left the field unset. `env_var` names the variable `env` was read +/// from, for error messages. +fn resolve_retries( + passed: Option, + env_var: &str, + env: Option<&str>, + default: u8, +) -> crate::Result { + if let Some(value) = passed { + Ok(value) + } else if let Some(env) = env { + env.trim().parse::().map_err(|_| Error::InvalidInput { + message: format!( + "{} must be an integer between 0 and 255, got '{}'", + env_var, env + ), + }) + } else { + Ok(default) + } +} + +/// Resolve a backoff factor from the config value, the environment, or a +/// default. +/// +/// Negative and non-finite values are rejected here rather than left to +/// produce a nonsensical sleep time later in `next_sleep_time`. +fn resolve_backoff( + passed: Option, + env_var: &str, + env: Option<&str>, + default: f32, +) -> crate::Result { + let value = if let Some(value) = passed { + value + } else if let Some(env) = env { + env.trim().parse::().map_err(|_| Error::InvalidInput { + message: format!( + "{} must be a non-negative number of seconds, got '{}'", + env_var, env + ), + })? + } else { + default + }; + if !value.is_finite() || value < 0.0 { + return Err(Error::InvalidInput { + message: format!( + "{} must be a non-negative, finite number of seconds, got '{}'", + env_var, value + ), + }); + } + Ok(value) +} + +/// Resolve the retryable status codes from the config value, the environment, +/// or a default. +/// +/// The environment value is a comma-separated list of integers; empty entries +/// are ignored, so a blank value disables status-based retries just like +/// passing an empty vector. +fn resolve_statuses( + passed: Option>, + env_var: &str, + env: Option<&str>, +) -> crate::Result> { + // `Some(env_var)` when the values came from the environment, so an + // out-of-range code can point the user at the variable to fix. + let (raw, from_env) = if let Some(statuses) = passed { + (statuses, None) + } else if let Some(env) = env { + let parsed = env + .split(',') + .map(str::trim) + .filter(|part| !part.is_empty()) + .map(|part| { + part.parse::().map_err(|_| Error::InvalidInput { + message: format!( + "{} must be a comma-separated list of integer status codes, got '{}'", + env_var, env + ), + }) + }) + .collect::>>()?; + (parsed, Some(env_var)) + } else { + (DEFAULT_RETRY_STATUSES.to_vec(), None) + }; + + raw.into_iter() + .map(|status| { + reqwest::StatusCode::from_u16(status).map_err(|_| Error::InvalidInput { + message: match from_env { + Some(env_var) => format!( + "{} contains an invalid HTTP status code: '{}'", + env_var, status + ), + None => format!( + "RetryConfig.statuses contains an invalid HTTP status code: '{}'", + status + ), + }, + }) + }) + .collect() +} + +impl ResolvedRetryConfig { + /// Resolve a `RetryConfig`, reading unset fields through `lookup`. + /// + /// The environment is reached only through `lookup`, so tests can exercise + /// every parsing and precedence rule without mutating process-global + /// state that sibling tests read concurrently. + fn resolve( + retry_config: RetryConfig, + lookup: impl Fn(&str) -> Option, + ) -> crate::Result { + let max_retries = lookup("LANCE_CLIENT_MAX_RETRIES"); + let connect_retries = lookup("LANCE_CLIENT_CONNECT_RETRIES"); + let read_retries = lookup("LANCE_CLIENT_READ_RETRIES"); + let backoff_factor = lookup("LANCE_CLIENT_RETRY_BACKOFF_FACTOR"); + let backoff_jitter = lookup("LANCE_CLIENT_RETRY_BACKOFF_JITTER"); + let statuses = lookup("LANCE_CLIENT_RETRY_STATUSES"); + + Ok(Self { + retries: resolve_retries( + retry_config.retries, + "LANCE_CLIENT_MAX_RETRIES", + max_retries.as_deref(), + DEFAULT_RETRIES, + )?, + connect_retries: resolve_retries( + retry_config.connect_retries, + "LANCE_CLIENT_CONNECT_RETRIES", + connect_retries.as_deref(), + DEFAULT_CONNECT_RETRIES, + )?, + read_retries: resolve_retries( + retry_config.read_retries, + "LANCE_CLIENT_READ_RETRIES", + read_retries.as_deref(), + DEFAULT_READ_RETRIES, + )?, + backoff_factor: resolve_backoff( + retry_config.backoff_factor, + "LANCE_CLIENT_RETRY_BACKOFF_FACTOR", + backoff_factor.as_deref(), + DEFAULT_BACKOFF_FACTOR, + )?, + backoff_jitter: resolve_backoff( + retry_config.backoff_jitter, + "LANCE_CLIENT_RETRY_BACKOFF_JITTER", + backoff_jitter.as_deref(), + DEFAULT_BACKOFF_JITTER, + )?, + statuses: resolve_statuses( + retry_config.statuses, + "LANCE_CLIENT_RETRY_STATUSES", + statuses.as_deref(), + )?, + }) + } +} + impl TryFrom for ResolvedRetryConfig { type Error = Error; fn try_from(retry_config: RetryConfig) -> crate::Result { - Ok(Self { - retries: retry_config.retries.unwrap_or(3), - connect_retries: retry_config.connect_retries.unwrap_or(3), - read_retries: retry_config.read_retries.unwrap_or(3), - backoff_factor: retry_config.backoff_factor.unwrap_or(0.25), - backoff_jitter: retry_config.backoff_jitter.unwrap_or(0.25), - statuses: retry_config - .statuses - .unwrap_or_else(|| vec![409, 429, 500, 502, 503, 504]) - .into_iter() - .map(|status| reqwest::StatusCode::from_u16(status).unwrap()) - .collect(), - }) + Self::resolve(retry_config, |name| std::env::var(name).ok()) } } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 880f61045..724c813b3 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -29,14 +29,18 @@ use uuid::Uuid; use crate::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}; use crate::database::ExecuteQueryRequest; -use crate::error::{Error, Result}; +use crate::error::{Error, JobFailure, Result}; use crate::job::Job; use crate::remote::client::{ClientConfig, TlsConfig}; use crate::remote::retry::ResolvedRetryConfig; use crate::sql::{Query, QueryDescription, QueryHandle, QueryStatus}; +mod function; pub(super) mod materialized_view; +mod objects; +mod secret; mod stream; +mod view; use stream::{StreamingQuery, StreamingQueryHandle, Submission}; @@ -47,6 +51,7 @@ const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(300); const STATUS_POLL_TIMEOUT: Duration = Duration::from_secs(1); const MIN_POLL_INTERVAL: Duration = Duration::from_millis(50); 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); const ABANDONED_QUERY_RETENTION: Duration = Duration::from_secs(24 * 60 * 60); @@ -56,6 +61,11 @@ pub(super) struct SqlClient { queries: Arc, } +pub(super) struct SubmittedQuery { + pub(super) query: Query, + pub(super) materialized_view_job_handle_supported: bool, +} + struct SqlClientInner { database: String, database_prefix: Option, @@ -91,7 +101,7 @@ impl ResultEndpointStream { tokio::time::timeout(self.read_timeout, self.stream.try_next()) .await .map_err(|_| sql_error(&self.request_id, "SQL result read timed out"))? - .map_err(|err| sql_error(&self.request_id, err)) + .map_err(|err| sql_flight_error(&self.request_id, &err)) } } @@ -200,24 +210,36 @@ impl SqlClient { } pub(super) async fn execute(&self, request: ExecuteQueryRequest) -> Result { + Ok(self + .execute_with_materialized_view_job_handle(request, false) + .await? + .query) + } + + pub(super) async fn execute_with_materialized_view_job_handle( + &self, + request: ExecuteQueryRequest, + materialized_view_job_handle: bool, + ) -> Result { let timeout = self.inner.overall_timeout()?; with_overall_timeout(timeout, "SQL query submission", async { validate_namespace_path(&request.default_namespace_path)?; let query_id = Uuid::now_v7(); - let submission = StreamingQuery::open( + let opened = StreamingQuery::open( self.inner.clone(), &request.query, request.parameters, &request.default_namespace_path, + materialized_view_job_handle, ) .await?; - match submission { + let query = match opened.submission { Submission::Stream(response) => { let query = Arc::new(StreamingQuery::new(query_id, self.inner.clone(), response)); self.queries .insert(query_id, RegisteredQuery::Streamed(query.clone())); - Ok(Query::new(Arc::new(StreamingQueryHandle::new(query)))) + Query::new(Arc::new(StreamingQueryHandle::new(query))) } Submission::Deferred(poll_info) => { let query = Arc::new(RemoteQuery::new( @@ -228,9 +250,14 @@ impl SqlClient { )?); self.queries .insert(query_id, RegisteredQuery::Polled(query.clone())); - Ok(Query::new(Arc::new(RemoteQueryHandle::new(query)))) + Query::new(Arc::new(RemoteQueryHandle::new(query))) } - } + }; + Ok(SubmittedQuery { + query, + materialized_view_job_handle_supported: opened + .materialized_view_job_handle_supported, + }) }) .await } @@ -283,6 +310,15 @@ impl SqlClient { }) .await?, ); + Ok(self.query_job(query, finish)) + } + + pub(super) fn query_job(&self, query: Arc, finish: F) -> Job + where + T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static, + F: FnOnce() -> Fut + Send + 'static, + Fut: Future> + Send + 'static, + { let query_id = query.id(); let execution = query.clone(); let task = tokio::spawn(async move { @@ -290,10 +326,10 @@ impl SqlClient { while reader.try_next().await?.is_some() {} finish().await }); - Ok(Job::from_query_task(query_id, task, move || { + Job::from_query_task(query_id, task, move || { let query = query.clone(); async move { query.cancel().await } - })) + }) } pub(super) async fn describe(&self, query_id: Uuid) -> Result { @@ -340,7 +376,7 @@ impl SqlClientInner { tokio::time::timeout(read_timeout, client.poll_flight_info(descriptor)) .await .map_err(|_| sql_error(&request_id, "SQL query poll timed out"))? - .map_err(|err| sql_error(&request_id, err)) + .map_err(|err| sql_flight_error(&request_id, &err)) } async fn poll_status( @@ -354,7 +390,9 @@ impl SqlClientInner { .await .map_err(|err| sql_error(&request_id, err))?; match tokio::time::timeout(STATUS_POLL_TIMEOUT, client.poll_flight_info(descriptor)).await { - Ok(result) => result.map(Some).map_err(|err| sql_error(&request_id, err)), + Ok(result) => result + .map(Some) + .map_err(|err| sql_flight_error(&request_id, &err)), Err(_) => Ok(None), } } @@ -398,7 +436,7 @@ impl SqlClientInner { tokio::time::sleep(poll_retry_delay(&retry_config, retry_count)).await; continue; } - Ok(Err(error)) => return Err(sql_error(&request_id, error)), + Ok(Err(error)) => return Err(sql_flight_error(&request_id, &error)), Ok(Ok(poll_info)) => poll_info, }; if let Some(delay) = MIN_POLL_INTERVAL.checked_sub(started.elapsed()) { @@ -429,7 +467,7 @@ impl SqlClientInner { let stream = tokio::time::timeout(read_timeout, endpoint_client.do_get(ticket)) .await .map_err(|_| sql_error(&request_id, "SQL result fetch timed out"))? - .map_err(|err| sql_error(&request_id, err))?; + .map_err(|err| sql_flight_error(&request_id, &err))?; Ok(ResultEndpointStream { stream, request_id, @@ -497,9 +535,9 @@ impl SqlClientInner { } Err(FlightError::Tonic(status)) if !cancellation_status_is_ambiguous(status.code()) => { attempt.resolve(); - return Err(sql_error(&request_id, status)); + return Err(sql_status_error(&request_id, &status)); } - Err(error) => return Err(sql_error(&request_id, error)), + Err(error) => return Err(sql_flight_error(&request_id, &error)), }; let status = CancelStatus::try_from(result.status) .map_err(|_| sql_error(&request_id, "SQL query returned an invalid cancel status"))?; @@ -1597,6 +1635,53 @@ fn sql_error(request_id: &str, error: impl std::fmt::Display) -> Error { } } +pub(super) fn sql_flight_error(request_id: &str, error: &FlightError) -> Error { + match error { + FlightError::Tonic(status) => sql_status_error(request_id, status), + _ => sql_error(request_id, error), + } +} + +pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Error { + let header = |name| { + status + .metadata() + .get(name) + .and_then(|value| value.to_str().ok()) + .filter(|value| !value.is_empty()) + .map(str::to_owned) + }; + let metadata = crate::error::RemoteErrorMetadata { + error_code: header("x-lancedb-error-code"), + job_id: header(SQL_JOB_ID_METADATA_KEY), + job_request_id: header("x-job-request-id"), + resource: header("x-lancedb-resource") + .as_deref() + .and_then(crate::error::parse_flight_resource_identity), + }; + let sql_job_id = metadata.job_id.clone(); + let error = Error::Sql { + message: status.message().into(), + request_id: request_id.into(), + grpc_code: status.code() as i32, + metadata: Box::new(metadata), + }; + if let Some(sql_job_id) = sql_job_id { + return Error::JobFailed { + job_id: Some(sql_job_id.clone()), + failure: Box::new(JobFailure { + phase: None, + message: Some(status.message().into()), + traceback: None, + retryable: None, + sql_job_id: Some(sql_job_id), + source: Some(Arc::new(error)), + }), + }; + } + error +} + #[cfg(test)] #[path = "sql_test.rs"] mod tests; diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs new file mode 100644 index 000000000..e90792a8a --- /dev/null +++ b/rust/lancedb/src/remote/sql/function.rs @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use super::{ + SqlClient, + materialized_view::quote_identifier, + objects::{definition, literal, string_lists, strings}, +}; +use crate::{ + database::ExecuteQueryRequest, + error::{Error, Result}, + function::{FunctionRegistrationRequest, FunctionVersion}, + job::Job, + listing::{ListingOptions, ListingPage}, + utils::{validate_function_name, validate_namespace}, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + +/// The SQL result of one Function drop, before the public boolean wrapper +/// discards the advisory details. +#[derive(Clone, serde::Deserialize, serde::Serialize)] +pub(in crate::remote) struct DropFunctionOutcome { + pub(in crate::remote) dropped: bool, + pub(in crate::remote) warnings: Vec, +} + +impl SqlClient { + pub(in crate::remote) async fn register_function( + &self, + request: FunctionRegistrationRequest, + namespace: &[String], + ) -> Result> { + request.validate()?; + validate_function_name(&request.name)?; + validate_namespace(namespace)?; + let name = quote_identifier(&request.name); + let mut body = serde_json::to_value(request).map_err(|error| Error::Runtime { + message: error.to_string(), + })?; + body.as_object_mut().unwrap().remove("name"); + self.object_job( + ExecuteQueryRequest { + query: format!("CREATE FUNCTION {name} FROM {}", literal(&body.to_string())), + default_namespace_path: namespace.to_vec(), + parameters: None, + }, + definition, + ) + .await + } + pub(in crate::remote) async fn describe_function( + &self, + name: &str, + version: &str, + namespace: &[String], + ) -> Result { + validate_function_name(name)?; + validate_namespace(namespace)?; + self.object_job( + ExecuteQueryRequest { + query: format!( + "DESCRIBE FUNCTION {} WITH (version = {})", + quote_identifier(name), + literal(version) + ), + default_namespace_path: namespace.to_vec(), + parameters: None, + }, + definition, + ) + .await? + .wait() + .await + } + pub(in crate::remote) async fn list_functions( + &self, + namespace: &[String], + options: ListingOptions, + ) -> Result> { + validate_namespace(namespace)?; + let limit = options.page_limit.unwrap_or(100); + if limit == 0 || limit > i32::MAX as u32 { + return Err(Error::InvalidInput { + message: "page limit must be between 1 and i32::MAX".into(), + }); + } + let invalid = || Error::InvalidInput { + message: "invalid function page token for this database or namespace".into(), + }; + let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { + let bytes = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid())?; + let (database, prefix, path, name, version): ( + String, + Option, + Vec, + String, + String, + ) = serde_json::from_slice(&bytes).map_err(|_| invalid())?; + if database != self.inner.database + || prefix != self.inner.database_prefix + || path != namespace + { + return Err(invalid()); + } + Some((name, version)) + } else { + None + }; + let mut sql_options = vec![ + format!("limit = {}", u64::from(limit) + 1), + "include_definition = true".to_owned(), + ]; + if let Some((name, version)) = &after { + sql_options.push(format!("after_name = {}", literal(name))); + sql_options.push(format!("after_version = {}", literal(version))); + } + let mut items: Vec = self + .object_job( + ExecuteQueryRequest { + query: format!("SHOW FUNCTIONS HISTORY WITH ({})", sql_options.join(", ")), + default_namespace_path: namespace.to_vec(), + parameters: None, + }, + |batches| { + strings(&batches, "definition")? + .into_iter() + .map(|value| { + serde_json::from_str(&value).map_err(|error| Error::Runtime { + message: error.to_string(), + }) + }) + .collect::>>() + }, + ) + .await? + .wait() + .await?; + let page_token = if items.len() > limit as usize { + items.truncate(limit as usize); + let last = items.last().unwrap(); + let bytes = serde_json::to_vec(&( + &self.inner.database, + &self.inner.database_prefix, + namespace, + last.name(), + last.version(), + )) + .map_err(|error| Error::Runtime { + message: error.to_string(), + })?; + Some(URL_SAFE_NO_PAD.encode(bytes)) + } else { + None + }; + Ok(ListingPage { items, page_token }) + } + pub(in crate::remote) async fn drop_function_outcome( + &self, + name: &str, + version: &str, + namespace: &[String], + ) -> Result<(DropFunctionOutcome, Job)> { + validate_function_name(name)?; + validate_namespace(namespace)?; + let job = self + .object_job( + ExecuteQueryRequest { + query: format!( + "DROP FUNCTION IF EXISTS {} WITH (version = {})", + quote_identifier(name), + literal(version) + ), + default_namespace_path: namespace.to_vec(), + parameters: None, + }, + |batches| { + let rows = strings(&batches, "status")?; + let dropped = match rows.as_slice() { + [status] if status == "dropped" => true, + [status] if status == "not_found" => false, + _ => { + return Err(Error::Runtime { + message: "invalid DROP FUNCTION result".into(), + }); + } + }; + Ok(DropFunctionOutcome { + dropped, + warnings: string_lists(&batches, "warnings")?, + }) + }, + ) + .await?; + let id = job.id().unwrap().parse().map_err(|_| Error::Runtime { + message: "invalid SQL query job id".into(), + })?; + let outcome = job.wait().await?; + let job = Job::from_query_task(id, tokio::spawn(async { Ok(()) }), || async { Ok(()) }); + Ok((outcome, job)) + } + + pub(in crate::remote) async fn drop_function( + &self, + name: &str, + version: &str, + namespace: &[String], + ) -> Result<(bool, Job)> { + let (outcome, job) = self.drop_function_outcome(name, version, namespace).await?; + Ok((outcome.dropped, job)) + } +} diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index 46c0a7bd2..4eaad5156 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -1,15 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use std::sync::Arc; + use arrow_array::{Array, RecordBatch, StringArray}; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::TryStreamExt; use super::SqlClient; +use crate::arrow::SendableRecordBatchStream; use crate::database::ExecuteQueryRequest; use crate::error::{Error, Result}; use crate::listing::{ListingOptions, ListingPage}; use crate::materialized_view::{MaterializedViewDefinition, MaterializedViewInfo}; +use crate::sql::Query; use crate::utils::{validate_namespace, validate_table_name}; pub(in crate::remote) fn quote_identifier(name: &str) -> String { @@ -34,7 +38,75 @@ fn strings(batch: &RecordBatch, name: &str) -> Result> { .collect()) } +pub(in crate::remote) enum MaterializedViewJobSubmission { + Registry { job_id: String }, + Query(Arc), +} + impl SqlClient { + pub(in crate::remote) async fn submit_materialized_view_job( + &self, + statement: String, + namespace: Vec, + ) -> Result { + let submitted = self + .execute_with_materialized_view_job_handle( + ExecuteQueryRequest { + query: statement, + default_namespace_path: namespace, + parameters: None, + }, + true, + ) + .await?; + let query = Arc::new(submitted.query); + if !submitted.materialized_view_job_handle_supported { + return Ok(MaterializedViewJobSubmission::Query(query)); + } + let mut reader: SendableRecordBatchStream = query.reader().await?; + let mut rows = 0; + let mut registry_job_id = None; + while let Some(batch) = reader.try_next().await? { + rows += batch.num_rows(); + if rows > 1 { + return Err(Error::Runtime { + message: "materialized-view submission must return exactly one status row" + .into(), + }); + } + if let Some(column) = batch.column_by_name("job_id") { + let values = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "materialized-view submission job_id is not UTF-8".into(), + })?; + if values.null_count() != 0 { + return Err(Error::Runtime { + message: "materialized-view submission contains a null job_id".into(), + }); + } + if values.is_empty() { + continue; + } + let value = values.value(0); + if !value.is_empty() { + registry_job_id = Some(value.to_string()); + } + } + } + if rows != 1 { + return Err(Error::Runtime { + message: "materialized-view submission must return exactly one status row".into(), + }); + } + let job_id = registry_job_id.ok_or_else(|| Error::Runtime { + message: "server acknowledged an early materialized-view handle but returned no job_id" + .into(), + })?; + Ok(MaterializedViewJobSubmission::Registry { job_id }) + } + pub(in crate::remote) async fn describe_materialized_view( &self, name: &str, diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs new file mode 100644 index 000000000..ff87e0000 --- /dev/null +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use super::SqlClient; +use crate::{ + database::ExecuteQueryRequest, + error::{Error, Result}, + job::Job, +}; +use arrow_array::{Array, ListArray, RecordBatch, StringArray}; +use futures::TryStreamExt; +use serde::{Serialize, de::DeserializeOwned}; +use std::sync::Arc; + +pub(super) fn literal(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} +pub(super) fn strings(batches: &[RecordBatch], name: &str) -> Result> { + batches + .iter() + .map(|batch| { + let values = batch + .column_by_name(name) + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(|| Error::Runtime { + message: format!("SQL result is missing UTF-8 column '{name}'"), + })?; + if values.null_count() != 0 { + return Err(Error::Runtime { + message: format!("SQL result contains null '{name}'"), + }); + } + Ok(values + .iter() + .map(|value| value.unwrap().to_owned()) + .collect::>()) + }) + .collect::>>() + .map(|rows| rows.into_iter().flatten().collect()) +} + +/// Read an optional `List` column. Older servers do not return the +/// column, so a missing column means no warnings rather than a bad result. +pub(super) fn string_lists(batches: &[RecordBatch], name: &str) -> Result> { + let mut values = Vec::new(); + for batch in batches { + let Some(column) = batch.column_by_name(name) else { + continue; + }; + let lists = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: format!("SQL result column '{name}' is not a string list"), + })?; + for index in 0..lists.len() { + if lists.is_null(index) { + return Err(Error::Runtime { + message: format!("SQL result contains null '{name}'"), + }); + } + let list = lists.value(index); + let strings = + list.as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: format!("SQL result column '{name}' contains a non-string value"), + })?; + if strings.null_count() != 0 { + return Err(Error::Runtime { + message: format!("SQL result column '{name}' contains null values"), + }); + } + values.extend(strings.iter().map(|value| value.unwrap().to_owned())); + } + } + Ok(values) +} + +pub(super) fn definition(batches: Vec) -> Result { + let values = strings(&batches, "definition")?; + let [value]: [String; 1] = values.try_into().map_err(|_| Error::Runtime { + message: "SQL definition command must return exactly one row".into(), + })?; + serde_json::from_str(&value).map_err(|error| Error::Runtime { + message: format!("invalid SQL definition: {error}"), + }) +} +impl SqlClient { + pub(super) async fn object_job( + &self, + request: ExecuteQueryRequest, + decode: F, + ) -> Result> + where + T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static, + F: FnOnce(Vec) -> Result + Send + 'static, + { + let query = Arc::new(self.execute(request).await?); + let id = query.id(); + let execution = query.clone(); + let task = tokio::spawn(async move { + let reader = execution.reader().await?; + decode(reader.try_collect().await?) + }); + Ok(Job::from_query_task(id, task, move || { + let query = query.clone(); + async move { query.cancel().await } + })) + } +} + +#[cfg(test)] +mod tests { + use super::string_lists; + use arrow_array::builder::{ListBuilder, StringBuilder}; + use arrow_array::{ArrayRef, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + fn warning_schema() -> Arc { + Arc::new(Schema::new(vec![Field::new( + "warnings", + DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))), + true, + )])) + } + + #[test] + fn reads_warnings_after_an_empty_first_batch() { + let schema = warning_schema(); + let empty = RecordBatch::new_empty(schema.clone()); + let mut builder = ListBuilder::new(StringBuilder::new()); + builder.values().append_value( + "materialized view \"pinned\" references Function \"embed\" version \"1\"", + ); + builder.append(true); + let non_empty = + RecordBatch::try_new(schema.clone(), vec![Arc::new(builder.finish()) as ArrayRef]) + .unwrap(); + + assert_eq!( + string_lists(&[empty, non_empty], "warnings").unwrap(), + ["materialized view \"pinned\" references Function \"embed\" version \"1\""] + ); + } + + #[test] + fn missing_warning_column_remains_an_empty_result() { + let schema = Arc::new(Schema::new(vec![Field::new( + "status", + DataType::Utf8, + false, + )])); + let batch = RecordBatch::new_empty(schema); + + assert_eq!( + string_lists(&[batch], "warnings").unwrap(), + Vec::::new() + ); + } + + #[test] + fn null_or_non_list_warning_values_are_rejected() { + let mut builder = ListBuilder::new(StringBuilder::new()); + builder.append(false); + let null_list = RecordBatch::try_new( + warning_schema(), + vec![Arc::new(builder.finish()) as ArrayRef], + ) + .unwrap(); + assert!(string_lists(&[null_list], "warnings").is_err()); + + let non_list_schema = Arc::new(Schema::new(vec![Field::new( + "warnings", + DataType::Utf8, + false, + )])); + let non_list = RecordBatch::new_empty(non_list_schema); + assert!(string_lists(&[non_list], "warnings").is_err()); + } +} diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs new file mode 100644 index 000000000..bdb70ef6f --- /dev/null +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use super::{SqlClient, materialized_view::quote_identifier, objects::strings}; +use crate::{ + database::ExecuteQueryRequest, + error::{Error, Result}, + listing::{ListingOptions, ListingPage}, + secrets::SecretInfo, + utils::{validate_namespace, validate_secret_name}, +}; +use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use futures::TryStreamExt; +use std::sync::Arc; +fn secret_info(batches: Vec) -> Result { + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(Error::Runtime { + message: "DESCRIBE SECRET must return exactly one row".into(), + }); + } + let batch = batches.iter().find(|batch| batch.num_rows() == 1).unwrap(); + let timestamp = |name: &str| -> Result { + let values = batch + .column_by_name(name) + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(|| Error::Runtime { + message: format!("DESCRIBE SECRET is missing INT64 column '{name}'"), + })?; + if values.is_null(0) { + return Err(Error::Runtime { + message: format!("DESCRIBE SECRET contains null '{name}'"), + }); + } + Ok(values.value(0)) + }; + Ok(SecretInfo { + name: strings(&batches, "name")?.remove(0), + created_at_millis: timestamp("created_at_millis")?, + updated_at_millis: timestamp("updated_at_millis")?, + }) +} + +impl SqlClient { + pub(in crate::remote) async fn write_secret( + &self, + name: &str, + value: &str, + namespace: &[String], + create: bool, + ) -> Result<()> { + validate_secret_name(name)?; + validate_namespace(namespace)?; + let parameters = RecordBatch::try_from_iter(vec![( + "", + Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef, + )]) + .map_err(|error| Error::Runtime { + message: error.to_string(), + })?; + self.object_job( + ExecuteQueryRequest { + query: format!( + "{} SECRET {} {}SECRET_STRING = $1", + if create { "CREATE" } else { "ALTER" }, + quote_identifier(name), + if create { + "TYPE = GENERIC_STRING " + } else { + "SET " + } + ), + default_namespace_path: namespace.to_vec(), + parameters: Some(parameters), + }, + |_| Ok(()), + ) + .await? + .wait() + .await + } + pub(in crate::remote) async fn describe_secret( + &self, + name: &str, + namespace: &[String], + ) -> Result { + validate_secret_name(name)?; + validate_namespace(namespace)?; + self.object_job( + ExecuteQueryRequest { + query: format!("DESCRIBE SECRET {}", quote_identifier(name)), + default_namespace_path: namespace.to_vec(), + parameters: None, + }, + secret_info, + ) + .await? + .wait() + .await + } + pub(in crate::remote) async fn drop_secret( + &self, + name: &str, + namespace: &[String], + ) -> Result<()> { + validate_secret_name(name)?; + validate_namespace(namespace)?; + self.object_job( + ExecuteQueryRequest { + query: format!("DROP SECRET IF EXISTS {}", quote_identifier(name)), + default_namespace_path: namespace.to_vec(), + parameters: None, + }, + |_| Ok(()), + ) + .await? + .wait() + .await + } + pub(in crate::remote) async fn list_secrets( + &self, + namespace: &[String], + options: ListingOptions, + ) -> Result> { + validate_namespace(namespace)?; + let limit = options.page_limit.unwrap_or(100); + if limit == 0 || limit > i32::MAX as u32 { + return Err(Error::InvalidInput { + message: "page limit must be between 1 and i32::MAX".into(), + }); + } + let invalid_token = || Error::InvalidInput { + message: "invalid secret page token for this database or namespace".into(), + }; + let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { + let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; + let (kind, database, prefix, path, last): ( + String, + String, + Option, + Vec, + String, + ) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; + if kind != "secret" + || database != self.inner.database + || prefix != self.inner.database_prefix + || path != namespace + { + return Err(invalid_token()); + } + format!(" WHERE name > '{}'", last.replace('\'', "''")) + } else { + String::new() + }; + let query = self + .execute(ExecuteQueryRequest { + query: format!("SHOW SECRETS{after} LIMIT {}", u64::from(limit) + 1), + default_namespace_path: namespace.to_vec(), + parameters: None, + }) + .await?; + let mut reader = query.reader().await?; + let mut items = Vec::new(); + while let Some(batch) = reader.try_next().await? { + items.extend(strings(&[batch], "name")?); + } + let page_token = if items.len() > limit as usize { + items.truncate(limit as usize); + let cursor = serde_json::to_vec(&( + "secret", + &self.inner.database, + &self.inner.database_prefix, + namespace, + items.last().unwrap(), + )) + .map_err(|error| Error::Runtime { + message: error.to_string(), + })?; + Some(URL_SAFE_NO_PAD.encode(cursor)) + } else { + None + }; + Ok(ListingPage { items, page_token }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::ArrayRef; + + #[test] + fn decodes_native_secret_metadata() { + let batch = RecordBatch::try_from_iter(vec![ + ( + "name", + Arc::new(StringArray::from(vec!["api-key"])) as ArrayRef, + ), + ( + "created_at_millis", + Arc::new(Int64Array::from(vec![10])) as ArrayRef, + ), + ( + "updated_at_millis", + Arc::new(Int64Array::from(vec![20])) as ArrayRef, + ), + ]) + .unwrap(); + let info = secret_info(vec![batch.clone()]).unwrap(); + assert_eq!(info.name, "api-key"); + assert_eq!(info.created_at_millis, 10); + assert_eq!(info.updated_at_millis, 20); + assert!(secret_info(vec![]).is_err()); + assert!(secret_info(vec![batch.clone(), batch]).is_err()); + let missing = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringArray::from(vec!["api-key"])) as ArrayRef, + )]) + .unwrap(); + assert!(secret_info(vec![missing]).is_err()); + } +} diff --git a/rust/lancedb/src/remote/sql/stream.rs b/rust/lancedb/src/remote/sql/stream.rs index ed85c6c92..420eecd15 100644 --- a/rust/lancedb/src/remote/sql/stream.rs +++ b/rust/lancedb/src/remote/sql/stream.rs @@ -20,7 +20,8 @@ use uuid::Uuid; use super::{ ABANDONED_QUERY_RETENTION, DEFAULT_READ_TIMEOUT, ResultEndpointStream, ResultStartGuard, - SqlClientInner, TERMINAL_QUERY_RETENTION, resolve_timeout, sql_error, with_overall_timeout, + SqlClientInner, TERMINAL_QUERY_RETENTION, resolve_timeout, sql_error, sql_flight_error, + sql_status_error, with_overall_timeout, }; use crate::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}; use crate::error::{Error, Result}; @@ -99,6 +100,9 @@ impl Drop for Borrowed<'_> { pub(super) const PROTOCOL_HEADER: &str = "lancedb-sql-protocol"; pub(super) const PROTOCOL_VERSION: &str = "adaptive-v1"; +const MATERIALIZED_VIEW_JOB_HANDLE_HEADER: &str = "x-lancedb-mv-job-handle"; +const MATERIALIZED_VIEW_JOB_HANDLE_VALUE: &str = "early"; +const MATERIALIZED_VIEW_JOB_HANDLE_ACK: &[u8] = b"early-v1"; const RESPONSE_TYPE_URL: &str = "type.googleapis.com/lancedb.sql.QueryResponse"; #[derive(Clone, PartialEq, Message)] @@ -118,13 +122,19 @@ pub(super) enum Submission { Deferred(PollInfo), } +pub(super) struct OpenedSubmission { + pub(super) submission: Submission, + pub(super) materialized_view_job_handle_supported: bool, +} + impl StreamingQuery { pub(super) async fn open( client: Arc, query: &str, parameters: Option, default_namespace_path: &[String], - ) -> Result { + materialized_view_job_handle: bool, + ) -> Result { if let Some(parameters) = ¶meters && parameters.num_rows() != 1 { @@ -154,6 +164,12 @@ impl StreamingQuery { .metadata() .clone(); metadata.insert(PROTOCOL_HEADER, PROTOCOL_VERSION.parse().unwrap()); + if materialized_view_job_handle { + metadata.insert( + MATERIALIZED_VIEW_JOB_HANDLE_HEADER, + MATERIALIZED_VIEW_JOB_HANDLE_VALUE.parse().unwrap(), + ); + } let mut flight = connection.client.clone(); let response = if let Some(parameters) = parameters { let messages = FlightDataEncoderBuilder::new() @@ -162,7 +178,7 @@ impl StreamingQuery { .build(futures::stream::iter([Ok(parameters)])) .try_collect::>() .await - .map_err(|error| sql_error(&request_id, error))?; + .map_err(|error| sql_flight_error(&request_id, &error))?; let mut request = tonic::Request::new(futures::stream::iter(messages)); *request.metadata_mut() = metadata; tokio::time::timeout(read_timeout, flight.do_exchange(request)).await @@ -173,7 +189,7 @@ impl StreamingQuery { tokio::time::timeout(read_timeout, flight.do_get(request)).await } .map_err(|_| sql_error(&request_id, "SQL query submission timed out"))? - .map_err(|error| sql_error(&request_id, error))?; + .map_err(|error| sql_status_error(&request_id, &error))?; let negotiated = response .metadata() .get(PROTOCOL_HEADER) @@ -183,7 +199,7 @@ impl StreamingQuery { let first = tokio::time::timeout(read_timeout, response_stream.message()) .await .map_err(|_| sql_error(&request_id, "SQL query handoff timed out"))? - .map_err(|error| sql_error(&request_id, error))? + .map_err(|error| sql_status_error(&request_id, &error))? .ok_or_else(|| { sql_error(&request_id, "SQL response omitted its execution decision") })?; @@ -210,18 +226,28 @@ impl StreamingQuery { "SQL handoff omitted result and continuation information", )); } - return Ok(Submission::Deferred(info)); + let materialized_view_job_handle_supported = + info.info.as_ref().is_some_and(|info| { + info.app_metadata.as_ref() == MATERIALIZED_VIEW_JOB_HANDLE_ACK + }); + return Ok(OpenedSubmission { + submission: Submission::Deferred(info), + materialized_view_job_handle_supported, + }); } } let stream = FlightRecordBatchStream::new_from_flight_data( response_stream .map_err(|status| arrow_flight::error::FlightError::Tonic(Box::new(status))), ); - Ok(Submission::Stream(ResultEndpointStream { - stream, - request_id, - read_timeout, - })) + Ok(OpenedSubmission { + submission: Submission::Stream(ResultEndpointStream { + stream, + request_id, + read_timeout, + }), + materialized_view_job_handle_supported: false, + }) } pub(super) fn new( diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs new file mode 100644 index 000000000..0c2229684 --- /dev/null +++ b/rust/lancedb/src/remote/sql/view.rs @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use super::{SqlClient, materialized_view::quote_identifier, objects::strings}; +use crate::{ + database::ExecuteQueryRequest, + error::{Error, Result}, + listing::{ListingOptions, ListingPage}, + utils::{validate_namespace, validate_view_name}, + view::ViewDescription, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use futures::TryStreamExt; +use lance_namespace::models::JsonArrowSchema; +use std::sync::Arc; +#[derive(Clone, serde::Serialize, serde::Deserialize)] +struct ViewDefinition { + name: String, + namespace: Vec, + query: String, + default_database: String, + default_namespace: Vec, + schema: JsonArrowSchema, +} + +impl ViewDefinition { + fn into_description(self) -> Result { + let schema = + lance_namespace::schema::convert_json_arrow_schema(&self.schema).map_err(|error| { + Error::Runtime { + message: format!("View '{}' has an undecodable schema: {error}", self.name), + } + })?; + Ok(ViewDescription { + name: self.name, + namespace_path: self.namespace, + query: self.query, + default_database: self.default_database, + default_namespace_path: self.default_namespace, + schema: Arc::new(schema), + }) + } +} + +fn view_description( + batches: Vec, + namespace: Vec, +) -> Result { + let one = |column: &str| -> Result { + let mut values = strings(&batches, column)?; + if values.len() != 1 { + return Err(Error::Runtime { + message: "View metadata must contain exactly one row".into(), + }); + } + Ok(values.remove(0)) + }; + let name = one("name")?; + let json: JsonArrowSchema = + serde_json::from_str(&one("schema")?).map_err(|error| Error::Runtime { + message: format!("View '{name}' has invalid schema JSON: {error}"), + })?; + let schema = lance_namespace::schema::convert_json_arrow_schema(&json).map_err(|error| { + Error::Runtime { + message: format!("View '{name}' has an undecodable schema: {error}"), + } + })?; + let default_database = schema + .metadata() + .get("lancedb::view::default_db") + .ok_or_else(|| Error::Runtime { + message: format!("View '{name}' has no defining database"), + })? + .clone(); + let default_namespace = schema + .metadata() + .get("lancedb::view::default_namespace") + .ok_or_else(|| Error::Runtime { + message: format!("View '{name}' has no defining namespace"), + })?; + let default_namespace_path = if default_namespace == "public" { + Vec::new() + } else { + default_namespace.split('$').map(str::to_owned).collect() + }; + Ok(ViewDefinition { + name, + namespace, + query: one("query")?, + default_database, + default_namespace: default_namespace_path, + schema: json, + }) +} + +impl SqlClient { + pub(in crate::remote) async fn create_view( + &self, + name: &str, + query: &str, + namespace: &[String], + ) -> Result { + validate_view_name(name)?; + validate_namespace(namespace)?; + let namespace_path = namespace.to_vec(); + self.object_job( + ExecuteQueryRequest { + query: format!("CREATE VIEW {} AS {query}", quote_identifier(name)), + default_namespace_path: namespace.to_vec(), + parameters: None, + }, + move |batches| view_description(batches, namespace_path), + ) + .await? + .wait() + .await? + .into_description() + } + pub(in crate::remote) async fn describe_view( + &self, + name: &str, + namespace: &[String], + ) -> Result { + validate_view_name(name)?; + validate_namespace(namespace)?; + let namespace_path = namespace.to_vec(); + self.object_job( + ExecuteQueryRequest { + query: format!("DESCRIBE VIEW {}", quote_identifier(name)), + default_namespace_path: namespace.to_vec(), + parameters: None, + }, + move |batches| view_description(batches, namespace_path), + ) + .await? + .wait() + .await? + .into_description() + } + pub(in crate::remote) async fn list_views( + &self, + namespace: &[String], + options: ListingOptions, + ) -> Result> { + validate_namespace(namespace)?; + let limit = options.page_limit.unwrap_or(100); + if limit == 0 || limit > i32::MAX as u32 { + return Err(Error::InvalidInput { + message: "page limit must be between 1 and i32::MAX".into(), + }); + } + let invalid_token = || Error::InvalidInput { + message: "invalid view page token for this database or namespace".into(), + }; + let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { + let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; + let (kind, database, prefix, path, last): ( + String, + String, + Option, + Vec, + String, + ) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; + if kind != "view" + || database != self.inner.database + || prefix != self.inner.database_prefix + || path != namespace + { + return Err(invalid_token()); + } + format!(" WHERE name > '{}'", last.replace('\'', "''")) + } else { + String::new() + }; + let query = self + .execute(ExecuteQueryRequest { + query: format!("SHOW VIEWS{after} LIMIT {}", u64::from(limit) + 1), + default_namespace_path: namespace.to_vec(), + parameters: None, + }) + .await?; + let mut reader = query.reader().await?; + let mut items = Vec::new(); + while let Some(batch) = reader.try_next().await? { + items.extend(strings(&[batch], "name")?); + } + let page_token = if items.len() > limit as usize { + items.truncate(limit as usize); + let cursor = serde_json::to_vec(&( + "view", + &self.inner.database, + &self.inner.database_prefix, + namespace, + items.last().unwrap(), + )) + .map_err(|error| Error::Runtime { + message: error.to_string(), + })?; + Some(URL_SAFE_NO_PAD.encode(cursor)) + } else { + None + }; + Ok(ListingPage { items, page_token }) + } +} diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 6a0421fa6..65d08c984 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3,7 +3,7 @@ use std::sync::atomic::AtomicUsize; -use arrow_array::builder::StringDictionaryBuilder; +use arrow_array::builder::{ListBuilder, StringBuilder, StringDictionaryBuilder}; use arrow_array::types::{Float32Type, Int32Type}; use arrow_array::{Array, ArrayRef, FixedSizeListArray, Float32Array, Int64Array, StringArray}; use arrow_flight::encode::FlightDataEncoderBuilder; @@ -14,6 +14,7 @@ use arrow_flight::{ FlightInfo, HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket, }; use arrow_schema::{DataType, Field, Schema}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::stream::BoxStream; use futures::{StreamExt, TryStreamExt}; use tonic::metadata::MetadataMap; @@ -21,6 +22,7 @@ use tonic::{Request, Response, Status, Streaming}; use super::stream::{PROTOCOL_HEADER, PROTOCOL_VERSION, QueryResponse}; use super::*; +use crate::Connection; use crate::database::Database; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::RemoteCatalogOptions; @@ -28,6 +30,7 @@ use crate::remote::client::HeaderProvider; use crate::remote::client::test_utils::client_with_handler; use crate::remote::db::RemoteDatabase; use crate::remote::table::RemoteTable; +use crate::storage_integration::{CreateStorageIntegrationRequest, SecretReference}; use crate::table::BaseTable; #[derive(Debug, Default)] @@ -65,6 +68,7 @@ struct CapturedHeaders { request_id: String, api_key: String, database_prefix: String, + materialized_view_job_handle: Option, } /// Every exchange's statement and the parameter row it arrived with. @@ -89,6 +93,8 @@ struct TestSqlService { headers: Arc>>, gate_refresh_release: Arc, exchanges: ReceivedExchanges, + result_overrides: Arc>>, + materialized_view_job_handle_supported: bool, /// How many exchange responses have been dropped, finished or not. exchange_drops: Arc, result: RecordBatch, @@ -124,8 +130,27 @@ impl TestSqlService { .get("x-lancedb-database-prefix") .map(|value| value.to_str().unwrap().to_string()) .unwrap_or_default(), + materialized_view_job_handle: metadata + .get("x-lancedb-mv-job-handle") + .map(|value| value.to_str().unwrap().to_string()), }); } + + fn result_for_query(&self, query: &str) -> RecordBatch { + if query == "SELECT large message" { + self.large_result.clone() + } else if query == "SELECT dictionary" { + self.dictionary_result.clone() + } else { + self.result_overrides + .lock() + .unwrap() + .get(query) + .cloned() + .unwrap_or_else(|| self.result.clone()) + } + } + fn adaptive_response( &self, query: &str, @@ -134,15 +159,19 @@ impl TestSqlService { if !self.adaptive { return Response::new(rows); } - let poll_info = - self.defer.then(|| PollInfo { - info: Some(FlightInfo::new().with_endpoint( - FlightEndpoint::new().with_ticket(Ticket::new(query.to_string())), - )), + let poll_info = self.defer.then(|| { + let mut info = FlightInfo::new() + .with_endpoint(FlightEndpoint::new().with_ticket(Ticket::new(query.to_string()))); + if self.materialized_view_job_handle_supported { + info.app_metadata = b"early-v1".to_vec().into(); + } + PollInfo { + info: Some(info), flight_descriptor: Some(FlightDescriptor::new_cmd(format!("poll:1:{query}"))), progress: Some(0.25), expiration_time: None, - }); + } + }); let first = FlightData { app_metadata: if self.invalid_decision { b"invalid protobuf".to_vec().into() @@ -222,6 +251,8 @@ impl Default for TestSqlService { headers: 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, exchange_drops: Arc::new(AtomicUsize::new(0)), result, large_result, @@ -313,6 +344,13 @@ impl FlightService for TestSqlService { { return Err(Status::unavailable("transient polling failure")); } + if query == "SELECT function failure" && stage == 1 { + let mut status = Status::failed_precondition("Function 'frames' raised ValueError"); + status + .metadata_mut() + .insert("x-lancedb-sql-job-id", "job-1".parse().unwrap()); + return Err(status); + } let complete = if query == "SELECT no info" { stage >= 2 } else { @@ -337,14 +375,8 @@ impl FlightService for TestSqlService { ); } if query != "SELECT empty" { - let schema = if query == "SELECT large message" { - self.large_result.schema_ref() - } else if query == "SELECT dictionary" { - self.dictionary_result.schema_ref() - } else { - self.result.schema_ref() - }; - info = info.try_with_schema(schema).unwrap(); + let schema = self.result_for_query(&query).schema(); + info = info.try_with_schema(&schema).unwrap(); } Ok(Response::new(PollInfo { info: (query != "SELECT no info" || stage > 0).then_some(info), @@ -392,13 +424,7 @@ impl FlightService for TestSqlService { let empty = ticket == b"SELECT empty"; let slow = ticket == b"SELECT slow get"; let large = ticket == b"SELECT large message"; - let result = if large { - self.large_result.clone() - } else if ticket == b"SELECT dictionary" { - self.dictionary_result.clone() - } else { - self.result.clone() - }; + let result = self.result_for_query(std::str::from_utf8(ticket).unwrap_or_default()); let schema = result.schema(); let gate_refresh_release = self.gate_refresh_release.clone(); let input = futures::stream::once(async move { @@ -597,6 +623,14 @@ fn parameterized(query: &str, parameters: RecordBatch) -> ExecuteQueryRequest { async fn start_sql_service( service: TestSqlService, client_config: ClientConfig, +) -> (SqlClient, tokio::sync::oneshot::Sender<()>) { + start_sql_service_with_prefix(service, client_config, None).await +} + +async fn start_sql_service_with_prefix( + service: TestSqlService, + client_config: ClientConfig, + database_prefix: Option<&str>, ) -> (SqlClient, tokio::sync::oneshot::Sender<()>) { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); @@ -614,7 +648,7 @@ async fn start_sql_service( ); let client = SqlClient::new( "analytics".to_string(), - None, + database_prefix.map(str::to_owned), "test-key".to_string(), None, Some(format!("grpc://{address}")), @@ -960,6 +994,166 @@ async fn remote_create_uses_sql_and_preserves_options_and_namespace() { } } +#[tokio::test] +async fn remote_create_returns_the_registry_job_from_the_early_status_row() { + let service = TestSqlService { + adaptive: true, + defer: true, + materialized_view_job_handle_supported: true, + ..Default::default() + }; + let headers = service.headers.clone(); + let schema = Arc::new(Schema::new(vec![ + Field::new("operation", DataType::Utf8, false), + Field::new("name", DataType::Utf8, false), + Field::new("job_id", DataType::Utf8, false), + Field::new("status", DataType::Utf8, false), + ])); + service.result_overrides.lock().unwrap().insert( + "CREATE MATERIALIZED VIEW \"adults\" AS SELECT * FROM people".into(), + RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec!["CREATE MATERIALIZED VIEW"])), + Arc::new(StringArray::from(vec!["adults"])), + Arc::new(StringArray::from(vec!["job-1"])), + Arc::new(StringArray::from(vec!["submitted"])), + ], + ) + .unwrap(), + ); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + http::Response::builder() + .status(200) + .body( + r#"{"job_id":"job-1","job_type":"sql","job_state":"DONE","creation_ms":1}"# + .to_string(), + ) + .unwrap() + }) + .with_sql_client(sql_client); + + let job = db + .create_materialized_view_async(CreateMaterializedViewRequest { + name: "adults".into(), + namespace_path: vec!["team".into(), "reports".into()], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + }) + .await + .unwrap(); + + assert_eq!(job.id(), Some("job-1")); + job.refresh().await.unwrap(); + assert_eq!(job.job_type().as_deref(), Some("sql")); + job.wait().await.unwrap(); + let headers = headers.lock().unwrap(); + assert!(headers.iter().any(|header| { + header.materialized_view_job_handle.as_deref() == Some("early") + && header.namespace_path == "team$reports" + })); + assert!( + headers + .iter() + .all(|header| header.namespace_path == "team$reports") + ); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_create_registry_handle_reopens_describes_and_cancels() { + let service = TestSqlService { + adaptive: true, + defer: true, + materialized_view_job_handle_supported: true, + ..Default::default() + }; + let schema = Arc::new(Schema::new(vec![ + Field::new("operation", DataType::Utf8, false), + Field::new("name", DataType::Utf8, false), + Field::new("job_id", DataType::Utf8, false), + Field::new("status", DataType::Utf8, false), + ])); + service.result_overrides.lock().unwrap().insert( + "CREATE MATERIALIZED VIEW \"adults\" AS SELECT * FROM people".into(), + RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec!["CREATE MATERIALIZED VIEW"])), + Arc::new(StringArray::from(vec!["adults"])), + Arc::new(StringArray::from(vec!["job-1"])), + Arc::new(StringArray::from(vec!["submitted"])), + ], + ) + .unwrap(), + ); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let describes = Arc::new(AtomicUsize::new(0)); + let seen_describes = describes.clone(); + let describe_ids = Arc::new(std::sync::Mutex::new(Vec::new())); + let seen_describe_ids = describe_ids.clone(); + let cancel_ids = Arc::new(std::sync::Mutex::new(Vec::new())); + let seen_cancel_ids = cancel_ids.clone(); + let db = RemoteDatabase::new_mock(move |request| { + let body = request + .body() + .and_then(|body| body.as_bytes()) + .and_then(|body| serde_json::from_slice::(body).ok()) + .unwrap_or_default(); + let job_id = body["job_id"].as_str().unwrap_or_default().to_string(); + match request.url().path() { + "/v1/jobs/describe" => { + assert_eq!(job_id, "job-1"); + seen_describe_ids.lock().unwrap().push(job_id.clone()); + seen_describes.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body(format!( + r#"{{"job_id":"{job_id}","job_type":"sql","job_state":"IN_PROGRESS","creation_ms":1}}"# + )) + .unwrap() + } + "/v1/jobs/cancel" => { + assert_eq!(job_id, "job-1"); + seen_cancel_ids.lock().unwrap().push(job_id); + http::Response::builder().status(200).body(String::new()).unwrap() + } + path => panic!("unexpected request: {path}"), + } + }) + .with_sql_client(sql_client); + + let job = db + .create_materialized_view_async(CreateMaterializedViewRequest { + name: "adults".into(), + namespace_path: vec!["team".into(), "reports".into()], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + }) + .await + .unwrap(); + assert_eq!(job.id(), Some("job-1")); + + job.refresh().await.unwrap(); + assert_eq!(job.job_type().as_deref(), Some("sql")); + assert_eq!(job.state().as_deref(), Some("running")); + + let reopened = db.open_job("job-1").await.unwrap(); + assert_eq!(reopened.id(), Some("job-1")); + assert_eq!(reopened.job_type().as_deref(), Some("sql")); + reopened.cancel().await.unwrap(); + + assert_eq!(*describe_ids.lock().unwrap(), vec!["job-1", "job-1"]); + assert_eq!(*cancel_ids.lock().unwrap(), vec!["job-1"]); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn query_backed_jobs_propagate_submission_and_execution_failures() { let (client, shutdown) = start_sql_service( @@ -991,6 +1185,34 @@ async fn query_backed_jobs_propagate_submission_and_execution_failures() { shutdown.send(()).unwrap(); } +#[tokio::test] +async fn function_failure_preserves_the_isolated_sql_job_id() { + let (client, shutdown) = start_sql_service( + TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }, + ClientConfig::default(), + ) + .await; + let job = client + .submit_as_job("SELECT function failure".into(), vec![], || async { + Ok(()) + }) + .await + .unwrap(); + + let Err(Error::JobFailed { job_id, failure }) = job.wait().await else { + panic!("a typed Function failure must stay a JobFailed error"); + }; + assert_eq!(job_id.as_deref(), Some("job-1")); + assert_eq!(failure.sql_job_id.as_deref(), Some("job-1")); + assert_eq!(failure.phase, None); + assert_eq!(failure.retryable, None); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn rejected_job_cancellation_does_not_abort_sql_completion() { let service = TestSqlService { @@ -1081,6 +1303,7 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { }); let table = RemoteTable::new_with_sql_client( client, + "analytics".into(), "view".into(), vec!["ns".into()], "ns$view".into(), @@ -1106,7 +1329,30 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { .await .unwrap(); - for result in [first, second] { + let third = view + .refresh() + .full(true) + .cpu_millis(8000) + .memory_bytes(16 << 30) + .gpu_count(2) + .gpu_class("h100") + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + for invalid in [ + view.refresh().cpu_millis(1), + view.refresh().gpu_class("H200:8"), + view.refresh().gpu_count(0).gpu_class("h100"), + ] { + assert!(matches!( + invalid.execute_async().await, + Err(Error::InvalidInput { .. }) + )); + } + for result in [first, second, third] { assert_eq!(result.mode, None); assert_eq!(result.rows_written, None); assert_eq!(result.source_version, None); @@ -1127,6 +1373,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')", ] ); assert!( @@ -1187,6 +1434,7 @@ async fn cancelling_remote_refresh_cancels_sql_query() { }); let table = RemoteTable::new_with_sql_client( client, + "analytics".into(), "cancel_view".into(), vec![], "cancel_view".into(), @@ -1197,6 +1445,8 @@ async fn cancelling_remote_refresh_cancels_sql_query() { .refresh_materialized_view_async(None, false) .await .unwrap(); + assert_eq!(job.job_type().as_deref(), Some("query")); + assert!(job.id().is_some()); tokio::time::timeout(Duration::from_secs(10), async { while do_get_count.load(Ordering::SeqCst) == 0 { tokio::task::yield_now().await; @@ -2051,6 +2301,266 @@ async fn remote_drop_materialized_view_uses_a_query_job() { } } +#[tokio::test] +async fn remote_optimize_submits_a_compaction_job_over_sql() { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "reports".into()], + "team$reports$events".into(), + Default::default(), + Some(sql_client), + ); + + let stats = table + .optimize(crate::table::optimize::OptimizeAction::Compact { + options: crate::table::optimize::CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap(); + + // The SQL job adapter does not expose compaction metrics, so + // `compaction` is a zeroed placeholder, not real numbers -- but it must + // be `Some`: callers (including the Python/Node bindings) unwrap it + // unconditionally on success. + assert_eq!( + stats.compaction, + Some(lance::dataset::optimize::CompactionMetrics::default()) + ); + assert!(stats.prune.is_none()); + assert_eq!( + *statements.lock().unwrap(), + ["OPTIMIZE \"events\" REWRITE DATA"] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team$reports") + ); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_optimize_on_a_branch_submits_a_with_clause_over_sql() { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "reports".into()], + "team$reports$events".into(), + Default::default(), + Some(sql_client), + ) + .with_branch(Some("o'brien".to_string())); + + table + .optimize(crate::table::optimize::OptimizeAction::Compact { + options: crate::table::optimize::CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap(); + + assert_eq!( + *statements.lock().unwrap(), + ["OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'o''brien')"] + ); + shutdown.send(()).unwrap(); +} + +/// Regression test for the language bindings' `optimize()` convenience +/// method, which used to submit a compaction job and then fail on the next +/// action because `Prune` and `Index` are not supported remotely -- so a +/// retry on that failure resubmitted another compaction job. `optimize_full` +/// is what both the Python and Node bindings now call instead of +/// orchestrating `Compact`, `Prune`, and `Index` themselves; on a remote +/// table it must submit only the compaction job and return zeroed prune +/// stats rather than attempting `Prune` and `Index` at all. +#[tokio::test] +async fn remote_optimize_full_skips_prune_and_index() { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let remote_table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "reports".into()], + "team$reports$events".into(), + Default::default(), + Some(sql_client), + ); + let database = Arc::new(RemoteDatabase::new_mock( + |request: reqwest::Request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }, + )); + let table = crate::Table::new(Arc::new(remote_table), database); + + let stats = table + .optimize_full( + crate::table::optimize::CompactionOptions::default(), + None, + None, + None, + ) + .await + .unwrap(); + + // Compaction was submitted (and its placeholder stats are present)... + assert_eq!( + stats.compaction, + Some(lance::dataset::optimize::CompactionMetrics::default()) + ); + // ...but Prune and Index were skipped rather than attempted and failed, + // so the call succeeds with zeroed prune stats instead of returning an + // error after the job has already been submitted. + assert_eq!( + stats.prune, + Some(lance::dataset::cleanup::RemovalStats::default()) + ); + assert_eq!( + *statements.lock().unwrap(), + ["OPTIMIZE \"events\" REWRITE DATA"] + ); + shutdown.send(()).unwrap(); +} + +/// `delete_unverified: Some(false)` is what every real Python call sends +/// (the public `optimize()` default is `False`, not `None`), so it must be +/// treated the same as "not asking to prune" -- not rejected -- or a plain +/// `table.optimize()` from Python would never succeed on a remote table. +#[tokio::test] +async fn remote_optimize_full_treats_delete_unverified_false_as_default() { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let remote_table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "reports".into()], + "team$reports$events".into(), + Default::default(), + Some(sql_client), + ); + let database = Arc::new(RemoteDatabase::new_mock( + |request: reqwest::Request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }, + )); + let table = crate::Table::new(Arc::new(remote_table), database); + + let stats = table + .optimize_full( + crate::table::optimize::CompactionOptions::default(), + None, + None, + Some(false), + ) + .await + .unwrap(); + + assert_eq!( + stats.prune, + Some(lance::dataset::cleanup::RemovalStats::default()) + ); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); +} + +/// Regression test: a caller who explicitly asks a remote table's +/// `optimize()` to prune (an older-than cutoff, an absolute timestamp, or +/// `delete_unverified=True`) used to get a success result reporting zero +/// bytes removed, even though no pruning was attempted at all -- silently +/// dropping their storage-reclaim request. It must instead reject before +/// anything is submitted, the same way a non-default `CompactionOptions` is. +#[tokio::test] +async fn remote_optimize_full_rejects_explicit_pruning_options() { + async fn assert_rejected_before_submission( + older_than: Option, + before_timestamp: Option>, + delete_unverified: Option, + ) { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let remote_table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "reports".into()], + "team$reports$events".into(), + Default::default(), + Some(sql_client), + ); + let database = Arc::new(RemoteDatabase::new_mock( + |request: reqwest::Request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }, + )); + let table = crate::Table::new(Arc::new(remote_table), database); + + let error = table + .optimize_full( + crate::table::optimize::CompactionOptions::default(), + older_than, + before_timestamp, + delete_unverified, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. }), "{error:?}"); + assert!(statements.lock().unwrap().is_empty()); + shutdown.send(()).unwrap(); + } + + assert_rejected_before_submission(Some(chrono::Duration::days(1)), None, None).await; + assert_rejected_before_submission(None, Some(chrono::Utc::now()), None).await; + assert_rejected_before_submission(None, None, Some(true)).await; +} + #[tokio::test] async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { for defer in [false, true] { @@ -2140,6 +2650,7 @@ async fn remote_describe_materialized_view_preserves_the_sql_definition() { client_with_handler(|request| -> http::Response { panic!("unexpected REST request: {}", request.url().path()); }), + "analytics".into(), "daily_sales".into(), vec!["analytics".into()], "analytics$daily_sales".into(), @@ -2156,3 +2667,1078 @@ async fn remote_describe_materialized_view_preserves_the_sql_definition() { shutdown.send(()).unwrap(); } } + +#[tokio::test] +async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata() { + let info: serde_json::Value = serde_json::from_str(include_str!( + "../../tests/fixtures/storage_integration.json" + )) + .unwrap(); + let columns: Vec<(String, ArrayRef)> = info + .as_object() + .unwrap() + .iter() + .map(|(name, value)| { + let column: ArrayRef = match value { + serde_json::Value::Bool(value) => { + Arc::new(arrow_array::BooleanArray::from(vec![*value])) + } + serde_json::Value::Number(value) => { + Arc::new(Int64Array::from(vec![value.as_i64().unwrap()])) + } + serde_json::Value::Null => Arc::new(StringArray::from(vec![None::])), + serde_json::Value::String(value) => { + Arc::new(StringArray::from(vec![value.clone()])) + } + value => Arc::new(StringArray::from(vec![value.to_string()])), + }; + (name.clone(), column) + }) + .collect(); + for defer in [false, true] { + let service = TestSqlService { + result: RecordBatch::try_from_iter(columns.clone()).unwrap(), + adaptive: true, + defer, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let database = RemoteDatabase::new_mock(|request| -> http::Response { + panic!( + "Storage integration operation used REST: {}", + request.url().path() + ); + }) + .with_sql_client(client); + let namespace = vec!["platform".into(), "aws".into()]; + let configuration = CreateStorageIntegrationRequest::s3( + "s3://customer-bucket/raw/", + "arn:aws:iam::123456789012:role/access", + ) + .with_aws_region("us-east-1"); + let created = database + .create_storage_integration("raw", configuration, &namespace) + .await + .unwrap(); + assert_eq!(created.database, "default"); + assert_eq!( + created.trust_policy["Statement"][0]["Condition"]["StringEquals"]["sts:ExternalId"], + created.aws_external_id + ); + assert_eq!( + database + .describe_storage_integration("raw", &namespace) + .await + .unwrap() + .aws_external_id, + created.aws_external_id + ); + assert_eq!( + database + .list_storage_integrations(&namespace, Default::default()) + .await + .unwrap() + .items, + ["raw"] + ); + database + .drop_storage_integration("raw", &namespace) + .await + .unwrap(); + let credential = SecretReference::new("key") + .with_database("platform/raw") + .with_namespace(vec!["credentials".into()]); + database + .create_storage_integration( + "raw", + CreateStorageIntegrationRequest::s3_with_secrets( + "s3://customer-bucket/raw/", + credential.clone(), + credential, + ), + &namespace, + ) + .await + .unwrap(); + let statements = statements.lock().unwrap(); + assert!(statements[0].contains("STORAGE_AWS_REGION = 'us-east-1'")); + assert_eq!(statements[1], "DESCRIBE STORAGE INTEGRATION \"raw\""); + assert_eq!(statements[2], "SHOW STORAGE INTEGRATIONS"); + assert_eq!(statements[3], "DROP STORAGE INTEGRATION \"raw\""); + assert!(statements[4].contains( + "STORAGE_AWS_ACCESS_KEY_ID_SECRET = \"platform/raw\".\"credentials\".\"key\"" + )); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "platform$aws") + ); + let _ = shutdown.send(()); + } +} + +#[tokio::test] +async fn function_creation_and_description_use_sql_query_handles() { + const VERSION: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + const REQUEST: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" + ); + for (defer, with_models) in [(false, false), (false, true), (true, false), (true, true)] { + let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); + request_json["batch_size"] = serde_json::json!(2); + request_json["row_timeout_seconds"] = serde_json::json!(0.75); + request_json["secret_bindings"] = serde_json::json!([{ + "kind": "env", + "variable": "HF_TOKEN", + "secret_ref": {"name": "hf-prod"}, + }]); + let mut version_json: serde_json::Value = serde_json::from_str(VERSION).unwrap(); + version_json["batch_size"] = serde_json::json!(12); + version_json["row_timeout_seconds"] = serde_json::json!(8.0); + version_json["result_stability"] = serde_json::json!("input_and_context"); + if with_models { + let models = serde_json::json!([{ + "repo": "sentence-transformers/all-MiniLM-L6-v2", + "revision": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41", + }]); + request_json["models"] = models.clone(); + version_json["image"]["models"] = models; + } + let expected_models = version_json["image"].get("models"); + let mut expected_request = request_json.clone(); + expected_request.as_object_mut().unwrap().remove("name"); + let request = + crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string()) + .unwrap(); + let result = RecordBatch::try_from_iter(vec![( + "definition", + Arc::new(StringArray::from(vec![version_json.to_string()])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }) + .with_sql_client(client.clone()); + let job = db + .create_function_async(request, &["team".into()]) + .await + .unwrap(); + assert_eq!(job.job_type().as_deref(), Some("query")); + let id = Uuid::parse_str(job.id().unwrap()).unwrap(); + let created = job.wait().await.unwrap(); + assert_eq!(created.name(), "embed"); + assert_eq!(created.version(), "1"); + assert_eq!(created.batch_size(), Some(12)); + assert_eq!(created.row_timeout_seconds(), Some(8.0)); + assert_eq!(created.result_stability(), Some("input_and_context")); + // Assert the actual SQL body, after the same native JSON decode used + // by the Python binding, rather than only the Python declaration. + { + let seen = statements.lock().unwrap(); + let encoded = seen[0] + .strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#) + .unwrap() + .strip_suffix('\'') + .unwrap(); + let sent: serde_json::Value = + serde_json::from_str(&encoded.replace("''", "'")).unwrap(); + assert_eq!(sent, expected_request); + } + let created_json: serde_json::Value = + serde_json::from_str(&created.to_canonical_json().unwrap()).unwrap(); + assert_eq!(created_json["image"].get("models"), expected_models); + assert_eq!(created_json["batch_size"], 12); + assert_eq!(created_json["row_timeout_seconds"], 8.0); + assert_eq!(created_json["result_stability"], "input_and_context"); + assert_eq!( + client.describe(id).await.unwrap().status, + QueryStatus::Finished + ); + let described = db + .get_function("embed", "1", &["team".into()]) + .await + .unwrap(); + assert_eq!(described.name(), "embed"); + assert_eq!(described.batch_size(), Some(12)); + assert_eq!(described.row_timeout_seconds(), Some(8.0)); + assert_eq!(described.result_stability(), Some("input_and_context")); + let described_json: serde_json::Value = + serde_json::from_str(&described.to_canonical_json().unwrap()).unwrap(); + assert_eq!(described_json["image"].get("models"), expected_models); + assert_eq!(described_json["batch_size"], 12); + assert_eq!(described_json["row_timeout_seconds"], 8.0); + assert_eq!(described_json["result_stability"], "input_and_context"); + let listed = db + .list_functions(&["team".into()], Default::default()) + .await + .unwrap(); + assert_eq!(listed.items.len(), 1); + assert_eq!(listed.items[0].batch_size(), Some(12)); + assert_eq!(listed.items[0].row_timeout_seconds(), Some(8.0)); + assert_eq!( + listed.items[0].result_stability(), + Some("input_and_context") + ); + let listed_json: serde_json::Value = + serde_json::from_str(&listed.items[0].to_canonical_json().unwrap()).unwrap(); + assert_eq!(listed_json["image"].get("models"), expected_models); + assert_eq!(listed_json["batch_size"], 12); + assert_eq!(listed_json["row_timeout_seconds"], 8.0); + assert_eq!(listed_json["result_stability"], "input_and_context"); + let seen = statements.lock().unwrap(); + assert_eq!(seen[1], "DESCRIBE FUNCTION \"embed\" WITH (version = '1')"); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn function_creation_rejects_invalid_execution_controls_before_sql() { + const REQUEST: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json" + ); + let service = TestSqlService::default(); + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }) + .with_sql_client(client.clone()); + + for timeout in [f64::NAN, f64::INFINITY, -1.0] { + let mut request = crate::function::FunctionRegistrationRequest::from_json(REQUEST).unwrap(); + request.row_timeout_seconds = Some(timeout); + let error = db.create_function_async(request, &[]).await.unwrap_err(); + assert!( + matches!(error, Error::InvalidInput { message } if message.contains("row_timeout_seconds")) + ); + } + + let mut request = crate::function::FunctionRegistrationRequest::from_json(REQUEST).unwrap(); + request.batch_size = Some(0); + let error = db.create_function_async(request, &[]).await.unwrap_err(); + assert!(matches!(error, Error::InvalidInput { message } if message.contains("batch_size"))); + assert!(statements.lock().unwrap().is_empty()); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn function_drop_keeps_the_query_id_and_reports_catalog_removal() { + for (status, expected) in [("dropped", true), ("not_found", false)] { + let result = RecordBatch::try_from_iter(vec![( + "status", + Arc::new(StringArray::from(vec![status])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: true, + result, + ..Default::default() + }; + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client.clone()); + let (dropped, job) = db.drop_function_async("embed", "1", &[]).await.unwrap(); + assert_eq!(dropped, expected); + assert_eq!(job.job_type().as_deref(), Some("query")); + let id = Uuid::parse_str(job.id().unwrap()).unwrap(); + job.wait().await.unwrap(); + job.wait().await.unwrap(); + assert_eq!( + client.describe(id).await.unwrap().status, + QueryStatus::Finished + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn function_drop_decodes_server_warnings_for_the_binding_bridge() { + let mut warning_values = ListBuilder::new(StringBuilder::new()); + warning_values + .values() + .append_value("materialized view \"pinned\" references Function \"embed\" version \"1\""); + warning_values.append(true); + let result = RecordBatch::try_from_iter(vec![ + ( + "status", + Arc::new(StringArray::from(vec!["dropped"])) as ArrayRef, + ), + ("warnings", Arc::new(warning_values.finish()) as ArrayRef), + ]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: true, + result, + ..Default::default() + }; + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client); + + let (dropped, warnings) = db + .drop_function_with_warnings("embed", "1", &[]) + .await + .unwrap(); + assert!(dropped); + assert_eq!( + warnings, + ["materialized view \"pinned\" references Function \"embed\" version \"1\""] + ); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + ..Default::default() + }; + let exchanges = service.exchanges.clone(); + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }) + .with_sql_client(client); + db.create_secret("api-key", "credential's value", &["team".into()]) + .await + .unwrap(); + db.alter_secret("api-key", "rotated-value", &["team".into()]) + .await + .unwrap(); + db.drop_secret("api-key", &["team".into()]).await.unwrap(); + assert_eq!( + statements.lock().unwrap().as_slice(), + ["DROP SECRET IF EXISTS \"api-key\""] + ); + let seen = exchanges.lock().unwrap(); + assert_eq!(seen.len(), 2); + assert_eq!( + seen[0].0, + "CREATE SECRET \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1" + ); + assert_eq!(seen[1].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1"); + assert_eq!( + seen[0] + .1 + .as_ref() + .unwrap() + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "credential's value" + ); + assert_eq!( + seen[1] + .1 + .as_ref() + .unwrap() + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "rotated-value" + ); + shutdown.send(()).unwrap(); + } +} +#[tokio::test] +async fn secret_description_uses_the_sql_metadata_projection() { + let result = RecordBatch::try_from_iter(vec![ + ( + "name", + Arc::new(StringArray::from(vec!["api-key"])) as ArrayRef, + ), + ( + "created_at_millis", + Arc::new(arrow_array::Int64Array::from(vec![1])) as ArrayRef, + ), + ( + "updated_at_millis", + Arc::new(arrow_array::Int64Array::from(vec![2])) as ArrayRef, + ), + ]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: true, + result, + ..Default::default() + }; + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client); + let info = db.describe_secret("api-key", &[]).await.unwrap(); + assert_eq!(info.name, "api-key"); + assert_eq!(info.updated_at_millis, 2); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { + for defer in [false, true] { + let first_result = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringArray::from(vec!["api-key", "hf'prod", "openai-prod"])) as ArrayRef, + )]) + .unwrap(); + let second_result = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef, + )]) + .unwrap(); + let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([ + ("SHOW SECRETS LIMIT 3".to_string(), first_result), + ( + "SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3".to_string(), + second_result, + ), + ]))); + let service = TestSqlService { + adaptive: true, + defer, + result_overrides, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (client, shutdown) = start_sql_service_with_prefix( + service, + ClientConfig::default(), + Some("tenant/production"), + ) + .await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client); + let namespace = vec!["team".to_owned(), "reports".to_owned()]; + + let first = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!(first.items, ["api-key", "hf'prod"]); + let token = first.page_token.expect("a third row must produce a token"); + + let second = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(&token), + ) + .await + .unwrap(); + assert_eq!(second.items, ["openai-prod"]); + assert!(second.page_token.is_none()); + + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW SECRETS LIMIT 3", + "SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3" + ] + ); + { + let headers = headers.lock().unwrap(); + assert!(!headers.is_empty()); + for header in headers.iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); + } + } + + for (path, token) in [ + (vec!["other".to_owned()], token), + (namespace.clone(), "invalid".to_owned()), + ] { + assert!(matches!( + db.list_secrets( + &path, + crate::listing::ListingOptions::default().page_token(token) + ) + .await, + Err(Error::InvalidInput { .. }) + )); + } + assert_eq!(statements.lock().unwrap().len(), 2); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn secret_listing_handles_empty_pages_and_rejects_invalid_limits() { + let empty = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringArray::from(Vec::::new())) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: true, + result: empty, + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client); + let namespace = vec!["team".to_owned(), "reports".to_owned()]; + + let page = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(""), + ) + .await + .unwrap(); + assert!(page.items.is_empty()); + assert!(page.page_token.is_none()); + + for limit in [0, i32::MAX as u32 + 1] { + assert!(matches!( + db.list_secrets( + &namespace, + crate::listing::ListingOptions::default().page_limit(limit) + ) + .await, + Err(Error::InvalidInput { .. }) + )); + } + assert_eq!(*statements.lock().unwrap(), ["SHOW SECRETS LIMIT 3"]); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() { + const VERSION: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut second: serde_json::Value = serde_json::from_str(VERSION).unwrap(); + second["version"] = serde_json::json!("2"); + let second = second.to_string(); + let mut tenth: serde_json::Value = serde_json::from_str(VERSION).unwrap(); + tenth["version"] = serde_json::json!("10"); + let tenth = tenth.to_string(); + let result = RecordBatch::try_from_iter(vec![( + "definition", + Arc::new(StringArray::from(vec![ + VERSION, + second.as_str(), + tenth.as_str(), + ])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: true, + result, + ..Default::default() + }; + service.result_overrides.lock().unwrap().insert( + "SHOW FUNCTIONS HISTORY WITH (limit = 3, include_definition = true, after_name = 'embed', after_version = '2')".into(), + RecordBatch::try_from_iter(vec![("definition", Arc::new(StringArray::from(vec![tenth.as_str()])) as ArrayRef)]).unwrap(), + ); + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client); + let first = db + .list_functions( + &["team".into()], + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!( + first + .items + .iter() + .map(|item| item.version()) + .collect::>(), + ["1", "2"] + ); + let token = first.page_token.unwrap(); + let second = db + .list_functions( + &["team".into()], + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(token.clone()), + ) + .await + .unwrap(); + assert_eq!(second.items.len(), 1); + assert_eq!(second.items[0].version(), "10"); + assert!(second.page_token.is_none()); + assert!( + db.list_functions( + &["other".into()], + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(token) + ) + .await + .is_err() + ); + let seen = statements.lock().unwrap(); + assert_eq!(seen.len(), 2); + assert!(seen[0].starts_with("SHOW FUNCTIONS HISTORY WITH (limit = 3,")); + assert!(seen[1].contains("after_version = '2'")); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn view_create_and_describe_return_metadata_through_sql() { + let schema = r#"{"fields":[{"name":"name","nullable":true,"type":{"type":"utf8"}}],"metadata":{"lancedb::view::default_db":"db","lancedb::view::default_namespace":"team"}}"#; + for defer in [false, true] { + let result = RecordBatch::try_from_iter(vec![ + ( + "name", + Arc::new(StringArray::from(vec!["adults"])) as ArrayRef, + ), + ( + "query", + Arc::new(StringArray::from(vec!["SELECT name FROM people"])) as ArrayRef, + ), + ( + "schema", + Arc::new(StringArray::from(vec![schema])) as ArrayRef, + ), + ]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client); + let created = db + .create_view("adults", "SELECT name FROM people", &["team".into()]) + .await + .unwrap(); + let described = db.describe_view("adults", &["team".into()]).await.unwrap(); + assert_eq!(created, described); + assert_eq!(created.schema.fields()[0].name(), "name"); + assert_eq!(created.default_namespace_path, ["team"]); + assert_eq!( + statements.lock().unwrap().as_slice(), + [ + "CREATE VIEW \"adults\" AS SELECT name FROM people", + "DESCRIBE VIEW \"adults\"" + ] + ); + shutdown.send(()).unwrap(); + } +} +#[tokio::test] +async fn view_drop_uses_a_repeatable_query_job() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client.clone()); + let job = db + .drop_view_async("adults", &["team".into()]) + .await + .unwrap(); + assert_eq!(job.job_type().as_deref(), Some("query")); + let id = Uuid::parse_str(job.id().unwrap()).unwrap(); + job.wait().await.unwrap(); + job.wait().await.unwrap(); + assert_eq!( + client.describe(id).await.unwrap().status, + QueryStatus::Finished + ); + assert_eq!( + statements.lock().unwrap().as_slice(), + ["DROP VIEW \"adults\""] + ); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn view_listing_uses_bounded_sql_and_scoped_cursors() { + for defer in [false, true] { + let first_result = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringArray::from(vec!["adults", "hf'prod", "openai-prod"])) as ArrayRef, + )]) + .unwrap(); + let second_result = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef, + )]) + .unwrap(); + let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([ + ("SHOW VIEWS LIMIT 3".to_string(), first_result), + ( + "SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3".to_string(), + second_result, + ), + ]))); + let service = TestSqlService { + adaptive: true, + defer, + result_overrides, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (client, shutdown) = start_sql_service_with_prefix( + service, + ClientConfig::default(), + Some("tenant/production"), + ) + .await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client); + let connection = Connection::new( + Arc::new(db), + Arc::new(crate::embeddings::MemoryRegistry::new()), + ); + let namespace = vec!["team".to_owned(), "reports".to_owned()]; + + let first = connection + .list_views( + &namespace, + crate::listing::ListingOptions::default().page_limit(2), + ) + .next_page() + .await + .unwrap() + .unwrap(); + assert_eq!(first.items, ["adults", "hf'prod"]); + let token = first.page_token.expect("a third row must produce a token"); + + let second = connection + .list_views( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(&token), + ) + .next_page() + .await + .unwrap() + .unwrap(); + assert_eq!(second.items, ["openai-prod"]); + assert!(second.page_token.is_none()); + + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW VIEWS LIMIT 3", + "SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3" + ] + ); + { + let headers = headers.lock().unwrap(); + assert!(!headers.is_empty()); + for header in headers.iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); + } + } + + let encode_token = + |kind: &str, database: &str, prefix: Option<&str>, path: &[String], last: &str| { + URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&(kind, database, prefix, path.to_vec(), last)).unwrap(), + ) + }; + for forged in [ + encode_token( + "secret", + "analytics", + Some("tenant/production"), + &namespace, + "hf'prod", + ), + encode_token( + "view", + "billing", + Some("tenant/production"), + &namespace, + "hf'prod", + ), + encode_token("view", "analytics", Some("other"), &namespace, "hf'prod"), + encode_token( + "view", + "analytics", + Some("tenant/production"), + &["other".to_owned()], + "hf'prod", + ), + "not-a-json-token".to_string(), + ] { + let mut listing = connection.list_views( + &namespace, + crate::listing::ListingOptions::default().page_token(forged), + ); + assert!(matches!( + listing.next_page().await, + Err(Error::InvalidInput { .. }) + )); + } + let mut listing = connection.list_views( + &["other".to_owned()], + crate::listing::ListingOptions::default().page_token(&token), + ); + assert!(matches!( + listing.next_page().await, + Err(Error::InvalidInput { .. }) + )); + assert_eq!(statements.lock().unwrap().len(), 2); + shutdown.send(()).unwrap(); + } +} + +#[test] +fn sql_status_keeps_input_category_and_request_ids() { + for (code, category) in [ + (tonic::Code::InvalidArgument, "column_not_found"), + (tonic::Code::InvalidArgument, "schema_mismatch"), + (tonic::Code::NotFound, "table_not_found"), + (tonic::Code::NotFound, "reference_not_found"), + (tonic::Code::Internal, "column_not_found"), + ] { + let mut status = tonic::Status::new(code, "original diagnostic"); + status + .metadata_mut() + .insert("x-lancedb-error-code", category.parse().unwrap()); + status + .metadata_mut() + .insert("x-job-request-id", "worker-request".parse().unwrap()); + for job_id in [None, Some("sql-job-1")] { + if let Some(job_id) = job_id { + status + .metadata_mut() + .insert("x-lancedb-sql-job-id", job_id.parse().unwrap()); + } + let error = super::sql_status_error("current-request", &status); + assert_eq!( + error.remote_error_metadata().unwrap().job_id.as_deref(), + job_id + ); + let source = match &error { + Error::JobFailed { + job_id: actual_job_id, + failure, + } => { + assert_eq!(actual_job_id.as_deref(), job_id); + assert_eq!(failure.sql_job_id.as_deref(), job_id); + failure.source.as_deref().unwrap() + } + error => { + assert!(job_id.is_none()); + error + } + }; + let Error::Sql { + message, + request_id, + grpc_code, + metadata, + } = source + else { + panic!("SQL status must remain structured: {source}"); + }; + assert_eq!(message, "original diagnostic"); + assert_eq!(request_id, "current-request"); + assert_eq!(*grpc_code, code as i32); + assert_eq!(metadata.error_code.as_deref(), Some(category)); + assert_eq!(metadata.job_id.as_deref(), job_id); + assert_eq!(metadata.job_request_id.as_deref(), Some("worker-request")); + } + } + let error = super::sql_status_error("request", &tonic::Status::not_found("column_not_found")); + assert!(error.remote_error_metadata().unwrap().error_code.is_none()); +} + +#[test] +fn sql_status_reports_structured_resource_identity() { + let mut status = tonic::Status::not_found("Function 'missing' was not found"); + status + .metadata_mut() + .insert("x-lancedb-error-code", "not_found".parse().unwrap()); + status.metadata_mut().insert( + "x-lancedb-resource", + "eyJraW5kIjoiZnVuY3Rpb24iLCJuYW1lIjoibWlzc2luZyIsIm5hbWVzcGFjZV9wYXRoIjpbIm5zIl19" + .parse() + .unwrap(), + ); + status + .metadata_mut() + .insert("x-lancedb-sql-job-id", "sql-job-1".parse().unwrap()); + + let error = super::sql_status_error("current-request", &status); + let resource = error + .remote_error_metadata() + .unwrap() + .resource + .as_ref() + .unwrap(); + assert_eq!(resource.kind, "function"); + assert_eq!(resource.name, "missing"); + assert_eq!(resource.namespace_path, ["ns"]); +} + +#[tokio::test] +async fn remote_optimize_forwards_per_job_options_on_main_and_branch() { + for branch in [None, Some("o'brien")] { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into()], + "team$events".into(), + Default::default(), + Some(sql_client), + ) + .with_branch(branch.map(str::to_string)); + table + .optimize(crate::table::optimize::OptimizeAction::Compact { + options: crate::table::optimize::CompactionOptions { + target_rows_per_fragment: 100, + max_source_rows: Some(500), + io_buffer_size: Some(0), + batch_size: Some(16), + ..Default::default() + }, + remap_options: None, + }) + .await + .unwrap(); + let prefix = if branch.is_some() { + "branch = 'o''brien', " + } else { + "" + }; + assert_eq!( + *statements.lock().unwrap(), + [format!( + "OPTIMIZE \"events\" REWRITE DATA WITH ({prefix}target_rows_per_fragment = 100, max_source_rows = 500, io_buffer_size = 0, batch_size = 16)" + )] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "team") + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_compact_preserves_omissions_and_explicit_default_values() { + use crate::table::{CompactionOptions, CompactionOverrides}; + let target = CompactionOptions::default().target_rows_per_fragment; + for (options, suffix) in [ + (CompactionOverrides::default(), String::new()), + ( + CompactionOverrides { + target_rows_per_fragment: Some(target), + ..Default::default() + }, + format!(" WITH (target_rows_per_fragment = {target})"), + ), + ( + CompactionOverrides { + io_buffer_size: Some(0), + ..Default::default() + }, + " WITH (io_buffer_size = 0)".into(), + ), + ] { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ); + table.compact(options).await.unwrap(); + assert_eq!( + *statements.lock().unwrap(), + [format!("OPTIMIZE \"events\" REWRITE DATA{suffix}")] + ); + shutdown.send(()).unwrap(); + } +} diff --git a/rust/lancedb/src/remote/storage_integration.rs b/rust/lancedb/src/remote/storage_integration.rs new file mode 100644 index 000000000..bdba4f1df --- /dev/null +++ b/rust/lancedb/src/remote/storage_integration.rs @@ -0,0 +1,392 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use arrow_array::{ + Array, BooleanArray, Int64Array, LargeStringArray, RecordBatch, StringArray, StringViewArray, +}; +use serde_json::Value; + +use crate::storage_integration::{ + CreateStorageIntegrationRequest, SecretReference, StorageIntegrationInfo, StorageProvider, +}; +use crate::utils::{validate_database_name, validate_namespace, validate_secret_name}; +use crate::{Error, Result}; + +fn invalid(message: impl Into) -> Error { + Error::InvalidInput { + message: message.into(), + } +} + +pub(super) fn identifier(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +fn literal(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} + +pub(super) fn object_name(name: &str, namespace: &[String]) -> Result { + validate_secret_name(name)?; + validate_namespace(namespace)?; + Ok(identifier(name)) +} + +fn secret_name(reference: &SecretReference) -> Result { + validate_secret_name(&reference.name)?; + validate_namespace(&reference.namespace_path)?; + let mut parts = Vec::new(); + if let Some(database) = &reference.database { + validate_database_name(database)?; + parts.push(identifier(database)); + } + if reference.namespace_path.is_empty() { + parts.push(identifier("public")); + } else { + parts.extend(reference.namespace_path.iter().map(|name| identifier(name))); + } + parts.push(identifier(&reference.name)); + Ok(parts.join(".")) +} + +pub(super) fn create_sql( + name: &str, + namespace: &[String], + request: &CreateStorageIntegrationRequest, +) -> Result { + if request.storage_provider != StorageProvider::HuggingFace + && request.huggingface_token_secret.is_some() + { + return Err(invalid( + "Hugging Face credential options require storage_provider HUGGINGFACE", + )); + } + if request.storage_provider == StorageProvider::HuggingFace { + if request.aws_role_arn.is_some() + || request.aws_access_key_id_secret.is_some() + || request.aws_secret_access_key_secret.is_some() + || request.aws_region.is_some() + || request.azure_storage_account.is_some() + || request.azure_tenant_id_secret.is_some() + || request.azure_client_id_secret.is_some() + || request.azure_client_secret_secret.is_some() + || request.gcp_credentials_json_secret.is_some() + { + return Err(invalid( + "Hugging Face integrations cannot contain AWS, Azure or GCP options", + )); + } + let mut sql = format!( + "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", + object_name(name, namespace)?, + literal(&request.storage_prefix) + ); + if let Some(reference) = &request.huggingface_token_secret { + sql.push_str(&format!( + " HUGGINGFACE_TOKEN_SECRET = {}", + secret_name(reference)? + )); + } + return Ok(sql); + } + if request.storage_provider != StorageProvider::Gcp + && request.gcp_credentials_json_secret.is_some() + { + return Err(invalid( + "GCP credential options require storage_provider GCP", + )); + } + if request.storage_provider == StorageProvider::Gcp { + if request.aws_role_arn.is_some() + || request.aws_access_key_id_secret.is_some() + || request.aws_secret_access_key_secret.is_some() + || request.aws_region.is_some() + || request.azure_storage_account.is_some() + || request.azure_tenant_id_secret.is_some() + || request.azure_client_id_secret.is_some() + || request.azure_client_secret_secret.is_some() + { + return Err(invalid( + "GCP integrations cannot contain AWS or Azure options", + )); + } + let reference = request + .gcp_credentials_json_secret + .as_ref() + .ok_or_else(|| invalid("GCP integrations require gcp_credentials_json_secret"))?; + return Ok(format!( + "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", + object_name(name, namespace)?, + literal(&request.storage_prefix), + secret_name(reference)? + )); + } + if request.storage_provider == StorageProvider::Azure { + if request.aws_role_arn.is_some() + || request.aws_access_key_id_secret.is_some() + || request.aws_secret_access_key_secret.is_some() + || request.aws_region.is_some() + { + return Err(invalid("Azure integrations cannot contain AWS options")); + } + let account = request + .azure_storage_account + .as_ref() + .filter(|account| !account.is_empty()) + .ok_or_else(|| invalid("Azure integrations require azure_storage_account"))?; + let mut sql = format!( + "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", + object_name(name, namespace)?, + literal(&request.storage_prefix), + literal(account) + ); + for (key, reference) in [ + ( + "STORAGE_AZURE_TENANT_ID_SECRET", + &request.azure_tenant_id_secret, + ), + ( + "STORAGE_AZURE_CLIENT_ID_SECRET", + &request.azure_client_id_secret, + ), + ( + "STORAGE_AZURE_CLIENT_SECRET_SECRET", + &request.azure_client_secret_secret, + ), + ] { + let reference = reference.as_ref().ok_or_else(|| { + invalid("Azure integrations require all three credential Secret references") + })?; + sql.push_str(&format!(" {key} = {}", secret_name(reference)?)); + } + return Ok(sql); + } + if request.azure_storage_account.is_some() + || request.azure_tenant_id_secret.is_some() + || request.azure_client_id_secret.is_some() + || request.azure_client_secret_secret.is_some() + { + return Err(invalid("S3 integrations cannot contain Azure options")); + } + let mut sql = format!( + "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", + object_name(name, namespace)?, + literal(&request.storage_prefix) + ); + match ( + &request.aws_role_arn, + &request.aws_access_key_id_secret, + &request.aws_secret_access_key_secret, + ) { + (Some(role), None, None) => { + sql.push_str(&format!(" STORAGE_AWS_ROLE_ARN = {}", literal(role))) + } + (None, Some(key), Some(secret)) => sql.push_str(&format!( + " STORAGE_AWS_ACCESS_KEY_ID_SECRET = {} STORAGE_AWS_SECRET_ACCESS_KEY_SECRET = {}", + secret_name(key)?, + secret_name(secret)? + )), + _ => { + return Err(invalid( + "Specify either an AWS role or both credential Secret references", + )); + } + } + if let Some(region) = &request.aws_region { + sql.push_str(&format!(" STORAGE_AWS_REGION = {}", literal(region))); + } + Ok(sql) +} + +fn string_value(column: &dyn Array, row: usize) -> Option<&str> { + if let Some(array) = column.as_any().downcast_ref::() { + Some(array.value(row)) + } else if let Some(array) = column.as_any().downcast_ref::() { + Some(array.value(row)) + } else if let Some(array) = column.as_any().downcast_ref::() { + Some(array.value(row)) + } else { + None + } +} + +pub(super) fn decode_info(batches: &[RecordBatch]) -> Result { + let mut rows = batches.iter().filter(|batch| batch.num_rows() > 0); + let batch = rows + .next() + .ok_or_else(|| invalid("SQL returned no storage integration"))?; + if batch.num_rows() != 1 || rows.next().is_some() { + return Err(invalid("SQL must return exactly one storage integration")); + } + let mut values = serde_json::Map::new(); + for (field, column) in batch.schema().fields().iter().zip(batch.columns()) { + let mut value = if column.is_null(0) { + Value::Null + } else if let Some(value) = string_value(column.as_ref(), 0) { + Value::String(value.into()) + } else if let Some(array) = column.as_any().downcast_ref::() { + Value::Bool(array.value(0)) + } else if let Some(array) = column.as_any().downcast_ref::() { + Value::from(array.value(0)) + } else { + return Err(invalid(format!("Unexpected SQL type for {}", field.name()))); + }; + if matches!( + field.name().as_str(), + "namespace_path" + | "aws_access_key_id_secret" + | "aws_secret_access_key_secret" + | "azure_tenant_id_secret" + | "azure_client_id_secret" + | "azure_client_secret_secret" + | "gcp_credentials_json_secret" + | "huggingface_token_secret" + | "trust_policy" + | "permissions_policy" + ) && let Some(json) = value.as_str() + { + value = serde_json::from_str(json) + .map_err(|error| invalid(format!("Invalid {} metadata: {error}", field.name())))?; + } + values.insert(field.name().clone(), value); + } + serde_json::from_value(Value::Object(values)) + .map_err(|error| invalid(format!("Invalid storage integration SQL result: {error}"))) +} + +pub(super) fn decode_names(batches: &[RecordBatch]) -> Result> { + let mut names = Vec::new(); + for batch in batches { + let column = batch + .column_by_name("name") + .ok_or_else(|| invalid("SQL storage integration listing is missing names"))?; + for row in 0..batch.num_rows() { + if column.is_null(row) { + return Err(invalid("SQL storage integration name cannot be null")); + } + names.push( + string_value(column.as_ref(), row) + .ok_or_else(|| { + invalid("SQL storage integration listing requires string names") + })? + .to_string(), + ); + } + } + names.sort(); + Ok(names) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + + #[test] + fn sql_quotes_values_and_keeps_secret_root_namespace_explicit() { + let role = CreateStorageIntegrationRequest::s3("s3://bucket/it's/", "role'value"); + let sql = create_sql("raw", &[], &role).unwrap(); + assert!(sql.contains("STORAGE_PREFIX = 's3://bucket/it''s/'")); + assert!(sql.contains("STORAGE_AWS_ROLE_ARN = 'role''value'")); + let reference = SecretReference::new("key").with_database("platform/raw"); + let static_config = CreateStorageIntegrationRequest::s3_with_secrets( + "s3://bucket/raw/", + reference.clone(), + reference, + ); + let sql = create_sql("raw", &["nested".into()], &static_config).unwrap(); + assert!( + sql.contains("STORAGE_AWS_ACCESS_KEY_ID_SECRET = \"platform/raw\".\"public\".\"key\"") + ); + assert!(create_sql("a/b", &[], &role).is_err()); + } + + #[test] + fn gcp_sql_accepts_one_secret_object_and_rejects_mixed_modes() { + let mut request = CreateStorageIntegrationRequest::gcp( + "gs://customer-data/raw/", + SecretReference::new("gcp") + .with_database("shared") + .with_namespace(vec!["credentials".into()]), + ); + let sql = create_sql("gcs", &[], &request).unwrap(); + assert!(sql.contains("STORAGE_PROVIDER = 'GCP'")); + assert!(sql.contains("GCP_CREDENTIALS_JSON_SECRET = \"shared\".\"credentials\".\"gcp\"")); + assert!(!sql.contains("STORAGE_AWS")); + request.aws_region = Some("us-east-1".into()); + assert!(create_sql("gcs", &[], &request).is_err()); + request.aws_region = None; + request.gcp_credentials_json_secret = None; + assert!(create_sql("gcs", &[], &request).is_err()); + } + + #[test] + fn azure_sql_uses_only_explicit_account_and_three_secret_objects() { + let reference = SecretReference::new("credential") + .with_database("shared") + .with_namespace(vec!["credentials".into()]); + let mut config = CreateStorageIntegrationRequest::azure( + "az://container/raw/", + "customeraccount", + reference.clone(), + reference.clone(), + reference, + ); + let sql = create_sql("blobs", &[], &config).unwrap(); + assert!(sql.contains("STORAGE_PROVIDER = 'AZURE'")); + assert!(sql.contains("STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount'")); + assert!(sql.contains( + "STORAGE_AZURE_CLIENT_SECRET_SECRET = \"shared\".\"credentials\".\"credential\"" + )); + assert!(!sql.contains("STORAGE_AWS")); + config.azure_tenant_id_secret = None; + assert!(create_sql("blobs", &[], &config).is_err()); + config.aws_region = Some("us-east-1".into()); + assert!(create_sql("blobs", &[], &config).is_err()); + } + + #[test] + fn sql_metadata_rejects_missing_rows_and_invalid_json() { + assert!(decode_info(&[]).is_err()); + let batch = RecordBatch::try_from_iter([( + "namespace_path", + Arc::new(StringArray::from(vec!["invalid json"])) as arrow_array::ArrayRef, + )]) + .unwrap(); + assert!( + decode_info(&[batch]) + .unwrap_err() + .to_string() + .contains("namespace_path") + ); + } +} + +#[cfg(test)] +mod huggingface_tests { + use super::*; + + #[test] + fn huggingface_renders_optional_secret_and_rejects_mixed_auth() { + let mut request = + CreateStorageIntegrationRequest::huggingface("hf://datasets/acme/private/raw/") + .with_huggingface_token_secret( + SecretReference::new("token") + .with_database("shared") + .with_namespace(vec!["credentials".into()]), + ); + let sql = create_sql("hub", &[], &request).unwrap(); + assert!(sql.contains("STORAGE_PROVIDER = 'HUGGINGFACE'")); + assert!(sql.contains("HUGGINGFACE_TOKEN_SECRET = \"shared\".\"credentials\".\"token\"")); + request.gcp_credentials_json_secret = Some(SecretReference::new("gcp")); + assert!(create_sql("hub", &[], &request).is_err()); + request.gcp_credentials_json_secret = None; + request.huggingface_token_secret = None; + assert!( + !create_sql("hub", &[], &request) + .unwrap() + .contains("HUGGINGFACE_TOKEN_SECRET") + ); + } +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index d997b64db..9ba767bb1 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3,6 +3,8 @@ pub mod blobs; pub mod insert; +mod ipc_stream; +mod optimize; use self::insert::{RemoteWriteExec, WriteOp}; use super::client::RequestResultExt; @@ -12,6 +14,7 @@ use super::sql::SqlClient; use super::{ARROW_FILE_CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE, extract_job_id}; use crate::blob::BlobFile; use crate::data::scannable::{PeekedScannable, Scannable, estimate_write_partitions}; +use crate::error::{HttpErrorSource, RemoteErrorMetadata}; use crate::expr::expr_to_sql_string; use crate::index::Index; use crate::index::IndexStatistics; @@ -59,15 +62,15 @@ use crate::{ }, }; use arrow_array::{LargeBinaryArray, RecordBatch}; -use arrow_ipc::reader::{FileReader, StreamReader}; -use arrow_schema::{ArrowError, DataType, SchemaRef}; +use arrow_ipc::reader::FileReader; +use arrow_schema::{DataType, SchemaRef}; use async_trait::async_trait; use chrono::{DateTime, Utc}; use datafusion_common::DataFusionError; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use datafusion_physical_plan::{ExecutionPlan, RecordBatchStream, SendableRecordBatchStream}; use futures::{StreamExt, TryStreamExt}; -use http::header::CONTENT_TYPE; +use http::header::{ACCEPT, CONTENT_TYPE}; use http::{HeaderName, StatusCode}; use lance::arrow::json::{JsonDataType, JsonSchema}; use lance::dataset::refs::TagContents; @@ -89,6 +92,10 @@ const MIN_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-ve const MIN_TIMESTAMP_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-timestamp"); const MIN_READ_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-read-version"); const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version"); +/// Asks for stream framing, which is decoded as it arrives. Servers that do not +/// stream query results ignore this and answer with file framing. +const QUERY_ACCEPT: &str = + "application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9"; const METRIC_TYPE_KEY: &str = "metric_type"; const INDEX_TYPE_KEY: &str = "index_type"; const SCHEMA_CACHE_TTL: Duration = Duration::from_secs(30); @@ -289,7 +296,14 @@ impl crate::job::JobHandle for FreshnessJob { } async fn wait(&self) -> Result { - let result = crate::job::JobHandle::wait(&self.inner).await?; + crate::job::JobHandle::wait_with_progress(self, None).await + } + + async fn wait_with_progress( + &self, + progress: Option, + ) -> Result { + let result = crate::job::JobHandle::wait_with_progress(&self.inner, progress).await?; let version = self.version.read().await; if version.is_none() { let result_version = match self.tracked_result { @@ -325,6 +339,82 @@ impl crate::job::JobHandle for FreshnessJob { } } +/// A registry-backed materialized-view refresh. Registry completion is only +/// the first half of `wait`; the submitting handle still has to observe the +/// committed table version before reporting the typed refresh result. +struct MaterializedViewRefreshJob { + inner: RemoteJob, + client: RestfulLanceDbClient, + db_name: String, + name: String, + namespace: Vec, + identifier: String, + server_version: ServerVersion, + sql_client: Option, + freshness: Arc>, + freshness_request: FreshnessHeaders, +} + +#[async_trait] +impl crate::job::JobHandle for MaterializedViewRefreshJob { + fn id(&self) -> Option<&str> { + crate::job::JobHandle::id(&self.inner) + } + + async fn status(&self) -> Result { + crate::job::JobHandle::status(&self.inner).await + } + + async fn describe(&self) -> Result { + crate::job::JobHandle::describe(&self.inner).await + } + + async fn events( + &self, + request: crate::job::JobEventsRequest, + ) -> Result> { + crate::job::JobHandle::events(&self.inner, request).await + } + + async fn wait(&self) -> Result { + crate::job::JobHandle::wait_with_progress(self, None).await + } + + async fn wait_with_progress( + &self, + progress: Option, + ) -> Result { + let result = crate::job::JobHandle::wait_with_progress(&self.inner, progress).await?; + let table = RemoteTable::new_with_sql_client( + self.client.clone(), + self.db_name.clone(), + self.name.clone(), + self.namespace.clone(), + self.identifier.clone(), + self.server_version.clone(), + self.sql_client.clone(), + ); + table.checkout_latest().await?; + let version = table.version().await?; + self.freshness_request + .observe_version(&self.freshness, version); + let refresh = RefreshMaterializedViewResult { + mode: None, + rows_written: None, + source_version: None, + version, + }; + let value = serde_json::to_value(refresh).map_err(|error| Error::Runtime { + message: format!("failed to encode materialized-view refresh result: {error}"), + })?; + Ok(result.with_value(value)) + } + + async fn cancel(&self) -> Result<()> { + crate::job::JobHandle::cancel(&self.inner).await + } +} + fn compute_min_timestamp( state: &FreshnessState, interval: Option, @@ -346,6 +436,10 @@ fn quote_sql_identifier(identifier: &str) -> String { format!("\"{}\"", identifier.replace('"', "\"\"")) } +fn quote_sql_string(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} + fn freshness_headers_snapshot( freshness: &Mutex, interval: Option, @@ -491,6 +585,7 @@ impl Tags for RemoteTags<'_, S> { pub struct RemoteTable { client: RestfulLanceDbClient, + db_name: String, name: String, namespace: Vec, identifier: String, @@ -519,6 +614,48 @@ impl std::fmt::Debug for RemoteTable { } impl RemoteTable { + fn table_overrides_query(&self) -> Vec<(&str, &str)> { + let mut query = Vec::with_capacity(3 + self.namespace.len()); + query.push(("db", self.db_name.as_str())); + query.push(("table", self.name.as_str())); + for namespace in &self.namespace { + query.push(("namespace", namespace.as_str())); + } + if let Some(branch) = self.branch.as_deref() { + query.push(("branch", branch)); + } + query + } + + fn table_overrides_set_body(&self, overrides: serde_json::Value) -> serde_json::Value { + let mut body = serde_json::json!({ + "db": &self.db_name, + "namespace": &self.namespace, + "table": &self.name, + "overrides": overrides, + }); + if let Some(branch) = &self.branch { + body["branch"] = serde_json::Value::String(branch.clone()); + } + body + } + + fn merge_table_overrides( + target: &mut serde_json::Map, + patch: serde_json::Map, + ) { + for (key, value) in patch { + match (target.get_mut(&key), value) { + (Some(serde_json::Value::Object(existing)), serde_json::Value::Object(patch)) => { + Self::merge_table_overrides(existing, patch); + } + (_, value) => { + target.insert(key, value); + } + } + } + } + async fn submit_create_index(&self, mut index: IndexBuilder) -> Result> { self.check_mutable().await?; let request = self @@ -569,7 +706,7 @@ impl RemoteTable { // Warn if train=false is specified since it's not meaningful if !index.train { log::warn!( - "train=false has no effect in LanceDB Distributed. The index will be created empty and automatically populated in the background." + "train=false has no effect in LanceDB Enterprise. The index will be created empty and automatically populated in the background." ); } @@ -623,7 +760,7 @@ impl RemoteTable { } Index::IvfHnswPq(_) => { return Err(Error::NotSupported { - message: "IVF_HNSW_PQ is not supported in LanceDB Distributed. Please use IVF_HNSW_SQ instead.".into(), + message: "IVF_HNSW_PQ is not supported in LanceDB Enterprise. Please use IVF_HNSW_SQ instead.".into(), }); } }; @@ -686,6 +823,7 @@ impl RemoteTable { pub(super) fn new_with_sql_client( client: RestfulLanceDbClient, + db_name: String, name: String, namespace: Vec, identifier: String, @@ -694,6 +832,7 @@ impl RemoteTable { ) -> Self { Self { client, + db_name, name, namespace, identifier, @@ -718,17 +857,18 @@ impl RemoteTable { return; }; self.track_read_version(description.version); - if let Ok(schema) = arrow_schema::Schema::try_from(description.schema) { - self.schema_cache.seed(Arc::new(schema)); + if let Ok(schema) = schema_from_description(description.schema) { + self.schema_cache.seed(schema); } } /// Return a new handle scoped to `branch`, sharing the client but with fresh /// caches and version/freshness state (the branch tracks its own latest). /// Mirrors `NativeTable`'s handle-per-branch model. - fn with_branch(&self, branch: Option) -> Self { + pub(super) fn with_branch(&self, branch: Option) -> Self { Self { client: self.client.clone(), + db_name: self.db_name.clone(), name: self.name.clone(), namespace: self.namespace.clone(), identifier: self.identifier.clone(), @@ -790,7 +930,7 @@ impl RemoteTable { } let description = self.describe_read_snapshot(read_snapshot).await?; - Ok(Arc::new(description.schema.try_into()?)) + schema_from_description(description.schema) } async fn resolve_tag_version_with_request( @@ -953,9 +1093,10 @@ impl RemoteTable { ) -> Result { let status = response.status(); if status == StatusCode::NOT_FOUND { + let metadata = RemoteErrorMetadata::from_headers(response.headers()); let body = response.text().await.ok().unwrap_or_default(); let request_error = Error::Http { - source: body.into(), + source: Box::new(HttpErrorSource::new(body.clone(), Some(&body), metadata)), request_id: request_id.into(), status_code: Some(status), }; @@ -1019,25 +1160,30 @@ impl RemoteTable { .map(str::to_owned); let framing = resolve_arrow_ipc_framing(content_type.as_deref(), request_id)?; - // Buffer the whole body. File framing keeps its footer at the end, so /query - // cannot decode incrementally. Stream framing could, via - // arrow_ipc::reader::StreamDecoder, but fetch_blobs concatenates every batch - // before returning, so no caller would see data sooner. - let body = response.bytes().await.err_to_http(request_id.into())?; - type IpcBatchIterator = - Box> + Send>; - let (schema, batches): (SchemaRef, IpcBatchIterator) = match framing { + match framing { ArrowIpcFraming::Stream => { - let reader = StreamReader::try_new(Cursor::new(body), None)?; - (reader.schema(), Box::new(reader)) + let table_version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse().ok()); + ipc_stream::read_ipc_stream( + response.bytes_stream(), + request_id.to_string(), + table_version, + ) + .await } ArrowIpcFraming::File => { + // File framing keeps its footer at the end, so the whole body is + // needed before anything can be decoded. + let body = response.bytes().await.err_to_http(request_id.into())?; let reader = FileReader::try_new(Cursor::new(body), None)?; - (reader.schema(), Box::new(reader)) + let schema = reader.schema(); + let stream = futures::stream::iter(reader).map_err(DataFusionError::from); + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) } - }; - let stream = futures::stream::iter(batches).map_err(DataFusionError::from); - Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) + } } fn apply_query_params( @@ -1067,7 +1213,7 @@ impl RemoteTable { QueryFilter::Datafusion(expr) => expr_to_sql_string(expr)?, QueryFilter::Substrait(_) => { return Err(Error::NotSupported { - message: "Substrait filters are not supported in LanceDB Distributed" + message: "Substrait filters are not supported in LanceDB Enterprise" .to_string(), }); } @@ -1117,7 +1263,7 @@ impl RemoteTable { if let Some(full_text_search) = ¶ms.full_text_search { if full_text_search.wand_factor.is_some() { return Err(Error::NotSupported { - message: "Wand factor is not supported in LanceDB Distributed.".into(), + message: "Wand factor is not supported in LanceDB Enterprise.".into(), }); } @@ -1408,8 +1554,15 @@ impl RemoteTable { ) -> Result>>> { let mut request = self .client - .post(&format!("/v1/table/{}/query/", self.identifier)); + .post(&format!("/v1/table/{}/query/", self.identifier)) + .header(ACCEPT, QUERY_ACCEPT); + // The timeout bounds the whole query, including reading the response, as + // the server's own deadline for this request does. A deadline too far + // away to represent is never reached. + let deadline = options + .timeout + .and_then(|timeout| Some((tokio::time::Instant::now().checked_add(timeout)?, timeout))); if let Some(timeout) = options.timeout { // Also send to server, so it can abort the query if it takes too long. // (If it doesn't fit into u64, it's not worth sending anyways.) @@ -1433,28 +1586,28 @@ impl RemoteTable { }); let streams = futures::future::try_join_all(futures); - let streams = if let Some(timeout) = options.timeout { - let timeout_future = tokio::time::sleep(timeout); - tokio::pin!(timeout_future); - tokio::pin!(streams); - tokio::select! { - _ = &mut timeout_future => { - return Err(Error::Other { - message: format!("Query timeout after {} ms", timeout.as_millis()), - source: None, - }) - } - result = &mut streams => { - result? - } - } + let streams = if let Some((deadline, timeout)) = deadline { + tokio::time::timeout_at(deadline, streams) + .await + .map_err(|_| Error::Other { + message: format!("Query timeout after {} ms", timeout.as_millis()), + source: None, + })?? } else { streams.await? }; Ok(streams .into_iter() - .map(|stream| restore_projection_order(stream, &query.base().select)) + .map(|stream| { + let stream = restore_projection_order(stream, &query.base().select); + match deadline { + Some((deadline, timeout)) => { + Box::pin(TimeoutStream::with_deadline(stream, timeout, deadline)) + } + None => stream, + } + }) .collect()) } @@ -1550,8 +1703,37 @@ struct TableDescription { location: Option, } -/// How a response body frames its Arrow IPC payload. `/query` answers with file framing -/// and `fetch_blobs` with stream framing, so the reader is picked per response. +/// Keep server-owned Function assignment columns out of client schemas. +fn schema_from_description(schema: JsonSchema) -> Result { + let schema: arrow_schema::Schema = schema.try_into()?; + // Reading a schema must remain possible with newer binding metadata. + let bindings = crate::table::computed_columns::function_bindings(&schema).unwrap_or_default(); + let assignments = bindings + .iter() + .filter_map(|binding| { + binding + .assignment() + .map(|assignment| assignment.output_name.as_str()) + }) + .collect::>(); + if assignments.is_empty() { + return Ok(Arc::new(schema)); + } + let fields = schema + .fields() + .iter() + .filter(|field| !assignments.contains(field.name().as_str())) + .cloned() + .collect::>(); + Ok(Arc::new(arrow_schema::Schema::new_with_metadata( + fields, + schema.metadata, + ))) +} + +/// How a response body frames its Arrow IPC payload. `fetch_blobs` answers with stream +/// framing, and `/query` with stream framing only on servers that stream query results, +/// so the reader is picked per response. enum ArrowIpcFraming { File, Stream, @@ -1677,8 +1859,7 @@ async fn fetch_schema( }); } - let arrow_schema: arrow_schema::Schema = description.schema.try_into()?; - Ok(Arc::new(arrow_schema)) + schema_from_description(description.schema) } impl std::fmt::Display for RemoteTable { @@ -1705,6 +1886,7 @@ mod test_utils { let client = client_with_handler(handler); Self { client, + db_name: "default".to_string(), name: name.clone(), namespace: vec![], identifier: name, @@ -1731,6 +1913,7 @@ mod test_utils { let client = client_with_handler_and_interval(handler, read_consistency_interval); Self { client, + db_name: "default".to_string(), name: name.clone(), namespace: vec![], identifier: name, @@ -1766,6 +1949,7 @@ mod test_utils { let client = client_with_handler_and_config(handler, config); Self { client, + db_name: "default".to_string(), name: name.clone(), namespace: vec![], identifier: name, @@ -2213,6 +2397,17 @@ impl BaseTable for RemoteTable { source_version: Option, full: bool, ) -> Result> { + self.refresh_materialized_view_async_with_options(source_version, full, Default::default()) + .await + } + + async fn refresh_materialized_view_async_with_options( + &self, + source_version: Option, + full: bool, + options: crate::materialized_view::RefreshMaterializedViewOptions, + ) -> Result> { + let with_clause = options.sql_clause(full)?; self.check_mutable().await?; if source_version.is_some() { return Err(Error::NotSupported { @@ -2226,39 +2421,60 @@ impl BaseTable for RemoteTable { let statement = format!( "REFRESH MATERIALIZED VIEW {}{}", quote_sql_identifier(&self.name), - if full { " WITH (full = true)" } else { "" }, + with_clause, ); let namespace = self.namespace.clone(); let client = self.client.clone(); + let db_name = self.db_name.clone(); let name = self.name.clone(); let identifier = self.identifier.clone(); let server_version = self.server_version.clone(); let freshness = self.freshness.clone(); let freshness_request = self.snapshot_freshness_headers(); let job_sql_client = sql_client.clone(); - sql_client - .submit_as_job(statement, namespace.clone(), move || async move { - let table = Self::new_with_sql_client( - client, - name, - namespace, - identifier, - server_version, - Some(job_sql_client), - ); - table.checkout_latest().await?; - let version = table.version().await?; - freshness_request.observe_version(&freshness, version); - Ok(RefreshMaterializedViewResult { - // The SQL job adapter does not expose refresh metrics. Table - // metadata cannot tell us what this refresh actually did. - mode: None, - rows_written: None, - source_version: None, - version, - }) - }) - .await + let submission = sql_client + .submit_materialized_view_job(statement, self.namespace.clone()) + .await?; + match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { + job_id, + } => Ok(Job::new_typed(Box::new(MaterializedViewRefreshJob { + inner: RemoteJob::new(self.client.clone(), job_id), + client: self.client.clone(), + db_name: self.db_name.clone(), + name: self.name.clone(), + namespace: self.namespace.clone(), + identifier: self.identifier.clone(), + server_version: self.server_version.clone(), + sql_client: self.sql_client.clone(), + freshness: self.freshness.clone(), + freshness_request: self.snapshot_freshness_headers(), + }))), + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Query(query) => { + Ok(sql_client.query_job(query, move || async move { + let table = Self::new_with_sql_client( + client, + db_name, + name, + namespace, + identifier, + server_version, + Some(job_sql_client), + ); + table.checkout_latest().await?; + let version = table.version().await?; + freshness_request.observe_version(&freshness, version); + Ok(RefreshMaterializedViewResult { + // The SQL job adapter does not expose refresh metrics. Table + // metadata cannot tell us what this refresh actually did. + mode: None, + rows_written: None, + source_version: None, + version, + }) + })) + } + } } async fn query_snapshot(&self) -> Result> { let description = self.describe().await?; @@ -2267,7 +2483,7 @@ impl BaseTable for RemoteTable { schema, location, } = description; - let schema = Arc::new(arrow_schema::Schema::try_from(schema)?); + let schema = schema_from_description(schema)?; let snapshot = self.with_branch(self.branch.clone()); *snapshot.version.write().await = Some(version); *snapshot.location.write().await = location; @@ -2285,7 +2501,7 @@ impl BaseTable for RemoteTable { schema, location, } = description; - let schema = Arc::new(arrow_schema::Schema::try_from(schema)?); + let schema = schema_from_description(schema)?; let snapshot = self.with_branch(self.branch.clone()); *snapshot.version.write().await = Some(version); *snapshot.location.write().await = location; @@ -2383,6 +2599,7 @@ impl BaseTable for RemoteTable { version: u64, timestamp: Option>, timestamp_millis: Option, + manifest_size: Option, #[serde(default)] metadata: std::collections::BTreeMap, } @@ -2428,6 +2645,7 @@ impl BaseTable for RemoteTable { version: entry.version, timestamp, metadata: entry.metadata, + manifest_size: entry.manifest_size, }) }) .collect() @@ -2608,7 +2826,9 @@ impl BaseTable for RemoteTable { .client .post(&format!("/v1/table/{}/branches/delete/", self.identifier)) .json(&serde_json::json!({ "name": name })); - let (request_id, response) = self.send(request, true).await?; + // Deletion is not idempotent: preserve conflicts and partial failures + // instead of replaying a request that may already have removed the ref. + let (request_id, response) = self.send(request, false).await?; if response.status() == StatusCode::NOT_FOUND { return Err(Error::TableNotFound { name: format!("{} (branch: {})", self.name, name), @@ -2825,10 +3045,9 @@ impl BaseTable for RemoteTable { options: QueryExecutionOptions, ) -> Result> { if let AnyQuery::Query(request) = query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - return crate::query::create_take_offsets_plan(self, request, offsets, options, false) - .await; + return crate::query::create_take_plan(self, request, options, false).await; } let streams = self.execute_query(query, &options).await?; @@ -2850,16 +3069,10 @@ impl BaseTable for RemoteTable { options: QueryExecutionOptions, ) -> Result { if let AnyQuery::Query(request) = query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - let plan = crate::query::create_take_offsets_plan( - self, - request, - offsets, - options.clone(), - false, - ) - .await?; + let plan = + crate::query::create_take_plan(self, request, options.clone(), false).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 { @@ -2920,9 +3133,9 @@ impl BaseTable for RemoteTable { async fn explain_plan(&self, query: &AnyQuery, verbose: bool) -> Result { if let AnyQuery::Query(request) = query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - return crate::query::explain_take_offsets_plan(self, request, offsets, verbose).await; + return crate::query::explain_take_plan(self, request, verbose, false).await; } let base_request = self @@ -2978,10 +3191,10 @@ impl BaseTable for RemoteTable { options: QueryExecutionOptions, ) -> Result { let prepared_query = if let AnyQuery::Query(request) = query - && request.take_offsets.is_some() + && request.has_take() { Some(AnyQuery::Query( - crate::query::prepare_take_offsets_request(self, request).await?, + crate::query::prepare_take_request(self, request).await?, )) } else { None @@ -3399,6 +3612,56 @@ impl BaseTable for RemoteTable { Ok(Some(spec)) } + async fn get_table_overrides(&self) -> Result { + let request = self + .client + .get("/admin/table/overrides") + .query(&self.table_overrides_query()); + let (request_id, response) = self.send(request, true).await?; + let response = self.client.check_response(&request_id, response).await?; + response.json().await.err_to_http(request_id) + } + + async fn update_table_overrides( + &self, + overrides: serde_json::Value, + ) -> Result { + self.check_mutable().await?; + let serde_json::Value::Object(patch) = overrides else { + return Err(Error::InvalidInput { + message: "table overrides update must be a JSON object".into(), + }); + }; + + let current = self.get_table_overrides().await?; + let mut current = match current { + serde_json::Value::Object(current) => current, + other => { + return Err(Error::InvalidInput { + message: format!("table overrides response must be an object, got {other}"), + }); + } + }; + Self::merge_table_overrides(&mut current, patch); + let merged = serde_json::Value::Object(current); + let body = self.table_overrides_set_body(merged); + let request = self.client.put("/admin/table/overrides").json(&body); + let (request_id, response) = self.send(request, true).await?; + let response = self.client.check_response(&request_id, response).await?; + response.json().await.err_to_http(request_id) + } + + async fn reset_table_overrides(&self) -> Result { + self.check_mutable().await?; + let request = self + .client + .post("/admin/table/overrides/reset") + .query(&self.table_overrides_query()); + let (request_id, response) = self.send(request, true).await?; + let response = self.client.check_response(&request_id, response).await?; + response.json().await.err_to_http(request_id) + } + // WAL-PK-FUSION: delete both. fn hybrid_pk_fusion_learned(&self) -> bool { self.wal_pk_fusion.learned() @@ -3432,10 +3695,93 @@ impl BaseTable for RemoteTable { Ok(()) } - async fn optimize(&self, _action: OptimizeAction) -> Result { + /// Only `OptimizeAction::Compact` with supported `options` and no custom + /// `remap_options` is supported remotely: it submits a durable + /// compaction job through the server's `OPTIMIZE ... REWRITE DATA` + /// SQL statement, the same atomic, single-worker, index-safe path the + /// server uses for its own automatic compaction. `.wait()` below waits + /// for that SQL statement's own execution to finish, which only confirms + /// the compaction job was accepted into the server's job registry; the + /// compaction job itself then runs asynchronously on the server, so this + /// call can return well before the table is actually compacted. + /// `OptimizeStats::compaction` is `Some(CompactionMetrics::default())`, + /// a placeholder rather than `None` -- callers (including the + /// Python/Node bindings) unwrap it unconditionally on success -- because + /// the SQL job adapter does not expose per-job compaction metrics. + /// `OptimizeAction::All`, `::Prune`, and `::Index` remain unsupported + /// remotely: there is no SQL statement yet for version pruning or index + /// optimization. A branch-scoped table handle submits a + /// `WITH (branch = '')` clause; the statement does not itself + /// validate the branch exists, so a nonexistent branch surfaces as an + /// async job failure rather than an error from this call. Per-job + /// `target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and + /// `batch_size` are forwarded in the SQL `WITH` clause. Other non-default + /// options are rejected before submission. Servers must support these + /// SQL options; an older server's error is returned without retrying + /// with the settings removed. + async fn optimize(&self, action: OptimizeAction) -> Result { self.check_mutable().await?; - Err(Error::NotSupported { - message: "optimize is not supported in LanceDB Distributed.".into(), + let OptimizeAction::Compact { + options, + remap_options, + } = &action + else { + return Err(Error::NotSupported { + message: "optimize is only supported in LanceDB Enterprise for \ + OptimizeAction::Compact; version pruning and index \ + optimization are not yet supported remotely." + .into(), + }); + }; + if remap_options.is_some() { + return Err(Error::NotSupported { + message: "a custom index remap strategy is not supported in LanceDB \ + Enterprise; omit remap_options to use the server's managed, \ + index-safe compaction path." + .into(), + }); + } + let mut overrides = crate::table::optimize::CompactionOverrides::try_from(options.clone())?; + // The legacy Lance options type has no presence bit for this field. + // Use Table::compact to explicitly send a target equal to Lance's default. + if options.target_rows_per_fragment + == crate::table::CompactionOptions::default().target_rows_per_fragment + { + overrides.target_rows_per_fragment = None; + } + self.compact(overrides).await + } + + async fn compact( + &self, + options: crate::table::optimize::CompactionOverrides, + ) -> Result { + self.check_mutable().await?; + let compaction_options = optimize::compaction_sql_options(&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) + // value is built afterward. + sql_client + .submit_as_job(statement, self.namespace.clone(), || async { Ok(()) }) + .await? + .wait() + .await?; + Ok(OptimizeStats { + compaction: Some(lance::dataset::optimize::CompactionMetrics::default()), + prune: None, }) } async fn add_columns( @@ -3654,8 +4000,21 @@ impl BaseTable for RemoteTable { &self, column: &str, ) -> Result> { + self.refresh_column_async_with_options(column, Default::default()) + .await + } + + async fn refresh_column_async_with_options( + &self, + column: &str, + options: crate::table::RefreshColumnOptions, + ) -> Result> { + options.validate()?; self.check_mutable().await?; - let mut body = serde_json::json!({ "column": column }); + 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 @@ -4092,6 +4451,7 @@ mod tests { use super::*; + use crate::remote::client::test_utils::client_with_handler; use crate::remote::client::{ClientConfig, RetryConfig}; use crate::table::{AddDataMode, FieldMetadataUpdate, FtsToken}; @@ -4102,6 +4462,7 @@ mod tests { BinaryArray, Int32Array, Int64Array, RecordBatch, RecordBatchIterator, StringArray, StructArray, record_batch, }; + use arrow_ipc::reader::StreamReader; use arrow_schema::{DataType, Field, Schema}; use chrono::{DateTime, Utc}; use futures::{StreamExt, TryFutureExt, TryStreamExt, future::BoxFuture}; @@ -6570,10 +6931,9 @@ mod tests { let mut fts = FullTextSearchQuery::new("test".into()); fts.wand_factor = Some(1.0); let results = [ - ( - "optimize", - table.optimize(OptimizeAction::All).await.map(|_| ()), - ), + // `optimize` has its own action-specific messages now and its + // own dedicated tests (`test_optimize_*`), not the generic + // boilerplate this loop checks. ( "Wand factor", table @@ -6588,7 +6948,7 @@ mod tests { match result.unwrap_err() { Error::NotSupported { message } => assert_eq!( message, - format!("{operation} is not supported in LanceDB Distributed.") + format!("{operation} is not supported in LanceDB Enterprise.") ), error => panic!("expected not-supported error, got {error}"), } @@ -6616,7 +6976,7 @@ mod tests { .unwrap_err(); assert_not_supported_error( error, - "IVF_HNSW_PQ is not supported in LanceDB Distributed. Please use IVF_HNSW_SQ instead.", + "IVF_HNSW_PQ is not supported in LanceDB Enterprise. Please use IVF_HNSW_SQ instead.", ); } @@ -6780,25 +7140,36 @@ mod tests { assert_eq!(blobs.value(0), b"alpha"); } + // Read as a stream, a file's leading magic declares a message longer than the + // whole body, so the body ends before the stream does. #[rstest] - #[case(ARROW_STREAM_CONTENT_TYPE, write_ipc_file(&one_row_blob_batch("image")))] + #[case(ARROW_STREAM_CONTENT_TYPE, write_ipc_file(&one_row_blob_batch("image")), true)] #[case( ARROW_FILE_CONTENT_TYPE, - write_ipc_stream_uncompressed(&one_row_blob_batch("image")) + write_ipc_stream_uncompressed(&one_row_blob_batch("image")), + false )] #[tokio::test] async fn test_fetch_blobs_fails_when_the_body_contradicts_the_content_type( #[case] content_type: &'static str, #[case] body: Vec, + #[case] ends_early: bool, ) { let table = table_with_fetch_blobs_content_type(Some(content_type), body); let error = table.fetch_blobs("image", &[10]).await.unwrap_err(); - assert!( - matches!(error, Error::Arrow { .. }), - "expected an Arrow decode failure, got {error}" - ); + if ends_early { + assert!( + matches!(error, Error::ResponseInterrupted { batches: 0, .. }), + "expected an incomplete stream, got {error}" + ); + } else { + assert!( + matches!(error, Error::Arrow { .. }), + "expected an Arrow decode failure, got {error}" + ); + } } #[tokio::test] @@ -7070,7 +7441,8 @@ mod tests { #[rstest] #[case::unset(None)] #[case::minimum(Some(0.0))] - #[case::low(Some(0.25))] + #[case::recall80(Some(0.1))] + #[case::recall90(Some(0.25))] #[case::auto(Some(0.5))] #[case::high(Some(0.75))] #[case::maximum(Some(1.0))] @@ -7438,8 +7810,11 @@ mod tests { assert_eq!(result, "analyzed plan"); } + #[rstest::rstest] + #[case::offsets(false)] + #[case::row_ids(true)] #[tokio::test] - async fn test_take_offsets_explain_plan_does_not_execute_query() { + async fn test_take_explain_plan_does_not_execute_query(#[case] by_row_id: bool) { let table = Table::new_with_handler("my_table", |request| { assert_eq!(request.method(), "POST"); assert_eq!(request.url().path(), "/v1/table/my_table/explain_plan/"); @@ -7450,8 +7825,12 @@ mod tests { .unwrap() }); - let explained = table - .take_offsets(vec![0, 1, 0, 2]) + let take = if by_row_id { + table.take_row_ids(vec![0, 1, 0, 2]) + } else { + table.take_offsets(vec![0, 1, 0, 2]) + }; + let explained = take .select(crate::query::Select::columns(&["id"])) .limit(3) .explain_plan(false) @@ -7460,7 +7839,7 @@ mod tests { assert!(explained.contains("GlobalLimitExec")); assert!(explained.contains("TakeRestoreExec")); - assert!(!explained.contains("CoalescePartitionsExec")); + assert_eq!(explained.contains("CoalescePartitionsExec"), by_row_id); assert!(explained.contains("RemoteLookupExec")); } @@ -7513,8 +7892,11 @@ mod tests { ); } + #[rstest::rstest] + #[case::offsets(false)] + #[case::row_ids(true)] #[tokio::test] - async fn test_take_offsets_analyze_plan_delegates_to_remote() { + async fn test_take_analyze_plan_delegates_to_remote(#[case] by_row_id: bool) { let table = Table::new_with_handler("my_table", |request| { assert_eq!(request.method(), "POST"); assert_eq!(request.url().path(), "/v1/table/my_table/analyze_plan/"); @@ -7532,8 +7914,12 @@ mod tests { .unwrap() }); - let analyzed = table - .take_offsets(vec![0, 1, 0, 2]) + let take = if by_row_id { + table.take_row_ids(vec![0, 1, 0, 2]) + } else { + table.take_offsets(vec![0, 1, 0, 2]) + }; + let analyzed = take .select(crate::query::Select::columns(&["id"])) .limit(3) .analyze_plan_with_options(QueryExecutionOptions { @@ -7546,6 +7932,84 @@ mod tests { assert_eq!(analyzed, "Remote analyzed plan: worker metrics"); } + #[rstest::rstest] + #[tokio::test] + async fn test_take_row_ids_restores_remote_order( + #[values(false, true)] with_row_id: bool, + #[values(false, true)] converted: bool, + ) { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/query/"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["columns"], json!(["id"])); + assert_eq!(body["with_row_id"], true); + assert_eq!(body["k"], json!(isize::MAX as usize)); + assert!(body.get("offset").is_none()); + assert!(body["filter"].as_str().unwrap().contains("_rowid IN")); + assert!(body.get("take_row_ids").is_none()); + + // The server can return the physical rows in any order and batches. + let data = arrow_array::record_batch!( + ("id", Int32, [1, 5, 17]), + ("_rowid", UInt64, [1, 5, 17]) + ) + .unwrap(); + let mut response = Vec::new(); + { + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut response, &data.schema()).unwrap(); + writer.write(&data.slice(0, 2)).unwrap(); + writer.write(&data.slice(2, 1)).unwrap(); + writer.finish().unwrap(); + } + http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_FILE_CONTENT_TYPE) + .body(response) + .unwrap() + }); + let mut take = table + .take_row_ids(vec![17, 5, u64::MAX, 17, 1]) + .select(crate::query::Select::columns(&["id"])) + .offset(1) + .limit(3); + if with_row_id { + take = take.with_row_id(); + } + let options = QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }; + let batches = if converted { + table + .base_table() + .query(&AnyQuery::Query(take.into_request()), options) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + } else { + take.execute_with_options(options) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + }; + assert!(batches.iter().all(|batch| batch.num_rows() <= 1)); + let actual = arrow::compute::concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["id"] + .as_primitive::() + .values() + .as_ref(), + &[5, 17, 1] + ); + assert_eq!(actual.column_by_name("_rowid").is_some(), with_row_id); + } + #[tokio::test] async fn test_query_structured_fts() { let table = @@ -8043,6 +8507,28 @@ mod tests { .document_granularity(DocumentGranularity::ListElement), ), ), + ( + "FTS", + { + let mut body = serde_json::to_value(InvertedIndexParams::default()).unwrap(); + body["base_tokenizer"] = "code".into(); + body["stem"] = false.into(); + body["remove_stop_words"] = false.into(); + body["split_identifiers"] = true.into(); + body["split_on_numerics"] = false.into(); + body["preserve_original"] = true.into(); + body["index_operators"] = true.into(); + body + }, + Index::FTS( + InvertedIndexParams::default() + .base_tokenizer("code".to_string()) + .split_identifiers(true) + .split_on_numerics(false) + .preserve_original(true) + .index_operators(true), + ), + ), ]; for (index_type, expected_body, index) in cases { @@ -8267,6 +8753,7 @@ mod tests { // The server said only that it failed, so nothing may be invented. assert!(failure.message.is_none(), "{failure:?}"); assert!(failure.phase.is_none(), "{failure:?}"); + assert!(failure.traceback.is_none(), "{failure:?}"); assert!(failure.retryable.is_none(), "{failure:?}"); assert_eq!(err.to_string(), "Job job-err failed"); } @@ -8291,7 +8778,7 @@ mod tests { "/v1/jobs/describe" => http::Response::builder() .status(200) .body( - r#"{"job_id": "job-err", "job_state": "FAILED", "failure": {"phase": "commit", "message": "preempted", "retryable": true}}"# + r#"{"job_id": "job-err", "job_state": "FAILED", "failure": {"phase": "commit", "message": "preempted", "traceback": "Traceback (most recent call last):\nValueError: preempted", "retryable": true}}"# .to_string(), ) .unwrap(), @@ -8309,6 +8796,10 @@ mod tests { panic!("expected JobFailed, got {err:?}"); }; assert_eq!(failure.message.as_deref(), Some("preempted")); + assert_eq!( + failure.traceback.as_deref(), + Some("Traceback (most recent call last):\nValueError: preempted") + ); assert_eq!(failure.phase.as_deref(), Some("commit")); assert_eq!(failure.retryable, Some(true)); assert_eq!(err.to_string(), "Job job-err failed: preempted (in commit)"); @@ -9367,11 +9858,13 @@ mod tests { version: 1, timestamp: "2024-01-01T00:00:00Z".parse().unwrap(), metadata: Default::default(), + manifest_size: Some(1024), }; let version2 = lance::dataset::Version { version: 2, timestamp: "2024-02-01T00:00:00Z".parse().unwrap(), metadata: Default::default(), + manifest_size: None, }; let response_body = serde_json::json!({ "versions": [ @@ -9390,6 +9883,7 @@ mod tests { let versions = table.list_versions().await.unwrap(); assert_eq!(versions.len(), 2); assert_eq!(versions[0].version, 1); + assert_eq!(versions[0].manifest_size, Some(1024)); assert_eq!( versions[0].timestamp, "2024-01-01T00:00:00Z".parse::>().unwrap() @@ -9399,7 +9893,7 @@ mod tests { versions[1].timestamp, "2024-02-01T00:00:00Z".parse::>().unwrap() ); - // assert_eq!(versions, expected); + assert_eq!(versions[1].manifest_size, None); } /// Namespace-backed servers report `timestamp_millis` instead of @@ -9441,6 +9935,7 @@ mod tests { "2024-01-01T00:00:00Z".parse::>().unwrap() ); assert!(versions[0].metadata.is_empty()); + assert_eq!(versions[0].manifest_size, None); assert_eq!(versions[1].version, 2); assert_eq!( versions[1].timestamp, @@ -10102,6 +10597,167 @@ mod tests { assert_eq!(result.version, 10); } + #[rstest] + #[case(false, false)] + #[case(true, false)] + #[case(true, true)] + #[tokio::test] + async fn test_add_flattened_function_bindings_with_server_owned_assignment( + #[case] has_assignment: bool, + #[case] has_assignment_field: bool, + ) { + use crate::function::{FunctionApplication, FunctionBinding}; + use crate::table::computed_columns::{ + FUNCTION_BINDINGS_META_KEY, function_bindings_metadata, + }; + + let mut raw_binding: serde_json::Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + for output in raw_binding["outputs"].as_array_mut().unwrap() { + output["nullable"] = json!(true); + } + let assignment_name = "__function_assignment_fb_01K3TEXT"; + if has_assignment { + raw_binding["assignment"] = json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw_binding["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + } + let function = raw_binding["function"].clone(); + let binding: FunctionBinding = serde_json::from_value(raw_binding).unwrap(); + let mut schema = fixture_bound_schema(); + schema.metadata.insert( + FUNCTION_BINDINGS_META_KEY.into(), + function_bindings_metadata(&[binding]).unwrap(), + ); + let visible_schema = Arc::new(schema.clone()); + if has_assignment_field { + let mut fields = schema.fields().to_vec(); + // Even the assignment field's physical type and metadata are server-owned. + fields.push(Arc::new(Field::new( + assignment_name, + DataType::Int32, + false, + ))); + schema = Schema::new_with_metadata(fields, schema.metadata().clone()); + } + let description = describe_response(&schema); + let seeded = RemoteTable::new_mock( + "my_table".into(), + move |_| { + http::Response::builder() + .status(200) + .body(description.clone()) + .unwrap() + }, + None, + ); + seeded.seed_schema(&describe_response(&schema)); + assert_eq!(seeded.schema().await.unwrap(), visible_schema); + seeded.invalidate_schema_cache(); + assert_eq!( + seeded + .schema_read_snapshot(seeded.snapshot_read_state().await) + .await + .unwrap(), + visible_schema, + ); + assert_eq!( + seeded + .query_snapshot() + .await + .unwrap() + .schema() + .await + .unwrap(), + visible_schema, + ); + assert_eq!( + seeded + .checkout_current() + .await + .unwrap() + .schema() + .await + .unwrap(), + visible_schema, + ); + + let initial_schema = Schema::new(schema.fields()[..2].to_vec()); + let writes = Arc::new(AtomicUsize::new(0)); + let handler_writes = writes.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let body = match request.url().path() { + "/v1/table/my_table/describe/" => { + if handler_writes.load(Ordering::SeqCst) == 0 { + describe_response(&initial_schema) + } else { + describe_response(&schema) + } + } + "/v1/table/my_table/add_columns/" => { + let actual: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let index = handler_writes.fetch_add(1, Ordering::SeqCst); + let prefix = if index == 0 { "search" } else { "secondary" }; + assert_eq!( + actual["new_columns"], + json!([ + {"name": format!("{prefix}_text"), "all_null": true}, + {"name": format!("{prefix}_token_count"), "all_null": true} + ]) + ); + json!({"version": index + 2}).to_string() + } + path => panic!("Unexpected path: {path}"), + }; + http::Response::builder().status(200).body(body).unwrap() + }); + + for prefix in ["search", "secondary"] { + let application = FunctionApplication::from_json( + &json!({ + "function": function, + "inputs": [ + {"parameter": "title", "kind": "column", "value": {"path": "title"}}, + {"parameter": "body", "kind": "column", "value": {"path": "body"}} + ], + "output": {"kind": "named_struct", "fields": [ + {"name": "normalized_text", "arrow_type": "utf8", "nullable": true}, + {"name": "token_count", "arrow_type": "int64", "nullable": true} + ]}, + "columns": { + "normalized_text": format!("{prefix}_text"), + "token_count": format!("{prefix}_token_count") + } + }) + .to_string(), + ) + .unwrap(); + table + .add_columns() + .function(application) + .execute() + .await + .unwrap(); + if prefix == "search" { + assert_eq!(table.schema().await.unwrap(), visible_schema); + } + } + assert_eq!(writes.load(Ordering::SeqCst), 2); + } + #[tokio::test] async fn test_add_fixed_size_list_function_column_declares_the_vector_type() { let table = Table::new_with_handler("my_table", |request| { @@ -10234,7 +10890,7 @@ mod tests { assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); let body = request.body().unwrap().as_bytes().unwrap(); let value: serde_json::Value = serde_json::from_slice(body).unwrap(); - assert_eq!(value["column"], "doubled"); + assert_eq!(value, serde_json::json!({"column": "doubled"})); http::Response::builder() .status(202) .body(r#"{"job_id": "j-42"}"#) @@ -10252,6 +10908,322 @@ mod tests { ); } + #[rstest] + #[case(false)] + #[case(true)] + #[tokio::test] + async fn materialized_view_registry_job_waits_then_reports_the_committed_version( + #[case] with_progress: bool, + ) { + let polls = AtomicUsize::new(0); + let client = client_with_handler(move |request| -> http::Response { + match request.url().path() { + "/v1/jobs/describe" => http::Response::builder() + .status(200) + .body( + json!({ + "job_id": "job-1", + "job_type": "sql", + "job_state": if polls.fetch_add(1, Ordering::SeqCst) == 0 { + "IN_PROGRESS" + } else { + "DONE" + }, + "creation_ms": 1, + }) + .to_string(), + ) + .unwrap(), + "/v1/table/ns$view/describe/" => http::Response::builder() + .status(200) + .body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string()) + .unwrap(), + path => panic!("unexpected request: {path}"), + } + }); + let freshness = Arc::new(Mutex::new(FreshnessState::default())); + let job = Job::new_typed(Box::new(MaterializedViewRefreshJob { + inner: RemoteJob::new(client.clone(), "job-1".to_string()), + client, + db_name: "analytics".to_string(), + name: "view".to_string(), + namespace: vec!["ns".to_string()], + identifier: "ns$view".to_string(), + server_version: Default::default(), + sql_client: None, + freshness: freshness.clone(), + freshness_request: FreshnessHeaders::default(), + })); + + assert_eq!(job.id(), Some("job-1")); + let observations = Arc::new(Mutex::new(Vec::new())); + let observed = observations.clone(); + let result: RefreshMaterializedViewResult = if with_progress { + job.wait_with_progress(move |description| { + observed + .lock() + .unwrap() + .push(description.progress_snapshot()); + }) + .await + .unwrap() + } else { + job.wait().await.unwrap() + }; + if with_progress { + let observations = observations.lock().unwrap(); + assert_eq!(observations.len(), 2); + assert_eq!(observations[0]["state"], "running"); + assert_eq!(observations[1]["state"], "finished"); + } + assert_eq!(result.version, 42); + assert_eq!(result.mode, None); + assert_eq!(result.rows_written, None); + assert_eq!(result.source_version, None); + assert_eq!(freshness.lock().unwrap().min_read_version, Some(42)); + } + + #[rstest] + #[case(None)] + #[case(Some(1))] + #[case(Some(8))] + #[tokio::test] + async fn test_refresh_column_async_batch_size(#[case] batch_size: Option) { + use crate::table::{Ref, RefreshColumnOptions}; + + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/branches/create/" => http::Response::builder() + .status(200) + .body("{}".to_string()) + .unwrap(), + "/v1/table/my_table/describe/" => simple_describe_response(), + "/v1/table/my_table/backfill_column" => { + let mut expected = serde_json::json!({"column": "quality", "branch": "exp"}); + if let Some(batch_size) = batch_size { + expected["batch_size"] = serde_json::json!(batch_size); + } + assert_eq!(request_body_json(&request), expected); + http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-42"}"#.to_string()) + .unwrap() + } + path => panic!("unexpected request: {path}"), + }); + let branch = table + .create_branch("exp", Ref::Version(None, None)) + .await + .unwrap(); + let options = RefreshColumnOptions { + batch_size, + ..Default::default() + }; + let job = branch + .refresh_column_async_with_options("quality", options) + .await + .unwrap(); + assert_eq!(job.id(), Some("j-42")); + } + + #[tokio::test] + async fn test_refresh_column_async_gpu_placement_options() { + use crate::table::RefreshColumnOptions; + + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "POST"); + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column": "quality", + "gpu_class": "a10g", + "gpu_count": 2, + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-gpu"}"#) + .unwrap() + }); + let options = RefreshColumnOptions::default() + .gpu_class("a10g") + .gpu_count(2); + let job = table + .refresh_column_async_with_options("quality", options) + .await + .unwrap(); + assert_eq!(job.id(), Some("j-gpu")); + } + + #[tokio::test] + async fn test_refresh_column_async_retry_policy() { + use crate::function::{FunctionErrorPolicy, FunctionRetryPolicy}; + use crate::table::RefreshColumnOptions; + let policy = FunctionRetryPolicy::transient(); + let expected_policy = serde_json::to_value(&policy).unwrap(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column":"quality", "retry_policy": expected_policy, "error_policy":"skip", + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"j-retry"}"#.to_string()) + .unwrap() + }); + let options = RefreshColumnOptions::default() + .retry_policy(policy) + .error_policy(FunctionErrorPolicy::Skip); + assert_eq!( + table + .refresh_column_async_with_options("quality", options) + .await + .unwrap() + .id(), + Some("j-retry") + ); + } + + #[tokio::test] + async fn test_refresh_column_async_filter_and_failure_options() { + use crate::function::FunctionErrorPolicy; + use crate::table::RefreshColumnOptions; + + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column": "quality", + "where": "id % 2 = 0", + "error_policy": "skip", + "max_failed_fraction": 0.01, + "max_failed_rows": 50, + "row_timeout_seconds": 30.0, + "init_timeout_seconds": 120.0, + "num_workers": 4, + "max_executor_processes_per_worker": 2, + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-filtered"}"#) + .unwrap() + }); + let options = RefreshColumnOptions::default() + .where_clause("id % 2 = 0") + .error_policy(FunctionErrorPolicy::Skip) + .max_failed_fraction(0.01) + .max_failed_rows(50) + .row_timeout_seconds(30.0) + .init_timeout_seconds(120.0) + .num_workers(4) + .max_executor_processes_per_worker(2); + let job = table + .refresh_column_async_with_options("quality", options) + .await + .unwrap(); + assert_eq!(job.id(), Some("j-filtered")); + } + + #[tokio::test] + async fn test_refresh_column_rejects_invalid_filter_and_limit_options_before_request() { + use crate::table::RefreshColumnOptions; + + let table = Table::new_with_handler("my_table", |_| -> http::Response { + panic!("invalid refresh options must not send a request") + }); + for (options, expected) in [ + (RefreshColumnOptions::default().where_clause(" "), "where"), + ( + RefreshColumnOptions::default().max_failed_fraction(1.5), + "max_failed_fraction", + ), + ( + RefreshColumnOptions::default().max_failed_fraction(f64::NAN), + "max_failed_fraction", + ), + ( + RefreshColumnOptions::default().row_timeout_seconds(0.0), + "row_timeout_seconds", + ), + ( + RefreshColumnOptions::default().init_timeout_seconds(f64::INFINITY), + "init_timeout_seconds", + ), + ( + RefreshColumnOptions::default().num_workers(0), + "num_workers", + ), + ( + RefreshColumnOptions::default().max_executor_processes_per_worker(0), + "max_executor_processes_per_worker", + ), + ] { + let error = table + .refresh_column_async_with_options("quality", options) + .await + .unwrap_err(); + assert!( + matches!(&error, Error::InvalidInput { message } if message.contains(expected)), + "{error:?}" + ); + } + } + + #[tokio::test] + async fn test_refresh_column_rejects_invalid_gpu_options_before_request() { + use crate::table::RefreshColumnOptions; + + let table = Table::new_with_handler("my_table", |_| -> http::Response { + panic!("invalid GPU options must not send a request") + }); + for (options, expected) in [ + ( + RefreshColumnOptions::default().gpu_class("A10G"), + "gpu_class", + ), + ( + RefreshColumnOptions::default().gpu_class("-a10g"), + "gpu_class", + ), + (RefreshColumnOptions::default().gpu_count(0), "gpu_count"), + ] { + let error = table + .refresh_column_async_with_options("quality", options) + .await + .unwrap_err(); + assert!( + matches!(&error, Error::InvalidInput { message } if message.contains(expected)), + "{error:?}" + ); + } + } + + #[tokio::test] + async fn test_refresh_column_rejects_zero_batch_size_before_request() { + use crate::table::RefreshColumnOptions; + + let table = Table::new_with_handler("my_table", |_| -> http::Response { + panic!("invalid batch size must not send a request") + }); + let options = RefreshColumnOptions::default().batch_size(0); + let error = table + .refresh_column_with_options("quality", options.clone()) + .await + .unwrap_err(); + assert!(matches!(error, Error::InvalidInput { message } if message.contains("batch_size"))); + let error = table + .refresh_column_async_with_options("quality", options) + .await + .unwrap_err(); + assert!(matches!(error, Error::InvalidInput { message } if message.contains("batch_size"))); + } + #[rstest] #[case(false, "Function is unavailable")] #[case(true, "Function name was not found")] @@ -10339,9 +11311,11 @@ mod tests { .status(200) .body( r#"{"records": [{"job_id": "j-7", "fragment_id": 3, "row_offset": 9, + "row_id": 42, "row_address": 12884901897, "column": "embedding", "function": "embed", "function_version": "2", "table_version": 11, "error_type": "ValueError", - "error_message": "bad input 'x'", "created_at_millis": 1700000000000}], + "error_message": "bad input 'x'", "traceback": "Traceback (most recent call last):\nValueError: bad input 'x'", + "created_at_millis": 1700000000000, "attempts": 3}], "fragments": [{"job_id": "j-7", "fragment_id": 4, "rows_skipped": 500, "rows_recorded": 100}], "truncated": true}"#, @@ -10361,15 +11335,21 @@ mod tests { assert_eq!( errors.records, [FunctionErrorRecord { + attempts: Some(3), job_id: "j-7".into(), fragment_id: 3, row_offset: Some(9), + row_id: Some(42), + row_address: Some(12_884_901_897), column: "embedding".into(), function: "embed".into(), function_version: "2".into(), table_version: 11, error_type: "ValueError".into(), error_message: "bad input 'x'".into(), + traceback: Some( + "Traceback (most recent call last):\nValueError: bad input 'x'".into() + ), created_at_millis: 1_700_000_000_000, }] ); @@ -10384,6 +11364,25 @@ mod tests { ); assert!(errors.truncated); + // Servers before row_address or row_id omit them; the record still + // decodes. + let legacy: FunctionErrorRecord = serde_json::from_value(serde_json::json!({ + "job_id": "j-6", + "fragment_id": 2, + "row_offset": null, + "column": "embedding", + "function": "embed", + "function_version": "1", + "table_version": 10, + "error_type": "ValueError", + "error_message": "fragment reached the record cap", + "created_at_millis": 1_700_000_000_000_i64, + })) + .unwrap(); + assert!(legacy.row_id.is_none()); + assert!(legacy.row_address.is_none()); + assert!(legacy.traceback.is_none()); + // No filter sends no filter, and an empty listing reads as such. let table = Table::new_with_handler("my_table", |request| { let body = request.body().unwrap().as_bytes().unwrap(); @@ -10467,6 +11466,172 @@ mod tests { assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 1); } + /// A newly submitted refresh returns a freshness-wrapped handle. Waiting + /// through it must forward progress observations and still establish the + /// published-version read fence after success. + #[tokio::test] + async fn test_new_refresh_handle_forwards_progress_and_keeps_read_freshness() { + let polls = Arc::new(AtomicUsize::new(0)); + let polls_in_handler = polls.clone(); + let saw_version = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let saw_version_in_handler = saw_version.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/backfill_column" => http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-progress"}"#.to_string()) + .unwrap(), + "/v1/jobs/describe" => { + let response = if polls_in_handler.fetch_add(1, Ordering::SeqCst) == 0 { + json!({ + "job_id": "j-progress", + "job_type": "refresh_column", + "job_state": "IN_PROGRESS", + "progress": {"rows_planned": 12, "rows_computed": 4}, + "phase": "running", + }) + } else { + serde_json::from_str(&refresh_done("j-progress")).unwrap() + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + } + "/v1/table/my_table/count_rows/" => { + saw_version_in_handler.store( + request + .headers() + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()) + == Some("8"), + Ordering::SeqCst, + ); + http::Response::builder() + .status(200) + .body("1".to_string()) + .unwrap() + } + path => panic!("unexpected path {path}"), + }); + + let job = table.refresh_column_async("doubled").await.unwrap(); + let observed = Arc::new(std::sync::Mutex::new(Vec::new())); + let observed_in_callback = observed.clone(); + let result = job + .wait_with_progress(move |description| { + observed_in_callback + .lock() + .unwrap() + .push(description.progress_snapshot()); + }) + .await + .unwrap(); + assert_eq!(result.rows_assigned, 12); + + { + let observed = observed.lock().unwrap(); + assert_eq!(observed.len(), 2); + assert_eq!(observed[0]["state"], "running"); + assert_eq!(observed[0]["rows_planned"], 12); + assert_eq!(observed[0]["rows_computed"], 4); + assert_eq!(observed[1]["state"], "finished"); + } + + table.count_rows(None).await.unwrap(); + assert!( + saw_version.load(Ordering::SeqCst), + "new refresh handle lost its published-version freshness fence" + ); + } + + /// Index submissions use the same freshness wrapper. Its wait must forward + /// observations and retain the successful-wait timestamp bookkeeping. + #[tokio::test] + async fn test_new_index_handle_forwards_progress_and_keeps_read_freshness() { + let polls = Arc::new(AtomicUsize::new(0)); + let polls_in_handler = polls.clone(); + let saw_timestamp = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let saw_timestamp_in_handler = saw_timestamp.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); + http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap() + } + "/v1/table/my_table/create_index/" => http::Response::builder() + .status(200) + .body(r#"{"job_id": "j-index-progress"}"#.to_string()) + .unwrap(), + "/v1/jobs/describe" => { + let response = if polls_in_handler.fetch_add(1, Ordering::SeqCst) == 0 { + json!({ + "job_id": "j-index-progress", + "job_type": "create_index", + "job_state": "IN_PROGRESS", + "progress": {"rows_planned": 10, "rows_computed": 3}, + "phase": "building", + }) + } else { + json!({ + "job_id": "j-index-progress", + "job_type": "create_index", + "job_state": "DONE", + }) + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + } + "/v1/table/my_table/count_rows/" => { + saw_timestamp_in_handler.store( + request.headers().contains_key("x-lancedb-min-timestamp"), + Ordering::SeqCst, + ); + http::Response::builder() + .status(200) + .body("1".to_string()) + .unwrap() + } + path => panic!("unexpected path {path}"), + }); + + let job = table + .create_index(&["a"], Index::BTree(Default::default())) + .execute_async() + .await + .unwrap(); + let observed = Arc::new(std::sync::Mutex::new(Vec::new())); + let observed_in_callback = observed.clone(); + job.wait_with_progress(move |description| { + observed_in_callback + .lock() + .unwrap() + .push(description.progress_snapshot()); + }) + .await + .unwrap(); + + { + let observed = observed.lock().unwrap(); + assert_eq!(observed.len(), 2); + assert_eq!(observed[0]["state"], "running"); + assert_eq!(observed[0]["rows_planned"], 10); + assert_eq!(observed[0]["rows_computed"], 3); + assert_eq!(observed[1]["state"], "finished"); + } + + table.count_rows(None).await.unwrap(); + assert!( + saw_timestamp.load(Ordering::SeqCst), + "new index handle lost its successful-wait timestamp bookkeeping" + ); + } + #[tokio::test] async fn test_refresh_submission_uses_add_columns_version_fence() { let table = Table::new_with_handler("my_table", |request| match request.url().path() { @@ -11084,6 +12249,116 @@ mod tests { ); } + #[tokio::test] + async fn test_get_table_overrides() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "GET"); + assert_eq!(request.url().path(), "/admin/table/overrides"); + assert_eq!(request.url().query(), Some("db=default&table=my_table")); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_types": { + "cleanup": { "enabled": false } + } + }) + .to_string(), + ) + .unwrap() + }); + + let overrides = table.get_table_overrides().await.unwrap(); + assert_eq!(overrides["job_types"]["cleanup"]["enabled"], false); + } + + #[tokio::test] + async fn test_update_table_overrides_merges_existing_fields() { + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = calls.clone(); + let table = Table::new_with_handler("my_table", move |request| { + match seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) { + 0 => { + assert_eq!(request.method(), "GET"); + assert_eq!(request.url().path(), "/admin/table/overrides"); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_types": { + "compaction": { "enabled": true }, + "reindex_vector": { + "table": { "num_workers": 3 } + } + }, + "unknown": { "keep": true } + }) + .to_string(), + ) + .unwrap() + } + 1 => { + assert_eq!(request.method(), "PUT"); + assert_eq!(request.url().path(), "/admin/table/overrides"); + let body = request_body_json(&request); + assert_eq!(body["db"], "default"); + assert_eq!(body["table"], "my_table"); + assert_eq!(body["namespace"], serde_json::json!([])); + assert_eq!( + body["overrides"], + serde_json::json!({ + "job_types": { + "compaction": { "enabled": true }, + "cleanup": { "enabled": false }, + "reindex_vector": { + "table": { "num_workers": 3 } + } + }, + "unknown": { "keep": true } + }) + ); + http::Response::builder() + .status(200) + .body(body["overrides"].to_string()) + .unwrap() + } + _ => panic!("unexpected request"), + } + }); + + let updated = table + .update_table_overrides(serde_json::json!({ + "job_types": { + "cleanup": { "enabled": false } + } + })) + .await + .unwrap(); + assert_eq!(updated["job_types"]["cleanup"]["enabled"], false); + assert_eq!(updated["job_types"]["compaction"]["enabled"], true); + assert_eq!( + updated["job_types"]["reindex_vector"]["table"]["num_workers"], + 3 + ); + assert_eq!(updated["unknown"]["keep"], true); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_reset_table_overrides() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "POST"); + assert_eq!(request.url().path(), "/admin/table/overrides/reset"); + assert_eq!(request.url().query(), Some("db=default&table=my_table")); + http::Response::builder().status(200).body("{}").unwrap() + }); + + assert_eq!( + table.reset_table_overrides().await.unwrap(), + serde_json::json!({}) + ); + } + #[tokio::test] async fn test_get_rte_spec_absent() { let table = Table::new_with_handler("my_table", |request| { @@ -14633,6 +15908,115 @@ mod tests { assert!(error.to_string().contains("SQL is unavailable")); } + #[tokio::test] + async fn test_optimize_requires_sql() { + let table = Table::new_with_handler("my_table", |request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()) + }); + let error = table + .optimize(OptimizeAction::Compact { + options: crate::table::optimize::CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap_err(); + assert!(error.to_string().contains("SQL is unavailable")); + } + + #[tokio::test] + async fn test_optimize_rejects_custom_remap_options() { + let table = Table::new_with_handler("my_table", move |_| -> http::Response { + panic!("a custom remap strategy must be rejected before any request is sent") + }); + + let error = table + .optimize(OptimizeAction::Compact { + options: crate::table::optimize::CompactionOptions::default(), + remap_options: Some(Arc::new(lance::dataset::optimize::IgnoreRemap::default())), + }) + .await + .unwrap_err(); + + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("remap")); + } + + #[tokio::test] + async fn test_optimize_rejects_unsupported_compaction_options() { + let table = Table::new_with_handler("my_table", move |_| -> http::Response { + panic!("custom compaction options must be rejected before any request is sent") + }); + + let error = table + .optimize(OptimizeAction::Compact { + options: crate::table::optimize::CompactionOptions { + target_rows_per_fragment: 17, + max_source_bytes: Some(1024), + ..Default::default() + }, + remap_options: None, + }) + .await + .unwrap_err(); + + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("CompactionOptions")); + } + + #[tokio::test] + async fn test_optimize_rejects_all_prune_and_index() { + for action in [ + OptimizeAction::All, + OptimizeAction::Prune { + older_than: None, + delete_unverified: None, + error_if_tagged_old_versions: None, + }, + OptimizeAction::Index(Default::default()), + ] { + let table = Table::new_with_handler("my_table", move |_| -> http::Response { + panic!( + "an unsupported remote optimize action must be rejected before any request is sent" + ) + }); + + let error = table.optimize(action).await.unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + } + } + + #[tokio::test] + async fn test_optimize_on_a_branch_requires_sql() { + use lance::dataset::refs::Ref; + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/branches/create/" => http::Response::builder() + .status(200) + .body(b"{}".to_vec()) + .unwrap(), + path => panic!("unexpected request on a branch-scoped optimize call: {path}"), + }); + + let branch = table + .create_branch("dev", Ref::Version(None, None)) + .await + .unwrap(); + + // No SQL client is wired to this REST-only mock, so the branch-scoped + // handle hits the same "SQL is unavailable" check `optimize` runs for + // main -- it does not reject the branch itself, and it does not send + // a REST request (see `test_optimize_requires_sql`). + let error = branch + .optimize(OptimizeAction::Compact { + options: crate::table::optimize::CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap_err(); + + assert!(error.to_string().contains("SQL is unavailable")); + } + #[tokio::test] async fn test_create_branch_empty_name_rejected_client_side() { use lance::dataset::refs::Ref; @@ -14780,6 +16164,73 @@ mod tests { assert!(matches!(err, Error::TableNotFound { .. }), "got {err:?}"); } + #[tokio::test] + async fn test_delete_branch_conflict_is_not_retried() { + let requests = Arc::new(AtomicUsize::new(0)); + let captured = requests.clone(); + let reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files"; + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/branches/delete/"); + captured.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(409) + .body(json!({ "code": 14, "error": reason }).to_string()) + .unwrap() + }); + + let err = table.delete_branch("exp").await.unwrap_err(); + assert_eq!(requests.load(Ordering::SeqCst), 1); + assert!(err.to_string().contains(reason), "got {err:?}"); + assert!( + matches!( + err, + Error::Http { + status_code: Some(StatusCode::CONFLICT), + .. + } + ), + "expected the original conflict, got {err:?}" + ); + } + + #[tokio::test] + async fn test_delete_branch_partial_failure_is_not_retried() { + let requests = Arc::new(AtomicUsize::new(0)); + let captured = requests.clone(); + let table = Table::new_with_handler("my_table", move |_| { + // The ref was removed before the first response failed. Replaying + // the deletion would hide that failure behind a missing-branch error. + if captured.fetch_add(1, Ordering::SeqCst) == 0 { + http::Response::builder() + .status(500) + .body("failed after removing branch ref") + .unwrap() + } else { + http::Response::builder() + .status(404) + .body("no such branch") + .unwrap() + } + }); + + let err = table.delete_branch("exp").await.unwrap_err(); + assert_eq!(requests.load(Ordering::SeqCst), 1); + assert!( + err.to_string().contains("failed after removing branch ref"), + "got {err:?}" + ); + assert!( + matches!( + err, + Error::Http { + status_code: Some(StatusCode::INTERNAL_SERVER_ERROR), + .. + } + ), + "expected the original server error, got {err:?}" + ); + } + fn sample_branch_diff_json() -> &'static str { r#"{ "fromBranch":"exp", diff --git a/rust/lancedb/src/remote/table/ipc_stream.rs b/rust/lancedb/src/remote/table/ipc_stream.rs new file mode 100644 index 000000000..af31a9b28 --- /dev/null +++ b/rust/lancedb/src/remote/table/ipc_stream.rs @@ -0,0 +1,729 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Incremental decoding of response bodies that use Arrow IPC stream framing. + +use arrow_array::RecordBatch; +use arrow_buffer::Buffer; +use arrow_ipc::reader::StreamDecoder; +use bytes::Bytes; +use datafusion_common::DataFusionError; +use datafusion_physical_plan::SendableRecordBatchStream; +use datafusion_physical_plan::stream::RecordBatchStreamAdapter; +use futures::stream::BoxStream; +use futures::{Stream, StreamExt, TryStreamExt}; + +use crate::error::{BoxError, Error, Result}; + +/// Decode an Arrow IPC stream from a response body as its chunks arrive. +/// +/// Only the current chunk and the decoder's state are held, so memory is bounded +/// by the size of a batch rather than the size of the result. This waits for the +/// first batch, or for the end of an empty result, so a body that fails before +/// any data arrives fails the request itself. +/// +/// A complete body ends with the end-of-stream marker; the server aborts the body +/// without it when the query fails after sending headers. A body that ends early, +/// even between messages, is reported as [`Error::ResponseInterrupted`] and never +/// as a short result. +pub(super) async fn read_ipc_stream( + chunks: impl Stream> + Send + 'static, + request_id: String, + table_version: Option, +) -> Result +where + E: Into + 'static, +{ + let mut body = IpcStreamBody { + chunks: chunks.map_err(Into::into).boxed(), + chunk: Buffer::default(), + decoder: StreamDecoder::new(), + finished: false, + request_id, + table_version, + batches: 0, + rows: 0, + }; + let first = body.next_batch().await?; + // The schema is the first message, so only a body holding nothing but the + // end-of-stream marker can complete without one. + let schema = body.decoder.schema().ok_or_else(|| Error::Http { + source: "Arrow IPC stream ended without a schema".into(), + request_id: body.request_id.clone(), + status_code: None, + })?; + let rest = futures::stream::try_unfold(body, |mut body| async move { + Ok(body.next_batch().await?.map(|batch| (batch, body))) + }); + let batches = futures::stream::iter(first.map(Ok)) + .chain(rest) + .map_err(|error: Error| DataFusionError::External(Box::new(error))); + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, batches))) +} + +struct IpcStreamBody { + chunks: BoxStream<'static, std::result::Result>, + /// The part of the current chunk that has not been decoded yet. + chunk: Buffer, + decoder: StreamDecoder, + /// Set once the body has ended with the end-of-stream marker. + finished: bool, + request_id: String, + table_version: Option, + batches: u64, + rows: u64, +} + +impl IpcStreamBody { + /// Decode until the next batch is complete. Returns `None` once the body + /// has ended with the end-of-stream marker. + async fn next_batch(&mut self) -> Result> { + while !self.finished { + if self.chunk.is_empty() { + match self.chunks.next().await { + Some(Ok(chunk)) => self.chunk = chunk.into(), + Some(Err(error)) => return Err(self.interrupted(error)), + None if read_end_of_stream(&mut self.decoder) => self.finished = true, + None => { + return Err(self.interrupted( + "the response ended before the Arrow end-of-stream marker".into(), + )); + } + } + continue; + } + // Decoding stops after each batch, keeping the rest of the chunk. + if let Some(batch) = self.decoder.decode(&mut self.chunk)? { + self.batches += 1; + self.rows += batch.num_rows() as u64; + return Ok(Some(batch)); + } + } + Ok(None) + } + + fn interrupted(&self, source: BoxError) -> Error { + Error::ResponseInterrupted { + request_id: self.request_id.clone(), + batches: self.batches, + rows: self.rows, + table_version: self.table_version, + source: source.into(), + } + } +} + +/// Whether the decoder has read the end-of-stream marker. +/// +/// [`StreamDecoder::finish`] also accepts input that stops between messages, +/// because the Arrow format lets a writer end a stream by closing it. A decoder +/// that has read the marker rejects any further input, which is the only way +/// its API tells the two apart. +fn read_end_of_stream(decoder: &mut StreamDecoder) -> bool { + decoder.finish().is_ok() && decoder.decode(&mut Buffer::from_slice_ref([0u8])).is_err() +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + use arrow_array::builder::StringDictionaryBuilder; + use arrow_array::types::Int8Type; + use arrow_array::{ArrayRef, Int32Array, StringArray}; + use arrow_ipc::CompressionType; + use arrow_ipc::writer::{DictionaryHandling, FileWriter, IpcWriteOptions, StreamWriter}; + use arrow_schema::{DataType, Field, Schema, SchemaRef}; + use lance::arrow::json::JsonSchema; + use rstest::rstest; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + use tokio::sync::mpsc; + + use super::*; + use crate::query::{ExecutableQuery, QueryExecutionOptions}; + use crate::remote::client::{ClientConfig, RetryConfig}; + use crate::remote::{ARROW_FILE_CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE}; + use crate::{Table, connect}; + + /// Three batches of two rows under a schema with metadata. The second batch's + /// dictionary extends the first one's, which writers can send as a delta, and + /// the third replaces it. + fn batches() -> Vec { + let schema = Arc::new(Schema::new_with_metadata( + vec![ + Field::new("id", DataType::Int32, false), + Field::new_dictionary("label", DataType::Int8, DataType::Utf8, false), + ], + HashMap::from([("origin".to_string(), "test".to_string())]), + )); + let labels: [(&[&str], [&str; 2]); 3] = [ + (&["a", "b"], ["a", "b"]), + (&["a", "b", "c"], ["c", "a"]), + (&["d"], ["d", "d"]), + ]; + labels + .into_iter() + .enumerate() + .map(|(i, (dictionary, values))| { + let dictionary = StringArray::from(dictionary.to_vec()); + let mut label = + StringDictionaryBuilder::::new_with_dictionary(2, &dictionary) + .unwrap(); + values + .into_iter() + .for_each(|value| label.append_value(value)); + let id = Int32Array::from(vec![2 * i as i32, 2 * i as i32 + 1]); + RecordBatch::try_new( + schema.clone(), + vec![Arc::new(id) as ArrayRef, Arc::new(label.finish())], + ) + .unwrap() + }) + .collect() + } + + /// An IPC stream cut where the server cuts it: after the schema, after each + /// batch with its dictionaries, and after the end-of-stream marker. + fn messages( + schema: &Schema, + batches: &[RecordBatch], + options: IpcWriteOptions, + ) -> Vec> { + let mut writer = StreamWriter::try_new_with_options(Vec::new(), schema, options).unwrap(); + let mut messages = vec![std::mem::take(writer.get_mut())]; + for batch in batches { + writer.write(batch).unwrap(); + messages.push(std::mem::take(writer.get_mut())); + } + writer.finish().unwrap(); + messages.push(std::mem::take(writer.get_mut())); + messages + } + + fn chunks(body: &[u8], size: usize) -> Vec> { + body.chunks(size) + .map(|chunk| Ok(Bytes::copy_from_slice(chunk))) + .collect() + } + + /// The schema, the batches yielded, and the error that ended the stream. + async fn read( + chunks: Vec>, + ) -> (Option, Vec, Option) { + let stream = + match read_ipc_stream(futures::stream::iter(chunks), "request".into(), Some(7)).await { + Ok(stream) => stream, + Err(error) => return (None, vec![], Some(error)), + }; + let schema = stream.schema(); + let results = stream.collect::>().await; + let (batches, errors): (Vec<_>, Vec<_>) = results.into_iter().partition(|r| r.is_ok()); + assert!(errors.len() <= 1, "the stream ends at its first error"); + let error = errors + .into_iter() + .next() + .map(|e| Error::from(e.unwrap_err())); + let batches = batches.into_iter().map(|r| r.unwrap()).collect(); + (Some(schema), batches, error) + } + + fn assert_interrupted(error: Option, expected_batches: u64, expected_rows: u64) { + match error { + Some(Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + .. + }) => { + assert_eq!(request_id, "request"); + assert_eq!((batches, rows), (expected_batches, expected_rows)); + assert_eq!(table_version, Some(7)); + } + other => panic!("expected an interrupted response, got {other:?}"), + } + } + + // One-byte chunks split every message; a single chunk holds them all. + #[rstest] + #[case(1)] + #[case(7)] + #[case(usize::MAX)] + #[tokio::test] + async fn decodes_any_chunking(#[case] chunk_size: usize) { + let input = batches(); + let body = messages(&input[0].schema(), &input, IpcWriteOptions::default()).concat(); + + let (schema, output, error) = read(chunks(&body, chunk_size)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(schema.unwrap(), input[0].schema()); + assert_eq!(output, input); + } + + #[rstest] + #[case(IpcWriteOptions::default().with_dictionary_handling(DictionaryHandling::Delta))] + #[case(IpcWriteOptions::default().try_with_compression(Some(CompressionType::LZ4_FRAME)).unwrap())] + #[case(IpcWriteOptions::default().try_with_compression(Some(CompressionType::ZSTD)).unwrap())] + #[tokio::test] + async fn decodes_dictionary_deltas_and_compressed_batches(#[case] options: IpcWriteOptions) { + let input = batches(); + let body = messages(&input[0].schema(), &input, options).concat(); + + let (_, output, error) = read(chunks(&body, 5)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, input); + } + + /// The server answers an empty result with the schema and the end-of-stream marker. + #[tokio::test] + async fn empty_result_keeps_its_schema() { + let schema = batches()[0].schema(); + let body = messages(&schema, &[], IpcWriteOptions::default()).concat(); + + let (decoded, output, error) = read(chunks(&body, 3)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(decoded.unwrap(), schema); + assert!(output.is_empty()); + } + + #[tokio::test] + async fn body_ending_without_end_of_stream_is_interrupted() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + let complete = messages[..messages.len() - 1].concat(); + let after_first_batch = messages[..2].concat().len(); + // Where the body stops, and how many batches it holds by then. + for (end, delivered) in [ + (complete.len(), 3), // between messages, after the last batch + (complete.len() - 3, 2), // inside the last batch + (after_first_batch, 1), // between messages + (messages[0].len(), 0), // after the schema + (messages[0].len() / 2, 0), // inside the schema + (0, 0), // an empty body + ] { + let (_, output, error) = read(chunks(&complete[..end], 4)).await; + assert_eq!(output, input[..delivered], "body cut at {end}"); + assert_interrupted(error, delivered as u64, 2 * delivered as u64); + } + } + + #[tokio::test] + async fn body_error_is_interrupted() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + let mut body = chunks(&messages[..2].concat(), usize::MAX); + body.push(Err(std::io::Error::other("connection reset"))); + + let (_, output, error) = read(body).await; + + assert_eq!(output, input[..1]); + let message = error.as_ref().map(ToString::to_string).unwrap_or_default(); + assert!(message.contains("connection reset"), "{message}"); + assert_interrupted(error, 1, 2); + } + + #[tokio::test] + async fn malformed_body_is_an_arrow_error() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + // A message whose metadata is not a flatbuffer. + let garbage = [&[0xff; 4][..], &8u32.to_le_bytes(), &[0xab; 8]].concat(); + // Anything after the end-of-stream marker. + let trailing = [messages.concat(), vec![0]].concat(); + for body in [[messages[0].clone(), garbage].concat(), trailing] { + let (_, _, error) = read(chunks(&body, usize::MAX)).await; + assert!(matches!(error, Some(Error::Arrow { .. })), "{error:?}"); + } + } + + /// What the test server does next for a query request. + enum Reply { + /// A complete response with this status and an empty body. + Status(u16), + /// Headers of a chunked body with this content type. + Head(Option<&'static str>), + Chunk(Vec), + /// The last chunk, ending the body cleanly. + End, + /// Close the connection in the middle of the body. + Abort, + } + + struct Server { + table: Table, + replies: mpsc::UnboundedSender, + /// Headers of each query request received. + queries: Arc>>>, + } + + impl Server { + fn reply(&self, replies: impl IntoIterator) { + replies + .into_iter() + .for_each(|reply| self.replies.send(reply).unwrap()); + } + } + + /// Serve table `t` over HTTP. Query requests are answered, in order, by the + /// replies the test sends. + async fn serve() -> Server { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (replies, mut pending) = mpsc::unbounded_channel(); + let queries = Arc::new(Mutex::new(Vec::new())); + let received = queries.clone(); + tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let (path, headers) = read_request(&mut socket).await; + if path.ends_with("/describe/") { + let schema = Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "vector", + DataType::new_fixed_size_list(DataType::Float32, 2, true), + false, + ), + ]); + let body = serde_json::json!({ + "version": 7, + "schema": JsonSchema::try_from(&schema).unwrap(), + }) + .to_string(); + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + socket.write_all(response.as_bytes()).await.unwrap(); + continue; + } + received.lock().unwrap().push(headers); + while let Some(reply) = pending.recv().await { + let last = !matches!(reply, Reply::Head(_) | Reply::Chunk(_)); + let bytes = match reply { + Reply::Status(status) => format!( + "HTTP/1.1 {status} Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + .into_bytes(), + Reply::Head(content_type) => format!( + "HTTP/1.1 200 OK\r\n{}Transfer-Encoding: chunked\r\n\ + x-lancedb-version: 7\r\nConnection: close\r\n\r\n", + content_type + .map(|value| format!("Content-Type: {value}\r\n")) + .unwrap_or_default() + ) + .into_bytes(), + Reply::Chunk(chunk) => { + [format!("{:x}\r\n", chunk.len()).into_bytes(), chunk, b"\r\n".into()] + .concat() + } + Reply::End => b"0\r\n\r\n".to_vec(), + Reply::Abort => break, + }; + // The client may have stopped reading. + if socket.write_all(&bytes).await.is_err() || last { + break; + } + } + } + }); + let db = connect("db://test") + .api_key("key") + .region("us-east-1") + .host_override(&format!("http://{address}")) + .client_config(ClientConfig { + retry_config: RetryConfig { + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }) + .execute() + .await + .unwrap(); + let table = db.open_table("t").execute().await.unwrap(); + Server { + table, + replies, + queries, + } + } + + async fn read_request(socket: &mut TcpStream) -> (String, HashMap) { + let mut request = Vec::new(); + let mut buf = [0; 4096]; + let head_end = loop { + let n = socket.read(&mut buf).await.unwrap(); + assert!(n > 0, "connection closed before the request head"); + request.extend_from_slice(&buf[..n]); + if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") { + break end + 4; + } + }; + let head = String::from_utf8(request[..head_end].to_vec()).unwrap(); + let mut lines = head.lines(); + let path = lines.next().unwrap().split(' ').nth(1).unwrap().to_string(); + let headers: HashMap<_, _> = lines + .filter_map(|line| line.split_once(':')) + .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_string())) + .collect(); + let length: usize = headers + .get("content-length") + .map_or(0, |length| length.parse().unwrap()); + while request.len() < head_end + length { + let n = socket.read(&mut buf).await.unwrap(); + assert!(n > 0, "connection closed before the request body"); + request.extend_from_slice(&buf[..n]); + } + (path, headers) + } + + /// The query batches as the server sends them: `id` only. + fn id_messages() -> Vec> { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batches: Vec<_> = (0..3) + .map(|i| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![i]))]) + .unwrap() + }) + .collect(); + messages(&schema, &batches, IpcWriteOptions::default()) + } + + fn ids(batch: &RecordBatch) -> Vec { + batch["id"] + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + } + + #[tokio::test] + async fn first_batch_arrives_before_the_rest_of_the_body() { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + ]); + + // The server sends the rest only after the first batch has been read. + let (results, first) = tokio::time::timeout(Duration::from_secs(10), async { + let mut results = server.table.query().execute().await.unwrap(); + let first = results.next().await.unwrap().unwrap(); + (results, first) + }) + .await + .expect("the first batch must not wait for the whole body"); + assert_eq!(ids(&first), [0]); + server.reply([Reply::Chunk(messages[2..].concat()), Reply::End]); + let rest = results.try_collect::>().await.unwrap(); + assert_eq!(rest.iter().flat_map(ids).collect::>(), [1, 2]); + + let queries = server.queries.lock().unwrap(); + assert_eq!(queries.len(), 1); + assert_eq!(queries[0]["accept"], super::super::QUERY_ACCEPT); + } + + /// A server abort, and a proxy that turns it into a clean end of the body, + /// both fail the query after the batches already read. Neither is retried. + #[rstest] + #[case::abort(Reply::Abort, true)] + #[case::clean_end(Reply::End, false)] + #[tokio::test] + async fn interrupted_body_is_typed_and_not_retried( + #[case] end: Reply, + #[case] transport_error: bool, + ) { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + end, + ]); + + let mut results = server.table.query().execute().await.unwrap(); + assert_eq!(ids(&results.next().await.unwrap().unwrap()), [0]); + let error = results.next().await.unwrap().unwrap_err(); + assert!(results.next().await.is_none()); + + let Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = error + else { + panic!("expected an interrupted response, got {error:?}"); + }; + assert!(!request_id.is_empty()); + assert_eq!((batches, rows, table_version), (1, 1, Some(7))); + assert_eq!(source.is::(), transport_error, "{source}"); + assert_eq!(server.queries.lock().unwrap().len(), 1); + } + + /// Vector queries run through a DataFusion plan, which must keep the error's type. + #[tokio::test] + async fn vector_query_keeps_the_interruption_type() { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + Reply::Abort, + ]); + + let results = server + .table + .query() + .nearest_to(&[0.0f32, 0.0]) + .unwrap() + .execute() + .await + .unwrap(); + let error = results.try_collect::>().await.unwrap_err(); + + assert!( + matches!(error, Error::ResponseInterrupted { batches: 1, .. }), + "{error:?}" + ); + } + + /// A server without multi-vector support gets a request per vector, and the + /// plan merging the responses shares an error between its partitions. + #[tokio::test] + async fn multi_vector_query_keeps_the_interruption() { + let server = serve().await; + let messages = id_messages(); + // Which vector gets which response does not matter. + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages.concat()), + Reply::End, + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + Reply::Abort, + ]); + + let results = server + .table + .query() + .nearest_to(&[0.0f32, 0.0]) + .unwrap() + .add_query_vector(&[1.0f32, 1.0]) + .unwrap() + .execute() + .await + .unwrap(); + let error = results.try_collect::>().await.unwrap_err(); + + let Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = error + else { + panic!("expected an interrupted response, got {error:?}"); + }; + assert!(!request_id.is_empty()); + assert_eq!((batches, rows, table_version), (1, 1, Some(7))); + assert!(source.is::(), "{source}"); + assert_eq!(server.queries.lock().unwrap().len(), 2); + } + + #[tokio::test] + async fn timeout_covers_reading_the_body() { + let server = serve().await; + let messages = id_messages(); + // The body stalls after the first batch. + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + ]); + + let options = QueryExecutionOptions { + timeout: Some(Duration::from_millis(500)), + ..Default::default() + }; + let mut results = server + .table + .query() + .execute_with_options(options) + .await + .unwrap(); + assert_eq!(ids(&results.next().await.unwrap().unwrap()), [0]); + let error = tokio::time::timeout(Duration::from_secs(10), results.next()) + .await + .expect("the timeout must end a stalled body") + .unwrap() + .unwrap_err(); + + assert!( + !matches!(error, Error::ResponseInterrupted { .. }), + "{error:?}" + ); + assert!( + error.to_string().contains("Query timeout after 500 ms"), + "{error}" + ); + assert_eq!( + server.queries.lock().unwrap()[0]["x-request-timeout-ms"], + "500" + ); + } + + /// Servers that do not stream query results answer with file framing, or + /// with no content type at all. + #[rstest] + #[case(Some(ARROW_FILE_CONTENT_TYPE))] + #[case(None)] + #[tokio::test] + async fn file_framing_is_still_read(#[case] content_type: Option<&'static str>) { + let server = serve().await; + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![4, 5]))]) + .unwrap(); + let mut writer = FileWriter::try_new(Vec::new(), &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + server.reply([ + Reply::Head(content_type), + Reply::Chunk(writer.into_inner().unwrap()), + Reply::End, + ]); + + let results = server.table.query().execute().await.unwrap(); + let output = results.try_collect::>().await.unwrap(); + + assert_eq!(output, [batch]); + } + + #[tokio::test] + async fn failure_before_headers_is_retried() { + let server = serve().await; + server.reply([ + Reply::Status(503), + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(id_messages().concat()), + Reply::End, + ]); + + let results = server.table.query().execute().await.unwrap(); + let output = results.try_collect::>().await.unwrap(); + + assert_eq!(output.iter().flat_map(ids).collect::>(), [0, 1, 2]); + assert_eq!(server.queries.lock().unwrap().len(), 2); + } +} diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs new file mode 100644 index 000000000..2a42dd3ab --- /dev/null +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Compaction options supported by the remote SQL submission protocol. +use crate::error::{Error, Result}; + +pub(super) fn compaction_sql_options( + options: &crate::table::optimize::CompactionOverrides, +) -> Result> { + for (name, value) in [ + ("target_rows_per_fragment", options.target_rows_per_fragment), + ("max_source_rows", options.max_source_rows), + ("batch_size", options.batch_size), + ] { + if value == Some(0) { + return Err(Error::InvalidInput { + message: format!("{name} must be greater than 0"), + }); + } + } + let mut result = Vec::new(); + for (name, value) in [ + ( + "target_rows_per_fragment", + options.target_rows_per_fragment.map(|v| v as u64), + ), + ("max_source_rows", options.max_source_rows.map(|v| v as u64)), + ("io_buffer_size", options.io_buffer_size), + ("batch_size", options.batch_size.map(|v| v as u64)), + ] { + if let Some(value) = value { + result.push(format!("{name} = {value}")); + } + } + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::table::{CompactionOptions, CompactionOverrides}; + + #[test] + fn omissions_and_explicit_default_target_are_distinct() { + assert!( + compaction_sql_options(&CompactionOverrides::default()) + .unwrap() + .is_empty() + ); + let target = CompactionOptions::default().target_rows_per_fragment; + assert_eq!( + compaction_sql_options(&CompactionOverrides { + target_rows_per_fragment: Some(target), + io_buffer_size: Some(0), + ..Default::default() + }) + .unwrap(), + [ + format!("target_rows_per_fragment = {target}"), + "io_buffer_size = 0".into() + ] + ); + } + + #[test] + fn unsupported_settings_are_rejected() { + assert!(matches!( + CompactionOverrides::try_from(CompactionOptions { + max_source_bytes: Some(1024), + ..Default::default() + }), + Err(Error::NotSupported { .. }) + )); + } + + #[test] + fn invalid_row_settings_are_rejected() { + for options in [ + CompactionOverrides { + target_rows_per_fragment: Some(0), + ..Default::default() + }, + CompactionOverrides { + max_source_rows: Some(0), + ..Default::default() + }, + CompactionOverrides { + batch_size: Some(0), + ..Default::default() + }, + ] { + assert!(matches!( + compaction_sql_options(&options), + Err(Error::InvalidInput { .. }) + )); + } + } +} diff --git a/rust/lancedb/src/remote/token_cache.rs b/rust/lancedb/src/remote/token_cache.rs index 6f34ab73c..cb6c6bca0 100644 --- a/rust/lancedb/src/remote/token_cache.rs +++ b/rust/lancedb/src/remote/token_cache.rs @@ -43,7 +43,7 @@ //! client_id: "my-app".to_string(), //! client_secret: None, //! scopes: vec!["openid".to_string()], -//! flow: OAuthFlow::DeviceCode, +//! flow: OAuthFlow::DeviceCode(Default::default()), //! client_auth_method: None, //! refresh_buffer_secs: None, //! resource: Some("https://api.example.com".to_string()), @@ -237,7 +237,7 @@ fn canonicalize_scopes(scopes: &[String]) -> Vec { fn flow_key(flow: &OAuthFlow) -> Option<&'static str> { match flow { OAuthFlow::AuthorizationCode(_) => Some("authorization_code"), - OAuthFlow::DeviceCode => Some("device_code"), + OAuthFlow::DeviceCode(_) => Some("device_code"), OAuthFlow::ClientCredentials | OAuthFlow::AzureManagedIdentity { .. } => None, } } @@ -845,7 +845,7 @@ pub struct SessionLogout { /// client_id: "my-app".to_string(), /// client_secret: None, /// scopes: vec!["openid".to_string()], -/// flow: OAuthFlow::DeviceCode, +/// flow: OAuthFlow::DeviceCode(Default::default()), /// client_auth_method: None, /// refresh_buffer_secs: None, /// resource: None, @@ -1012,7 +1012,7 @@ mod tests { client_secret: None, client_auth_method: None, scopes: vec!["openid".to_string()], - flow: OAuthFlow::DeviceCode, + flow: OAuthFlow::DeviceCode(Default::default()), refresh_buffer_secs: None, resource: None, audience: None, @@ -1546,6 +1546,18 @@ mod tests { assert_eq!(canonical.file_stem, key.file_stem); } + #[test] + fn test_device_pkce_preserves_cache_identity() { + let dir = cache_tempdir(); + let mut config = device_config(dir.path()); + let standard = CacheKey::new(&config).unwrap(); + config.flow = OAuthFlow::DeviceCode(crate::remote::DeviceCodeOptions::new().use_pkce(true)); + assert_eq!( + CacheKey::new(&config).unwrap().file_stem, + standard.file_stem + ); + } + #[test] fn test_cache_key_separates_identity_dimensions() { let base = device_config(Path::new("/tmp/cache")); diff --git a/rust/lancedb/src/rerankers/rrf.rs b/rust/lancedb/src/rerankers/rrf.rs index 4da1927be..7e58448d0 100644 --- a/rust/lancedb/src/rerankers/rrf.rs +++ b/rust/lancedb/src/rerankers/rrf.rs @@ -28,6 +28,7 @@ impl RRFReranker { /// Create a new RRFReranker /// /// The parameter k is a constant used in the RRF formula (default is 60). + /// Each result contributes `1 / (k + rank)`, with ranks starting at 1. /// Experiments indicate that k = 60 was near-optimal, but that the choice /// is not critical. See paper: /// https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf @@ -84,7 +85,7 @@ impl Reranker for RRFReranker { let mut rrf_score_map = BTreeMap::new(); let mut update_score_map = |(i, result_id)| { - let score = 1.0 / (i as f32 + self.k); + let score = 1.0 / ((i + 1) as f32 + self.k); rrf_score_map .entry(result_id) .and_modify(|e| *e += score) @@ -180,11 +181,12 @@ pub mod test { .unwrap(); // scores should be calculated as: - // - foo = 1/1 = 1.0 - // - bar = 1/2 + 1/1 = 1.5 - // - baz = 1/3 = 0.333 - // - bean = 1/4 + 1/2 = 0.75 - // - dog = 1/5 + 1/3 = 0.533 + // With k = 1 and ranks starting at 1: + // - foo = 1/2 + // - bar = 1/3 + 1/2 + // - baz = 1/4 + // - bean = 1/5 + 1/3 + // - dog = 1/6 + 1/4 // then we should get the result ranked in descending order let reranker = RRFReranker::new(1.0); @@ -205,19 +207,58 @@ pub mod test { let names: StringArray = downcast_array(result.column(0)); assert_eq!( names.iter().map(|e| e.unwrap()).collect::>(), - vec!["bar", "foo", "bean", "dog", "baz"] + vec!["bar", "bean", "foo", "dog", "baz"] ); let ids: UInt64Array = downcast_array(result.column(1)); assert_eq!( ids.iter().map(|e| e.unwrap()).collect::>(), - vec![4, 1, 5, 3, 2] + vec![4, 5, 1, 3, 2] ); let scores: Float32Array = downcast_array(result.column(2)); assert_eq!( scores.iter().map(|e| e.unwrap()).collect::>(), - vec![1.5, 1.0, 0.75, 1.0 / 5.0 + 1.0 / 3.0, 1.0 / 3.0] + vec![ + 1.0 / 3.0 + 1.0 / 2.0, + 1.0 / 5.0 + 1.0 / 3.0, + 1.0 / 2.0, + 1.0 / 6.0 + 1.0 / 4.0, + 1.0 / 4.0, + ] ); } + + #[tokio::test] + async fn test_rrf_default_rank_order() { + // Only rows 0 and 1 occur in both lists. Their ranks are (9, 6) + // and (2, 14), respectively. Zero-based ranks reverse their order + // even with the default k = 60. + let vector_ids = vec![2, 1, 3, 4, 5, 6, 7, 8, 0]; + let fts_ids = vec![9, 10, 11, 12, 13, 0, 14, 15, 16, 17, 18, 19, 20, 1]; + let schema = Arc::new(Schema::new(vec![Field::new( + ROW_ID, + DataType::UInt64, + false, + )])); + let vector_results = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(UInt64Array::from(vector_ids))], + ) + .unwrap(); + let fts_results = + RecordBatch::try_new(schema, vec![Arc::new(UInt64Array::from(fts_ids))]).unwrap(); + + let result = RRFReranker::default() + .rerank_hybrid("", vector_results, fts_results) + .await + .unwrap(); + let ids: UInt64Array = downcast_array(result.column_by_name(ROW_ID).unwrap()); + let scores: Float32Array = downcast_array(result.column_by_name(RELEVANCE_SCORE).unwrap()); + + assert_eq!(result.num_rows(), 21); + assert_eq!(&ids.values()[..2], &[0, 1]); + assert_eq!(scores.value(0), 1.0 / 69.0 + 1.0 / 66.0); + assert_eq!(scores.value(1), 1.0 / 62.0 + 1.0 / 74.0); + } } diff --git a/rust/lancedb/src/secrets.rs b/rust/lancedb/src/secrets.rs index c980e51ee..29a07ba95 100644 --- a/rust/lancedb/src/secrets.rs +++ b/rust/lancedb/src/secrets.rs @@ -19,7 +19,7 @@ use serde_json::Value; /// /// Returned by [`crate::connection::Connection::describe_secret`]. There is no /// field for the credential and no method that could produce one. -#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct SecretInfo { /// The Secret's database-scoped name. pub name: String, @@ -82,7 +82,7 @@ impl SecretReference { #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[non_exhaustive] pub enum SecretBinding { - /// Delivered as an environment variable, which the UDF's library already + /// Delivered as an environment variable, which the function's library already /// reads. The variable is the delivery target; the Secret is what fills it. Env { variable: String, diff --git a/rust/lancedb/src/sql.rs b/rust/lancedb/src/sql.rs index 713a79e86..5c01fe898 100644 --- a/rust/lancedb/src/sql.rs +++ b/rust/lancedb/src/sql.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! Handles to SQL queries running on a LanceDB Distributed database. +//! Handles to SQL queries running on a LanceDB Enterprise database. use std::{fmt, sync::Arc}; diff --git a/rust/lancedb/src/storage_integration.rs b/rust/lancedb/src/storage_integration.rs new file mode 100644 index 000000000..50bfc0aca --- /dev/null +++ b/rust/lancedb/src/storage_integration.rs @@ -0,0 +1,258 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Database-owned cloud-storage access configurations managed by the remote service. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// A Secret object, optionally qualified by its owning database and namespace. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SecretReference { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub database: Option, + #[serde(default)] + pub namespace_path: Vec, + pub name: String, +} +impl SecretReference { + /// Reference a Secret in the integration's database. + pub fn new(name: impl Into) -> Self { + Self { + database: None, + namespace_path: vec![], + name: name.into(), + } + } + /// Qualify the database that owns the Secret. + pub fn with_database(mut self, database: impl Into) -> Self { + self.database = Some(database.into()); + self + } + /// Qualify the namespace that owns the Secret. + pub fn with_namespace(mut self, namespace: Vec) -> Self { + self.namespace_path = namespace; + self + } +} + +/// Configuration for registering a cloud storage integration. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] +pub struct CreateStorageIntegrationRequest { + pub storage_provider: StorageProvider, + pub storage_prefix: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aws_role_arn: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aws_access_key_id_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aws_secret_access_key_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aws_region: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub azure_storage_account: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub azure_tenant_id_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub azure_client_id_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub azure_client_secret_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub gcp_credentials_json_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub huggingface_token_secret: Option, +} + +/// Cloud storage providers supported by storage integrations. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum StorageProvider { + #[serde(rename = "S3")] + S3, + #[serde(rename = "AZURE")] + Azure, + #[serde(rename = "GCP")] + Gcp, + #[serde(rename = "HUGGINGFACE")] + HuggingFace, +} + +impl CreateStorageIntegrationRequest { + /// Register a prefix and the customer-owned IAM role authorized to access it. + pub fn s3(storage_prefix: impl Into, aws_role_arn: impl Into) -> Self { + Self { + storage_provider: StorageProvider::S3, + storage_prefix: storage_prefix.into(), + aws_role_arn: Some(aws_role_arn.into()), + aws_access_key_id_secret: None, + aws_secret_access_key_secret: None, + aws_region: None, + azure_storage_account: None, + azure_tenant_id_secret: None, + azure_client_id_secret: None, + azure_client_secret_secret: None, + gcp_credentials_json_secret: None, + huggingface_token_secret: None, + } + } + + /// Register static S3 credentials by Secret reference, without accepting key values. + pub fn s3_with_secrets( + storage_prefix: impl Into, + access_key: SecretReference, + secret_key: SecretReference, + ) -> Self { + Self { + storage_provider: StorageProvider::S3, + storage_prefix: storage_prefix.into(), + aws_role_arn: None, + aws_access_key_id_secret: Some(access_key), + aws_secret_access_key_secret: Some(secret_key), + aws_region: None, + azure_storage_account: None, + azure_tenant_id_secret: None, + azure_client_id_secret: None, + azure_client_secret_secret: None, + gcp_credentials_json_secret: None, + huggingface_token_secret: None, + } + } + + /// Register Azure Blob access using three Secret references and an explicit account. + /// + /// ``` + /// use lancedb::storage_integration::{CreateStorageIntegrationRequest, SecretReference}; + /// let config = CreateStorageIntegrationRequest::azure( + /// "az://customer-data/raw/", "customeraccount", + /// SecretReference::new("tenant"), SecretReference::new("client"), + /// SecretReference::new("credential"), + /// ); + /// ``` + pub fn azure( + storage_prefix: impl Into, + storage_account: impl Into, + tenant_id: SecretReference, + client_id: SecretReference, + client_secret: SecretReference, + ) -> Self { + Self { + storage_provider: StorageProvider::Azure, + storage_prefix: storage_prefix.into(), + azure_storage_account: Some(storage_account.into()), + azure_tenant_id_secret: Some(tenant_id), + azure_client_id_secret: Some(client_id), + azure_client_secret_secret: Some(client_secret), + gcp_credentials_json_secret: None, + huggingface_token_secret: None, + aws_role_arn: None, + aws_access_key_id_secret: None, + aws_secret_access_key_secret: None, + aws_region: None, + } + } + + /// Register Google Cloud Storage access using a Secret containing credentials JSON. + /// + /// ``` + /// use lancedb::storage_integration::{CreateStorageIntegrationRequest, SecretReference}; + /// let config = CreateStorageIntegrationRequest::gcp( + /// "gs://customer-data/raw/", SecretReference::new("gcp_credentials"), + /// ); + /// ``` + pub fn gcp(storage_prefix: impl Into, credentials_json: SecretReference) -> Self { + Self { + storage_provider: StorageProvider::Gcp, + storage_prefix: storage_prefix.into(), + gcp_credentials_json_secret: Some(credentials_json), + huggingface_token_secret: None, + aws_role_arn: None, + aws_access_key_id_secret: None, + aws_secret_access_key_secret: None, + aws_region: None, + azure_storage_account: None, + azure_tenant_id_secret: None, + azure_client_id_secret: None, + azure_client_secret_secret: None, + } + } + + /// Register anonymous Hugging Face access at the default anonymous rate limits. + /// Use `with_huggingface_token_secret` to reference a Secret containing a token. + /// + /// ``` + /// use lancedb::storage_integration::{CreateStorageIntegrationRequest, SecretReference}; + /// let config = CreateStorageIntegrationRequest::huggingface( + /// "hf://datasets/acme/private/data/", + /// ).with_huggingface_token_secret(SecretReference::new("hf_token")); + /// ``` + pub fn huggingface(storage_prefix: impl Into) -> Self { + Self { + storage_provider: StorageProvider::HuggingFace, + storage_prefix: storage_prefix.into(), + huggingface_token_secret: None, + gcp_credentials_json_secret: None, + aws_role_arn: None, + aws_access_key_id_secret: None, + aws_secret_access_key_secret: None, + aws_region: None, + azure_storage_account: None, + azure_tenant_id_secret: None, + azure_client_id_secret: None, + azure_client_secret_secret: None, + } + } + + /// Use a Hugging Face token stored in a Secret instead of anonymous access. + pub fn with_huggingface_token_secret(mut self, token: SecretReference) -> Self { + self.huggingface_token_secret = Some(token); + self + } + + /// Set the AWS region of the storage prefix. + pub fn with_aws_region(mut self, region: impl Into) -> Self { + self.aws_region = Some(region.into()); + self + } +} + +/// Persisted configuration and cloud setup instructions. +/// +/// Registration does not verify AWS access or bind the integration to a storage +/// operation. The policies and external ID are configuration metadata, never +/// AWS access credentials. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] +pub struct StorageIntegrationInfo { + pub name: String, + pub database: String, + pub namespace_path: Vec, + pub storage_provider: StorageProvider, + pub storage_prefix: String, + #[serde(default)] + pub aws_role_arn: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aws_access_key_id_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aws_secret_access_key_secret: Option, + pub aws_region: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub azure_storage_account: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub azure_tenant_id_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub azure_client_id_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub azure_client_secret_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub gcp_credentials_json_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub huggingface_token_secret: Option, + pub aws_account_id: String, + pub aws_iam_principal_arn: String, + pub aws_external_id: String, + pub created_at_millis: i64, + pub access_verified: bool, + pub trust_policy: Value, + pub permissions_policy: Value, + pub configuration_instructions: String, +} diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index cf2442d50..c51199b50 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -19,6 +19,7 @@ pub use lance::dataset::ReadParams; pub use lance::dataset::Version; use lance::dataset::WriteMode; use lance::dataset::builder::DatasetBuilder; +use lance::dataset::cleanup::RemovalStats; pub use lance::dataset::mem_wal::MemIndexRegistry; /// The traits a memtable index plugin implements; see [`MemIndexRegistry`]. pub use lance::dataset::mem_wal::index as mem_index; @@ -42,6 +43,7 @@ use lance_table::io::commit::CommitHandler; use lance_table::io::commit::ManifestNamingScheme; use lance_table::io::commit::external_manifest::ExternalManifestCommitHandler; use serde::{Deserialize, Serialize}; +pub type TableOverrides = serde_json::Value; use std::collections::{HashMap, HashSet}; use std::format; use std::path::Path; @@ -54,6 +56,7 @@ use crate::blob::BlobRangeRequest; use crate::data::scannable::{PeekedScannable, Scannable, estimate_write_partitions}; use crate::database::Database; use crate::database::read_freshness::TableFreshness; +use crate::docs::DocLink; use crate::embeddings::{EmbeddingDefinition, EmbeddingRegistry, MemoryRegistry}; use crate::error::{Error, Result}; use crate::function::FunctionErrorsRequest; @@ -108,9 +111,10 @@ pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTa pub use lance::dataset::scanner::DatasetRecordBatchStream; pub use lance_index::optimize::OptimizeOptions; pub use optimize::{ - CompactionMode, CompactionOptions, IndexRemapMode, OptimizeAction, OptimizeStats, + CompactionMode, CompactionOptions, CompactionOverrides, IndexRemapMode, OptimizeAction, + OptimizeStats, }; -pub use refresh::RefreshColumnResult; +pub use refresh::{RefreshColumnOptions, RefreshColumnResult}; pub use rte_stats::{MemtableStats, RTEStats, SsTableStats, TableShardStats}; pub use schema_evolution::{ AddColumnsResult, AlterColumnsResult, DropColumnsResult, FieldMetadataUpdate, @@ -588,9 +592,29 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { _full: bool, ) -> Result> { Err(Error::NotSupported { - message: "remote materialized-view refresh is not supported on this table type".into(), + message: DocLink::MaterializedViews + .append_to("remote materialized-view refresh is not supported on this table type"), }) } + /// Submit an Enterprise refresh with aggregate resource caps and GPU placement. + #[doc(hidden)] + async fn refresh_materialized_view_async_with_options( + &self, + source_version: Option, + full: bool, + options: crate::materialized_view::RefreshMaterializedViewOptions, + ) -> Result> { + options.validate()?; + if !options.is_empty() { + return Err(Error::NotSupported { + message: + "this table cannot enforce materialized-view resource budgets or GPU placement" + .into(), + }); + } + self.refresh_materialized_view_async(source_version, full) + .await + } /// Create a read-only handle pinned to the table's current active revision. /// /// The returned handle is independent from later refreshes or checkouts on @@ -652,7 +676,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn prewarm_index(&self, name: &str) -> Result<()>; /// Prewarm data for the table. /// - /// Currently only supported in LanceDB Distributed. + /// Currently only supported in LanceDB Enterprise. /// If `columns` is `None`, all columns are prewarmed. async fn prewarm_data(&self, columns: Option>) -> Result<()>; /// Get statistics about the index. @@ -710,6 +734,34 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "get_rte_spec is not supported on this table type".into(), }) } + /// Read Enterprise table overrides. + /// + /// The default implementation returns `NotSupported`; Enterprise remote + /// tables override it. + async fn get_table_overrides(&self) -> Result { + Err(Error::NotSupported { + message: "get_table_overrides is supported only on remote Enterprise tables".into(), + }) + } + /// Merge Enterprise table overrides into the currently stored object. + /// + /// The default implementation returns `NotSupported`; Enterprise remote + /// tables override it. + async fn update_table_overrides(&self, _overrides: TableOverrides) -> Result { + Err(Error::NotSupported { + message: "update_table_overrides is supported only on remote Enterprise tables".into(), + }) + } + /// Clear Enterprise table overrides. + /// + /// The default implementation returns `NotSupported`; Enterprise remote + /// tables override it. + async fn reset_table_overrides(&self) -> Result { + Err(Error::NotSupported { + message: "reset_table_overrides is supported only on remote Enterprise tables".into(), + }) + } + /// Whether a hybrid query on this table has already been told it cannot /// join its legs on `_rowid`. /// @@ -735,6 +787,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// the only cost of being late to notice is a base-only read that is still /// correct. fn note_hybrid_pk_fusion(&self) {} + /// Freeze every table shard's active memtable into an SSTable. /// /// The default implementation returns `NotSupported`. @@ -809,6 +862,14 @@ 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; + /// Compact with optional fields, preserving remote policy inheritance. + async fn compact(&self, options: optimize::CompactionOverrides) -> Result { + self.optimize(OptimizeAction::Compact { + options: options.into_options(), + remap_options: None, + }) + .await + } /// Add columns to the table. async fn add_columns( &self, @@ -818,7 +879,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// Declare computed columns, each defined by a SQL expression. /// /// Where the declaration is planned depends on the backend: a LanceDB Embedded - /// table validates and types the expression itself, while a LanceDB Distributed + /// table validates and types the expression itself, while a LanceDB Enterprise /// table sends the expression for the server to plan. async fn add_computed_columns( &self, @@ -837,7 +898,8 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { _options: computed_columns::ComputedColumnOptions, ) -> Result { Err(Error::NotSupported { - message: "Function columns are supported only in LanceDB Distributed".into(), + message: DocLink::Functions + .append_to("Function columns are supported only in LanceDB Enterprise"), }) } /// Fill a computed column's unfilled rows and recompute those whose @@ -849,6 +911,21 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "this operation is only supported on LanceDB Embedded".into(), }) } + /// Refresh with options. A local refresh ignores the Function batch size + /// and GPU placement and rejects every other option. + async fn refresh_column_with_options( + &self, + column: &str, + options: RefreshColumnOptions, + ) -> Result { + options.validate()?; + if let Some(name) = options.enterprise_only_option() { + return Err(Error::NotSupported { + message: format!("{name} requires a LanceDB Enterprise refresh"), + }); + } + self.refresh_column(column).await + } /// Fill a computed column's unfilled rows and recompute those whose /// inputs changed, returning a [`Job`] tracking the operation. async fn refresh_column_async( @@ -859,6 +936,20 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "this operation is only supported on LanceDB Embedded".into(), }) } + /// Start a refresh job with options. + async fn refresh_column_async_with_options( + &self, + column: &str, + options: RefreshColumnOptions, + ) -> Result> { + options.validate()?; + if let Some(name) = options.enterprise_only_option() { + return Err(Error::NotSupported { + message: format!("{name} requires a LanceDB Enterprise refresh"), + }); + } + self.refresh_column_async(column).await + } /// The per-row errors Function refreshes recorded on this table; see /// [`Table::function_errors`]. The default returns `NotSupported`. async fn function_errors( @@ -866,7 +957,8 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { _request: &crate::function::FunctionErrorsRequest, ) -> Result { Err(Error::NotSupported { - message: "per-row Function errors are recorded only in LanceDB Distributed".into(), + message: DocLink::FunctionErrors + .append_to("per-row Function errors are recorded only in LanceDB Enterprise"), }) } /// Alter columns in the table. @@ -939,14 +1031,16 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// Diff a branch against main. Remote only. async fn diff_branch(&self, _from_branch: &str) -> Result { Err(Error::NotSupported { - message: "Branch diffs are only supported on Enterprise tables.".into(), + message: DocLink::BranchDiff + .append_to("Branch diffs are only supported on Enterprise tables."), }) } /// Cherry-pick a branch onto main, or dry-run. Remote only. /// HTTP 409 still returns [`Ok`] with [`CherryPickStatus::Failed`]. async fn cherry_pick(&self, _from_branch: &str, _dry_run: bool) -> Result { Err(Error::NotSupported { - message: "Cherry-picking branches is only supported on Enterprise tables.".into(), + message: DocLink::BranchCherryPick + .append_to("Cherry-picking branches is only supported on Enterprise tables."), }) } /// The branch this handle is scoped to, or `None` for `main`. @@ -993,7 +1087,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// [`FieldMetadataUpdate::remove`] deletes a key and /// [`FieldMetadataUpdate::replace`] swaps the field's whole map. /// - /// The default returns `NotSupported`; Lance-backed and LanceDB Distributed tables override it. + /// The default returns `NotSupported`; Lance-backed and LanceDB Enterprise tables override it. async fn update_field_metadata( &self, _updates: &[FieldMetadataUpdate], @@ -1284,7 +1378,7 @@ impl Table { /// /// Native tables support both legacy blob v1 and blob v2 columns. /// Output matches `row_ids` in length and order. Null blobs are null; - /// valid empty blobs contain empty byte strings. LanceDB Distributed limits individual + /// valid empty blobs contain empty byte strings. LanceDB Enterprise limits individual /// requests to 1024 row ids and 64 MiB of blob bytes; the client /// splits requests and reads a single larger blob through the Range route. /// This method still materializes all bytes in memory, so prefer @@ -1336,7 +1430,7 @@ impl Table { /// ranges for the same blob. The output has the same length and order as /// the requests. Null blobs produce null output slots; empty ranges on /// non-null blobs produce empty byte strings. - /// LanceDB Distributed tables read through version-pinned [`BlobFile`] handles using + /// LanceDB Enterprise tables read through version-pinned [`BlobFile`] handles using /// HTTP byte-range requests. /// /// `_rowid` values stay valid after compaction when the table has stable @@ -1595,7 +1689,7 @@ impl Table { } /// See [Table::create_index] - /// In LanceDB Distributed, this allows an optional wait_timeout to poll until asynchronous indexing is complete + /// In LanceDB Enterprise, this allows an optional wait_timeout to poll until asynchronous indexing is complete pub fn create_index_with_timeout( &self, columns: &[impl AsRef], @@ -1823,9 +1917,20 @@ impl Table { /// There is an ongoing effort to make row ids stable which is tracked at /// https://github.com/lancedb/lancedb/issues/1120 /// - /// No guarantees are made regarding the order in which results are returned. If you - /// desire an output order that matches the order of the given ids, you will need - /// to add the row id column to the output and align it yourself. + /// Results follow the requested row-id order, including repeated IDs. Missing or + /// deleted IDs are omitted. An explicit nonempty [`QueryBase::order_by`] overrides + /// the requested order. Limits and offsets apply after restoring occurrences. + /// These guarantees also apply to remote tables. + /// + /// ```rust + /// use lancedb::query::ExecutableQuery; + /// # async fn example(table: &lancedb::Table, first: u64, second: u64) -> lancedb::Result<()> { + /// // If both IDs exist, return second, first, then second again. + /// let rows = table.take_row_ids(vec![second, first, second]).execute().await?; + /// # Ok(()) + /// # } + /// ``` + /// /// Parameters /// ---------- /// row_ids: list[int] @@ -1860,10 +1965,65 @@ impl Table { /// optimize should be run frequently. A good rule of thumb is to run optimize if /// you have added or modified 100,000 or more records or run more than 20 data /// modification operations. + /// + /// # LanceDB Enterprise (remote tables) + /// + /// [`OptimizeAction::Compact`] supports per-job `target_rows_per_fragment`, + /// `max_source_rows`, `io_buffer_size`, and `batch_size`, with no custom + /// `remap_options`. Other non-default options, `All`, `Prune`, and `Index` return + /// [`crate::Error::NotSupported`]. See [`OptimizeAction::Compact`] for + /// what a remote call submits and what it does and does not wait for. pub async fn optimize(&self, action: OptimizeAction) -> Result { self.inner.optimize(action).await } + /// Compact data files with optional tuning fields. On remote tables, + /// omitted fields inherit table tuning, then deployment/built-in defaults. + /// Returns after job submission; remote statistics are placeholders. + /// + /// ``` + /// use lancedb::{Table, table::optimize::CompactionOverrides}; + /// # async fn compact(table: &Table) -> lancedb::Result<()> { + /// table.compact(CompactionOverrides { + /// io_buffer_size: Some(64 * 1024 * 1024), + /// ..Default::default() + /// }).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn compact(&self, options: optimize::CompactionOverrides) -> Result { + self.inner.compact(options).await + } + + /// Language-binding entry point retaining optional compaction fields. + #[doc(hidden)] + pub async fn optimize_full_with_overrides( + &self, + options: optimize::CompactionOverrides, + older_than: Option, + before_timestamp: Option>, + delete_unverified: Option, + ) -> Result { + if self.as_native().is_some() { + return self + .optimize_full( + options.into_options(), + older_than, + before_timestamp, + delete_unverified, + ) + .await; + } + if older_than.is_some() || before_timestamp.is_some() || delete_unverified == Some(true) { + return Err(Error::NotSupported { message: "pruning is not supported in LanceDB Enterprise; omit pruning options to run compaction only".into() }); + } + let stats = self.compact(options).await?; + Ok(OptimizeStats { + compaction: stats.compaction, + prune: Some(RemovalStats::default()), + }) + } + /// Prune versions committed before an absolute timestamp. /// /// This is an internal entry point for language bindings whose public API @@ -1876,7 +2036,7 @@ impl Table { error_if_tagged_old_versions: Option, ) -> Result { let native = self.as_native().ok_or_else(|| Error::NotSupported { - message: "optimize is not supported in LanceDB Distributed.".into(), + message: "optimize is not supported in LanceDB Enterprise.".into(), })?; let prune = optimize::cleanup_old_versions_before( native, @@ -1891,6 +2051,77 @@ impl Table { }) } + /// Run the maintenance cycle used by language bindings' `optimize()` + /// convenience method: compact, then -- on a local table -- prune and + /// optimize indices. + /// + /// This is an internal entry point for language bindings. On a remote + /// table (LanceDB Enterprise) only [`OptimizeAction::Compact`] with its + /// supported per-job options is supported. A caller asking for anything pruning-related + /// (`older_than`, `before_timestamp`, or `delete_unverified: Some(true)`) + /// gets `NotSupported` before anything is submitted, the same way + /// unsupported `CompactionOptions` are rejected -- rather than a + /// success that silently reports zero bytes pruned when nothing was + /// pruned at all. A plain call with none of those set only compacts: + /// `Prune` and `Index` are skipped here rather than attempted and + /// failed, since by this point the compaction job has already been + /// durably submitted and a caller retrying on that failure would + /// resubmit it. The returned prune stats are zeroed in that case. See + /// [`OptimizeAction::Compact`] for what the submission does and does not + /// wait for. + #[doc(hidden)] + pub async fn optimize_full( + &self, + compaction_options: CompactionOptions, + older_than: Option, + before_timestamp: Option>, + delete_unverified: Option, + ) -> Result { + let is_remote = self.as_native().is_none(); + if is_remote + && (older_than.is_some() + || before_timestamp.is_some() + || delete_unverified == Some(true)) + { + return Err(Error::NotSupported { + message: "pruning (older_than, before_timestamp, or \ + delete_unverified) is not supported in LanceDB \ + Enterprise; omit those options to run compaction \ + only." + .into(), + }); + } + let compaction = self + .optimize(OptimizeAction::Compact { + options: compaction_options, + remap_options: None, + }) + .await? + .compaction; + if is_remote { + return Ok(OptimizeStats { + compaction, + prune: Some(RemovalStats::default()), + }); + } + let prune = if let Some(before_timestamp) = before_timestamp { + self.optimize_prune_before(before_timestamp, delete_unverified, None) + .await? + .prune + } else { + self.optimize(OptimizeAction::Prune { + older_than, + delete_unverified, + error_if_tagged_old_versions: None, + }) + .await? + .prune + }; + self.optimize(OptimizeAction::Index(OptimizeOptions::default())) + .await?; + Ok(OptimizeStats { compaction, prune }) + } + /// Add new columns to the table, providing values to fill in. pub fn add_columns(&self) -> AddColumnsBuilder { AddColumnsBuilder::new(self.inner.clone()) @@ -1906,7 +2137,7 @@ impl Table { /// [`freshness`](crate::table::freshness)); everything else is left as /// it is. /// - /// LanceDB Embedded only: in LanceDB Distributed a refresh runs as a server job, through + /// LanceDB Embedded only: in LanceDB Enterprise a refresh runs as a server job, through /// [`Table::refresh_column_async`]. /// /// ``` @@ -1921,6 +2152,36 @@ impl Table { self.inner.refresh_column(column.as_ref()).await } + /// Like [`Table::refresh_column`], with explicit refresh options. + /// + /// [`RefreshColumnOptions::batch_size()`] caps rows per Function call in + /// LanceDB Enterprise and must be greater than zero when set. + /// [`RefreshColumnOptions::gpu_class()`] selects a GPU pool and + /// [`RefreshColumnOptions::gpu_count()`] sets the aggregate GPU budget. + /// These options have no effect on expression-backed columns in LanceDB + /// Embedded. Remote refreshes require + /// [`Table::refresh_column_async_with_options`]. + /// + /// ``` + /// # use lancedb::{Table, table::RefreshColumnOptions}; + /// # async fn refresh(table: &Table) -> Result<(), Box> { + /// let result = table.refresh_column_with_options( + /// "doubled", RefreshColumnOptions::default(), + /// ).await?; + /// println!("filled {} rows", result.rows_filled); + /// # Ok(()) + /// # } + /// ``` + pub async fn refresh_column_with_options( + &self, + column: impl AsRef, + options: RefreshColumnOptions, + ) -> Result { + self.inner + .refresh_column_with_options(column.as_ref(), options) + .await + } + /// Like [`Table::refresh_column`], but returns a [`Job`] tracking the /// operation instead of blocking until it completes. /// @@ -1930,7 +2191,7 @@ impl Table { /// both expression-backed and Function-backed columns. Invalid input /// -- an unknown column, or one that is not computed -- is reported by /// this call rather than by the job. In LanceDB Embedded the job runs as an - /// in-process task; in LanceDB Distributed it is the server's + /// in-process task; in LanceDB Enterprise it is the server's /// backfill job. /// /// ``` @@ -1950,13 +2211,53 @@ impl Table { self.inner.refresh_column_async(column.as_ref()).await } + /// Like [`Table::refresh_column_async`], with explicit refresh options. + /// + /// Set [`RefreshColumnOptions::batch_size()`] to cap the rows each remote + /// Function call receives, for example to keep slow Functions within the + /// executor's per-call deadline. Set + /// [`RefreshColumnOptions::gpu_class()`] and + /// [`RefreshColumnOptions::gpu_count()`] to override the registered GPU + /// class or set an aggregate GPU budget for Function workers. Unset values + /// use the Function and server defaults; zero counts and malformed class + /// names are rejected before submitting a job. Embedded expression + /// refreshes ignore all three options. + /// + /// ``` + /// # use lancedb::{Table, table::RefreshColumnOptions}; + /// # async fn refresh(table: &Table) -> Result<(), Box> { + /// let job = table.refresh_column_async_with_options( + /// "quality", + /// RefreshColumnOptions::default() + /// .batch_size(8) + /// .gpu_class("a10g") + /// .gpu_count(2), + /// ).await?; + /// let result = job.wait().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn refresh_column_async_with_options( + &self, + column: impl AsRef, + options: RefreshColumnOptions, + ) -> Result> { + self.inner + .refresh_column_async_with_options(column.as_ref(), options) + .await + } + /// The per-row errors Function refreshes recorded on this table: the /// rows a refresh skipped under its skip policy, with the failing input /// and the error, plus a summary for any fragment whose detail was /// capped. Filter by job or column through the request; a listing that /// hit its limit reports [`FunctionErrors::truncated`]. /// - /// LanceDB Distributed only, and the caller needs read access + /// 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. + /// + /// LanceDB Enterprise only, and the caller needs read access /// to the table, since a message carries the value that failed. /// /// ``` @@ -1985,6 +2286,10 @@ impl Table { /// Each alteration must specify at least one of `rename`, `data_type`, or /// `nullable`. Returns [`Error::InvalidInput`] before applying any changes /// if an alteration does not specify any of these fields. + /// + /// Local tables reject renaming source or vector columns referenced by + /// [`EmbeddingDefinition`] or `embedding_functions` schema metadata to + /// preserve the embedding binding. pub async fn alter_columns( &self, alterations: &[ColumnAlteration], @@ -2028,6 +2333,10 @@ impl Table { } /// Remove columns from the table. + /// + /// Local tables reject dropping source or vector columns referenced by + /// [`EmbeddingDefinition`] or `embedding_functions` schema metadata to + /// preserve the embedding binding. pub async fn drop_columns(&self, columns: &[&str]) -> Result { self.inner.drop_columns(columns).await } @@ -2125,6 +2434,33 @@ impl Table { self.inner.get_rte_spec().await } + /// Read Enterprise table overrides for this table. + /// + /// Table overrides configure Enterprise-managed background behavior such as + /// automatic compaction, cleanup, and reindex execution. Local tables return + /// `NotSupported` because they do not have an Enterprise background planner + /// consuming these overrides. + pub async fn get_table_overrides(&self) -> Result { + self.inner.get_table_overrides().await + } + + /// 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. + pub async fn update_table_overrides( + &self, + overrides: TableOverrides, + ) -> Result { + self.inner.update_table_overrides(overrides).await + } + + /// Clear Enterprise table overrides for this table. + pub async fn reset_table_overrides(&self) -> Result { + self.inner.reset_table_overrides().await + } + /// Converge this table's RTE write path into its base table. /// /// One `flush` to freeze every memtable into an SSTable, then compaction triggers @@ -2311,7 +2647,7 @@ impl Table { /// Tokenize a full-text search query using the tokenizer configured on an FTS index. /// /// Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in - /// the client process from index metadata. In LanceDB Distributed, this means the + /// the client process from index metadata. In LanceDB Enterprise, this means the /// same tokenizer model files must also exist locally, and must match the /// files the server uses: the client cannot detect a mismatch, so it may /// return tokens the server's index never produces. If the model files are @@ -2349,7 +2685,7 @@ impl Table { /// /// The column must have exactly one FTS index. Model-backed tokenizers such /// as `jieba/*` and `lindera/*` are rebuilt in the client process from - /// index metadata. In LanceDB Distributed, this means the same tokenizer model + /// index metadata. In LanceDB Enterprise, this means the same tokenizer model /// files must also exist locally, and must match the files the server uses /// (see [`Self::tokenize`]). pub async fn tokenize_with_column(&self, query: &str, column: &str) -> Result> { @@ -2438,7 +2774,7 @@ impl Table { /// Get the table URI (storage location) /// /// Returns the full storage location of the table (e.g., S3/GCS path). - /// In LanceDB Distributed, this fetches the location from the server via describe. + /// In LanceDB Enterprise, this fetches the location from the server via describe. pub async fn uri(&self) -> Result { self.inner.uri().await } @@ -2483,7 +2819,7 @@ impl Table { /// Drop an index from the table. /// - /// Note: This is not yet available in LanceDB Distributed. + /// Note: This is not yet available in LanceDB Enterprise. /// /// This does not delete the index from disk, it just removes it from the table. /// To delete the index, run [`Self::optimize()`] after dropping the index. @@ -2516,7 +2852,7 @@ impl Table { /// This is a hint to the database that the given columns will be accessed in /// the future and the database should prefetch the data if possible. This /// can reduce cold-start latency for subsequent queries. Currently only - /// supported in LanceDB Distributed. + /// 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 — @@ -2839,6 +3175,8 @@ impl NativeTable { Err(e) => return Err(e.into()), }; + crate::docs::check_table_maintenance_warnings(&dataset, uri).await; + let dataset = DatasetConsistencyWrapper::new_latest(dataset, read_consistency_interval); let id = Self::build_id(&namespace, name); @@ -3717,7 +4055,8 @@ impl BaseTable for NativeTable { async fn prewarm_data(&self, _columns: Option>) -> Result<()> { Err(Error::NotSupported { - message: "prewarm_data is currently only supported in LanceDB Distributed.".into(), + message: DocLink::PrewarmData + .append_to("prewarm_data is currently only supported in LanceDB Enterprise."), }) } @@ -4143,7 +4482,7 @@ impl BaseTable for NativeTable { .await; sorted_sizes.sort(); - let small_frag_threshold = 100000; + let small_frag_threshold = crate::docs::SMALL_FRAGMENT_ROW_THRESHOLD; let num_fragments = sorted_sizes.len(); let num_small_fragments = sorted_sizes .iter() @@ -4288,9 +4627,10 @@ mod tests { use tempfile::tempdir; use super::*; + use lance_io::assert_io_lt; + use crate::connect; use crate::connection::ConnectBuilder; - use crate::io::object_store::io_tracking::IoTrackingStore; use crate::query::Select; use crate::query::{ExecutableQuery, QueryBase}; use crate::test_utils::connection::new_test_connection; @@ -4354,7 +4694,7 @@ mod tests { .await .unwrap_err(); assert!( - matches!(&err, Error::NotSupported { message } if message.contains("LanceDB Distributed")), + matches!(&err, Error::NotSupported { message } if message.contains("LanceDB Enterprise")), "{err:?}" ); } @@ -6322,34 +6662,31 @@ mod tests { table.add(batch.clone()).execute().await.unwrap(); } - // Reopen through a tracking store so the counters cover `stats()` alone and - // not the writes above. - let (wrapper, io_stats) = IoTrackingStore::new_wrapper(); - let table = conn - .open_table("test_stats_io") - .lance_read_params(ReadParams { - store_options: Some(ObjectStoreParams { - object_store_wrapper: Some(wrapper), - ..Default::default() - }), - ..Default::default() - }) - .execute() - .await - .unwrap(); - io_stats.lock().unwrap().read_iops = 0; + // Reopen, then count against the store's own tracker so the counters cover + // `stats()` alone and not the writes above. + let table = conn.open_table("test_stats_io").execute().await.unwrap(); + let io_tracker = { + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + dataset + .object_store(None) + .await + .unwrap() + .io_tracker() + .clone() + }; + io_tracker.incremental_stats(); let stats = table.stats().await.unwrap(); - let read_iops = io_stats.lock().unwrap().read_iops; + let io_stats = io_tracker.incremental_stats(); assert_eq!(stats.fragment_stats.num_fragments, NUM_APPENDS + 1); assert!(stats.total_bytes > 0); // Reading the fragments' data files would take at least one IOP each. - assert!( - read_iops < stats.fragment_stats.num_fragments as u64, - "stats() issued {} read IOPs across {} fragments", + assert_io_lt!( + io_stats, read_iops, - stats.fragment_stats.num_fragments + stats.fragment_stats.num_fragments as u64, + "stats() should not read the fragments' data files" ); } diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 24329d323..be319a8be 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -70,9 +70,9 @@ impl AddColumnsBuilder { /// expression names it. /// /// LanceDB Embedded declaration and refresh require the `experimental-functions` - /// Cargo feature. LanceDB Distributed operations do not require this feature. + /// Cargo feature. LanceDB Enterprise operations do not require this feature. /// - /// In LanceDB Distributed the expression is planned by the + /// In LanceDB Enterprise the expression is planned by the /// server, and the refresh runs as a server job -- see /// [`Table::refresh_column_async`](super::Table::refresh_column_async). /// diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 45d0e95dc..d2fdd165b 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -61,7 +61,7 @@ pub const AUTO_REFRESH_ENABLED_META_KEY: &str = "computed_column.auto_refresh_en pub const AUTO_REFRESH_INTERVAL_META_KEY: &str = "computed_column.auto_refresh_interval_seconds"; /// Scheduling settings persisted on each computed output. LanceDB Embedded -/// stores these settings; automatic scheduling requires LanceDB Distributed. +/// stores these settings; automatic scheduling requires LanceDB Enterprise. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct ComputedColumnOptions { @@ -407,12 +407,23 @@ pub(crate) fn ensure_supported_function_metadata(schema: &ArrowSchema) -> Result .iter() .map(|binding| (binding.binding_id(), binding)) .collect::>(); + let assignment_columns = bindings + .iter() + .filter_map(|binding| { + binding + .assignment() + .map(|assignment| assignment.output_name.as_str()) + }) + .collect::>(); for field in schema.fields() { - if field - .metadata() - .get(COMPUTED_COLUMN_META_KEY) - .map(String::as_str) - != Some("true") + // Assignment columns are server-owned bookkeeping, even when describe + // includes them. Only user-visible outputs require reciprocal metadata. + if assignment_columns.contains(field.name().as_str()) + || field + .metadata() + .get(COMPUTED_COLUMN_META_KEY) + .map(String::as_str) + != Some("true") { continue; } @@ -1028,7 +1039,7 @@ fn canonical_input_arrow_type(field: &JsonArrowField) -> Result { if is_blob_v2 || field.r#type.fields.is_some() { let arrow_field = lance_namespace::schema::convert_json_arrow_field(field) .map_err(|e| invalid_function(format!("invalid Function input field: {e}")))?; - validate_function_blob_nesting(&arrow_field, false)?; + validate_function_blob_nesting(&arrow_field, false, false)?; if is_blob_v2 { return Ok(FUNCTION_BLOB_V2_TYPE.to_string()); } @@ -1050,11 +1061,16 @@ fn has_supported_blob_v2_layout(field: &ArrowField) -> bool { ) } -fn validate_function_blob_nesting(field: &ArrowField, inside_collection: bool) -> Result<()> { +/// Blob v2 under a collection is accepted only where `collection_blobs` is set (outputs). +fn validate_function_blob_nesting( + field: &ArrowField, + inside_collection: bool, + collection_blobs: bool, +) -> Result<()> { if field.is_blob_v2() { - if inside_collection { + if inside_collection && !collection_blobs { return Err(invalid_function(format!( - "Function field '{}' nests Blob v2 under a collection, which Function signatures do not support", + "Function field '{}' nests Blob v2 under a collection; only a Function output may, under a list or large_list", field.name() ))); } @@ -1067,13 +1083,16 @@ fn validate_function_blob_nesting(field: &ArrowField, inside_collection: bool) - return Ok(()); } match field.data_type() { - DataType::Struct(fields) => fields - .iter() - .try_for_each(|field| validate_function_blob_nesting(field, inside_collection)), - DataType::List(field) - | DataType::LargeList(field) - | DataType::FixedSizeList(field, _) - | DataType::Map(field, _) => validate_function_blob_nesting(field, true), + DataType::Struct(fields) => fields.iter().try_for_each(|field| { + validate_function_blob_nesting(field, inside_collection, collection_blobs) + }), + DataType::List(field) | DataType::LargeList(field) => { + validate_function_blob_nesting(field, true, collection_blobs) + } + // Lance stores Blob v2 under List and LargeList only. + DataType::FixedSizeList(field, _) | DataType::Map(field, _) => { + validate_function_blob_nesting(field, true, false) + } _ => Ok(()), } } @@ -1172,7 +1191,7 @@ fn function_output_field(name: &str, nullable: bool, raw: &str) -> Result().ok()) - != Some(FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL) + // Servers may include the internal assignment in the persisted output + // schema while omitting it from describe. Compare only user outputs. + if let Some(fields) = declared_output_schema + .as_mut() + .and_then(|schema| schema.get_mut("fields")) + .and_then(Value::as_array_mut) { - return Err(invalid_function(format!( - "Function binding '{}' assignment column no longer matches its declaration", - binding.binding_id() - ))); + fields.retain(|field| { + field.get("name").and_then(Value::as_str) != Some(assignment.output_name.as_str()) + }); } - let json = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ - ArrowField::new(assignment.output_name.clone(), DataType::Boolean, true), - ])) - .map_err(|e| invalid_function(format!("invalid Function assignment schema: {e}")))?; - output_fields.push(json.fields.into_iter().next().unwrap()); - } else if binding.outputs().iter().all(|output| output.nullable) - && binding - .outputs() - .iter() - .all(|output| output.result_field != WHOLE_RESULT_FIELD) - { - return Err(invalid_function(format!( - "Function binding '{}' has no flattened-result assignment column", - binding.binding_id() - ))); } let output_schema = JsonArrowSchema::new(output_fields); let output_schema = serde_json::to_value(output_schema).map_err(|e| { @@ -1422,7 +1410,7 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding "could not encode exact Function output schema: {e}" )) })?; - if binding.output_schema() != Some(&output_schema) { + if declared_output_schema.as_ref() != Some(&output_schema) { return Err(invalid_function(format!( "Function binding '{}' output schema does not match physical siblings", binding.binding_id() @@ -3886,7 +3874,7 @@ mod tests { } #[test] - fn test_binding_preserves_all_nullable_outputs_with_an_assignment_column() { + fn test_binding_accepts_server_owned_assignment_columns() { let mut raw_binding: Value = serde_json::from_str(include_str!( "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" )) @@ -3895,16 +3883,11 @@ mod tests { raw_binding["outputs"][1]["nullable"] = Value::Bool(true); let without_assignment: FunctionBinding = serde_json::from_value(raw_binding.clone()).unwrap(); - let error = ensure_binding_matches_schema( + ensure_binding_matches_schema( &valid_function_binding_schema(true, true, &without_assignment), &without_assignment, ) - .unwrap_err(); - assert!( - error - .to_string() - .contains("flattened-result assignment column") - ); + .unwrap(); raw_binding["assignment"] = serde_json::json!({ "output_name": "__function_assignment_fb_01K3TEXT", @@ -3936,6 +3919,36 @@ mod tests { ); ensure_supported_function_metadata(&schema).unwrap(); + let assignment_name = &binding.assignment().unwrap().output_name; + let fields = schema + .fields() + .iter() + .filter(|field| field.name() != assignment_name) + .cloned() + .collect::>(); + let hidden = ArrowSchema::new_with_metadata(fields.clone(), schema.metadata().clone()); + ensure_supported_function_metadata(&hidden).unwrap(); + + // The assignment field's type and metadata belong to the server. + let mut fields = fields; + fields.push(Arc::new( + ArrowField::new(assignment_name, DataType::Int32, false).with_metadata(HashMap::from( + [ + (COMPUTED_COLUMN_META_KEY.into(), "true".into()), + (KIND_META_KEY.into(), "server_owned".into()), + ], + )), + )); + let changed = ArrowSchema::new_with_metadata(fields, schema.metadata().clone()); + ensure_supported_function_metadata(&changed).unwrap(); + + // Describe metadata may also omit the internal output-schema field. + let mut raw = serde_json::to_value(&binding).unwrap(); + raw["output_schema"]["fields"].as_array_mut().unwrap().pop(); + let binding_without_assignment_field: FunctionBinding = + serde_json::from_value(raw).unwrap(); + ensure_binding_matches_schema(&hidden, &binding_without_assignment_field).unwrap(); + let mut metadata: Value = serde_json::from_str(schema.metadata().get(FUNCTION_BINDINGS_META_KEY).unwrap()) .unwrap(); @@ -4486,6 +4499,72 @@ mod tests { assert!(!fields.iter().any(|field| field.name() == "payload")); } + #[test] + fn test_blob_children_under_lists_are_output_only() { + let input = crate::blob("image", false); + let accepted = [ + DataType::List(Arc::new(crate::blob("item", true))), + DataType::LargeList(Arc::new(crate::blob("item", true))), + ]; + for data_type in accepted { + let output_type = exact_arrow_type(ArrowField::new("frames", data_type, false)); + let output = serde_json::json!({ + "kind": "scalar", + "arrow_type": output_type, + "nullable": false + }); + let application = blob_application(&output.to_string()); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &application, + Some("frames"), + ) + .unwrap(); + + assert_eq!(plan.outputs.len(), 1); + assert_eq!(plan.outputs[0].output_name, "frames"); + assert!(plan.output_schema.fields[0].nullable); + let schema = + lance_namespace::schema::convert_json_arrow_schema(&plan.output_schema).unwrap(); + let item = match schema.field(0).data_type() { + DataType::List(item) | DataType::LargeList(item) => item, + other => panic!("expected a list output, got {other}"), + }; + assert!(item.is_blob_v2()); + } + + let rejected = [ + DataType::FixedSizeList(Arc::new(crate::blob("item", true)), 2), + DataType::Map( + Arc::new(ArrowField::new( + "entries", + DataType::Struct(Fields::from(vec![ + ArrowField::new("key", DataType::Utf8, false), + crate::blob("value", true), + ])), + false, + )), + false, + ), + ]; + for data_type in rejected { + let output_type = exact_arrow_type(ArrowField::new("frames", data_type, false)); + let output = serde_json::json!({ + "kind": "scalar", + "arrow_type": output_type, + "nullable": false + }); + let application = blob_application(&output.to_string()); + let error = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &application, + Some("frames"), + ) + .unwrap_err(); + assert!(error.to_string().contains("nests Blob v2"), "{error}"); + } + } + #[test] fn test_blob_children_under_collections_are_rejected() { let collections = vec![ diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 1795b778e..5f9ae13b4 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -480,7 +480,7 @@ mod tests { use arrow_array::{ Array, ArrayRef, BinaryArray, BooleanArray, FixedSizeListArray, Float32Array, Int32Array, LargeBinaryArray, LargeStringArray, ListArray, RecordBatch, StringArray, StructArray, - UInt32Array, + UInt32Array, UInt64Array, }; use arrow_data::ArrayDataBuilder; use arrow_schema::{DataType, Field, Schema}; @@ -502,6 +502,55 @@ mod tests { use lance_index::scalar::FullTextSearchQuery; use lance_index::scalar::inverted::query::{FtsQuery, MatchQuery}; + struct OrderPreservingShuffler; + + struct SinglePartitionReader { + batches: Vec, + } + + #[async_trait::async_trait] + impl lance_index::vector::v3::shuffler::Shuffler for OrderPreservingShuffler { + async fn shuffle( + &self, + data: Box, + ) -> lance_core::Result> { + Ok(Box::new(SinglePartitionReader { + batches: data.try_collect().await?, + })) + } + } + + #[async_trait::async_trait] + impl lance_index::vector::v3::shuffler::ShuffleReader for SinglePartitionReader { + async fn read_partition( + &self, + partition_id: usize, + ) -> lance_core::Result< + Option>, + > { + if partition_id != 0 || self.batches.is_empty() { + return Ok(None); + } + let schema = self.batches[0].schema(); + let stream = futures::stream::iter(self.batches.clone().into_iter().map(Ok)); + Ok(Some(Box::new( + lance_io::stream::RecordBatchStreamAdapter::new(schema, stream), + ))) + } + + fn partition_size(&self, partition_id: usize) -> lance_core::Result { + Ok(if partition_id == 0 { + self.batches.iter().map(RecordBatch::num_rows).sum() + } else { + 0 + }) + } + + fn total_loss(&self) -> Option { + Some(0.0) + } + } + fn create_fixed_size_list( values: T, list_size: i32, @@ -1012,6 +1061,135 @@ mod tests { assert_eq!(stats.distance_type, Some(crate::DistanceType::L2)); } + #[tokio::test] + async fn test_ivf_hnsw_sq_merge_preserves_shuffled_row_order() { + use lance::index::vector::builder::IvfIndexBuilder; + use lance_core::{ROW_ID, ROW_ID_FIELD, cache::LanceCache}; + use lance_encoding::decoder::{DecoderPlugins, FilterExpression}; + use lance_file::reader::{FileReader, FileReaderOptions}; + use lance_index::INDEX_AUXILIARY_FILE_NAME; + use lance_index::vector::hnsw::{HNSW, builder::HnswBuildParams}; + use lance_index::vector::ivf::IvfBuildParams; + use lance_index::vector::sq::{ScalarQuantizer, builder::SQBuildParams}; + use lance_io::ReadBatchParams; + use lance_io::object_store::ObjectStore; + use lance_io::scheduler::{ScanScheduler, SchedulerConfig}; + use lance_io::stream::RecordBatchStreamAdapter; + use lance_io::utils::CachedFileSize; + + const NUM_ROWS: usize = 64; + const DIMENSION: i32 = 16; + + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let vector_field = Field::new( + "embeddings", + DataType::FixedSizeList( + Arc::new(Field::new("item", DataType::Float32, true)), + DIMENSION, + ), + false, + ); + let values = Float32Array::from_iter_values( + (0..NUM_ROWS * DIMENSION as usize).map(|value| (value % 97) as f32), + ); + let vectors = Arc::new(create_fixed_size_list(values, DIMENSION).unwrap()); + let table_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![vector_field.clone()])), + vec![vectors.clone()], + ) + .unwrap(); + let table = conn + .create_table("test", table_batch) + .execute() + .await + .unwrap(); + + let dataset_guard = table.as_native().unwrap().dataset.get().await.unwrap(); + let dataset = (*dataset_guard).clone(); + drop(dataset_guard); + + // Descending row IDs are a small sentinel for the removed merge-time + // sort. The old sort reordered this batch and used FixedSizeList::take, + // which overflowed for the large partitions reported in #3126. + let expected_row_ids = (0..NUM_ROWS as u64).rev().collect::>(); + let input_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ROW_ID_FIELD.clone(), vector_field])), + vec![ + Arc::new(UInt64Array::from(expected_row_ids.clone())), + vectors, + ], + ) + .unwrap(); + let input = RecordBatchStreamAdapter::new( + input_batch.schema(), + futures::stream::iter(vec![Ok(input_batch)]), + ); + + let index_dir = dataset.indices_dir().join(uuid::Uuid::new_v4().to_string()); + let mut builder = IvfIndexBuilder::::new( + dataset, + "embeddings".to_string(), + index_dir.clone(), + lance_linalg::distance::DistanceType::L2, + Box::new(OrderPreservingShuffler), + Some(IvfBuildParams::new(1)), + Some(SQBuildParams::default()), + HnswBuildParams::default(), + None, + ) + .unwrap(); + builder.shuffle_data_input(Some(input)); + builder.build().await.unwrap(); + + let object_store = Arc::new(ObjectStore::local()); + let scheduler = ScanScheduler::new(object_store, SchedulerConfig::default_for_testing()); + let auxiliary_path = index_dir.join(INDEX_AUXILIARY_FILE_NAME); + let reader = FileReader::try_open( + scheduler + .open_file(&auxiliary_path, &CachedFileSize::unknown()) + .await + .unwrap(), + None, + Arc::::default(), + &LanceCache::no_cache(), + FileReaderOptions::default(), + ) + .await + .unwrap(); + let batches = reader + .read_stream( + ReadBatchParams::RangeFull, + u32::MAX, + 1, + FilterExpression::no_filter(), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let stored_row_ids = batches + .iter() + .flat_map(|batch| { + batch + .column_by_name(ROW_ID) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect::>(); + + assert_eq!(stored_row_ids, expected_row_ids); + } + #[tokio::test] async fn test_create_index_ivf_hnsw_pq() { use std::iter::repeat_with; diff --git a/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs b/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs index 06f9ba6d9..4627f901a 100644 --- a/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs +++ b/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs @@ -76,7 +76,7 @@ pub trait DuplicatePairsResolver: std::fmt::Debug + Send + Sync { ) -> Result>; } -/// `vector_duplicate_pairs('table', version, 'column', threshold)`. +/// `duplicate_pairs('table', version, 'column', threshold)`. /// Registration is explicit so the host controls catalog access and execution. #[derive(Debug)] pub struct DuplicatePairsTableFunction { @@ -108,7 +108,7 @@ impl TableFunctionImpl for DuplicatePairsTableFunction { fn call(&self, args: &[Expr]) -> Result> { if args.len() != 4 { return plan_err!( - "vector_duplicate_pairs requires (table, dataset_version, column, distance_threshold)" + "duplicate_pairs requires (table, dataset_version, column, distance_threshold)" ); } let string = |expr: &Expr| match expr { diff --git a/rust/lancedb/src/table/datafusion/udtf/vector_query.rs b/rust/lancedb/src/table/datafusion/udtf/vector_query.rs index 6b59a623b..dce350986 100644 --- a/rust/lancedb/src/table/datafusion/udtf/vector_query.rs +++ b/rust/lancedb/src/table/datafusion/udtf/vector_query.rs @@ -193,7 +193,7 @@ impl VectorQueryTable { || options.output.id_column.is_some()) { return plan_err!( - "vector_dedup requires all partitions and returns original rows; sampling and id_column are pair-query options" + "dedupe requires all partitions and returns original rows; sampling and id_column are pair-query options" ); } let config = DuplicatePairsConfig { diff --git a/rust/lancedb/src/table/dataset.rs b/rust/lancedb/src/table/dataset.rs index 69d02776f..2739522bc 100644 --- a/rust/lancedb/src/table/dataset.rs +++ b/rust/lancedb/src/table/dataset.rs @@ -373,10 +373,10 @@ mod tests { use super::*; - use crate::{ - connect, io::object_store::io_tracking::IoStatsHolder, table::WriteOptions, - utils::background_cache::clock, - }; + use lance_io::assert_io_eq; + use lance_io::utils::tracking_store::IOTracker; + + use crate::{connect, table::WriteOptions, utils::background_cache::clock}; async fn create_test_dataset(uri: &str) -> Dataset { let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); @@ -626,7 +626,7 @@ mod tests { .execute() .await .expect("Failed to connect to database"); - let io_stats = IoStatsHolder::default(); + let io_stats = IOTracker::default(); let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); @@ -651,7 +651,7 @@ mod tests { // latest version. table.schema().await.unwrap(); let stats = io_stats.incremental_stats(); - assert_eq!(stats.read_iops, 1); + assert_io_eq!(stats, read_iops, 1); } /// Regression test: a write that races with as_time_travel() must not panic. @@ -689,7 +689,7 @@ mod tests { .execute() .await .unwrap(); - let io_stats = IoStatsHolder::default(); + let io_stats = IOTracker::default(); let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); let table = db .create_empty_table("test", schema) @@ -712,12 +712,12 @@ mod tests { // Step 1: within interval — no list table.schema().await.unwrap(); let s = io_stats.incremental_stats(); - assert_eq!(s.read_iops, 0, "step 1, elapsed={:?}", start.elapsed()); + assert_io_eq!(s, read_iops, 0, "step 1, elapsed={:?}", start.elapsed()); // Step 2: still within interval — no list table.schema().await.unwrap(); let s = io_stats.incremental_stats(); - assert_eq!(s.read_iops, 0, "step 2, elapsed={:?}", start.elapsed()); + assert_io_eq!(s, read_iops, 0, "step 2, elapsed={:?}", start.elapsed()); // Step 3: sleep past the 1s boundary tokio::time::sleep(Duration::from_secs(1)).await; @@ -725,14 +725,14 @@ mod tests { // Step 4: interval expired — exactly 1 list, timer resets table.schema().await.unwrap(); let s = io_stats.incremental_stats(); - assert_eq!(s.read_iops, 1, "step 4, elapsed={:?}", start.elapsed()); + assert_io_eq!(s, read_iops, 1, "step 4, elapsed={:?}", start.elapsed()); // Step 5: 10 more calls — timer just reset, no lists (THIS is the regression test). for _ in 0..10 { table.schema().await.unwrap(); } let s = io_stats.incremental_stats(); - assert_eq!(s.read_iops, 0, "step 5, elapsed={:?}", start.elapsed()); + assert_io_eq!(s, read_iops, 0, "step 5, elapsed={:?}", start.elapsed()); } /// Helper: poison the mutex inside a DatasetConsistencyWrapper. diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index b2c933cd8..021abe5a9 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -4,20 +4,24 @@ //! Source-change detection for computed columns. //! //! A refresh fills nulls, so once a value is durable nothing recomputes it and -//! a later write to one of its inputs leaves it stale forever. Two stamps in -//! the column's field metadata close that: the definition it was computed -//! under, and a per-fragment signature of the input storage it was computed -//! from. A refresh compares both with the manifest and recomputes what -//! disagrees. Signatures are read from manifests, never from data. +//! a later write to one of its inputs leaves it stale forever. The column's +//! field metadata records the definition it was computed under, a +//! per-fragment signature of the input storage it was computed from, and the +//! rows whose retained values are not current for that signature. A refresh +//! compares the stamps with the manifest and recomputes what disagrees. +//! Signatures are read from manifests, never from data. //! //! The map is not stored in the manifest: it is one entry per fragment per //! column, which would dominate the manifest of a large table with many //! computed columns. It lives in an immutable sidecar object under //! `_computed/`, named by its content digest, and the field metadata holds -//! only the reference. Sidecars no retained version references are removed -//! by [`prune_sidecars`]. +//! only the reference. The sidecar also carries row-level exceptions and the +//! accepted repair basis, so old readers reject the newer format and +//! conservatively recompute. Sidecars no retained version references are +//! removed by [`prune_sidecars`]. use std::collections::{BTreeMap, HashMap, HashSet}; +use std::io::{Cursor, Read}; use std::ops::Range; use arrow_array::{Array, UInt64Array}; @@ -33,6 +37,7 @@ use object_store::path::Path; use roaring::RoaringBitmap; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; +use uuid::Uuid; use crate::table::computed_columns::{ DEFINITION_VERSION_META_KEY, RECORDED_AT_VERSION_META_KEY, SOURCE_SIGNATURE_META_KEY, @@ -46,6 +51,110 @@ const MAX_CARRY_FORWARD_VERSIONS: u64 = 1024; /// `{fragment id -> input signature}`. pub type SignatureMap = BTreeMap; +/// Rows whose retained values are not current for the fragment signature. +/// +/// `AllExcept` represents a fragment whose basis changed after a partial +/// refresh: every physical row is dirty except the offsets recorded as clean. +/// It avoids materializing a full bitmap while preserving a partially filled +/// fragment. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum DirtyRows { + /// The listed physical offsets are dirty. + Rows(RoaringBitmap), + /// Every physical offset is dirty except the listed clean offsets. + AllExcept(RoaringBitmap), +} + +impl DirtyRows { + fn mark_dirty(&mut self, rows: &RoaringBitmap) { + match self { + Self::Rows(dirty) => *dirty |= rows, + Self::AllExcept(clean) => *clean -= rows, + } + } + + fn mark_clean(&mut self, rows: &RoaringBitmap) { + match self { + Self::Rows(dirty) => *dirty -= rows, + Self::AllExcept(clean) => *clean |= rows, + } + } + + fn is_explicitly_empty(&self) -> bool { + matches!(self, Self::Rows(rows) if rows.is_empty()) + } + + /// Materialize the dirty offsets among `live_rows`. + pub fn live_dirty_rows(&self, live_rows: &RoaringBitmap) -> RoaringBitmap { + match self { + Self::Rows(dirty) => dirty & live_rows, + Self::AllExcept(clean) => live_rows - clean, + } + } +} + +/// `{fragment id -> row-level dirty state}`. A missing fragment is clean. +pub type RowStateMap = BTreeMap; + +/// The single owning value of the freshness sidecar. +/// +/// `SignatureMap` remains the public facade for callers that only need input +/// signatures. The row state and accepted basis live here so a reader can +/// never observe one half of a mixed-generation freshness record. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +struct FreshnessState { + signatures: SignatureMap, + row_state: RowStateMap, + basis: String, + // A fresh identity for each begin, even when the basis and dirty rows repeat. + intent_id: Uuid, +} + +impl FreshnessState { + fn normalize(mut self) -> Result { + self.row_state.retain(|_, rows| !rows.is_explicitly_empty()); + if self + .row_state + .keys() + .any(|fragment_id| !self.signatures.contains_key(fragment_id)) + { + return Err(invalid( + "row state names a fragment without a signature".to_string(), + )); + } + if self + .signatures + .values() + .any(|signature| !is_signature_hex(signature)) + { + return Err(invalid( + "freshness signature is not a 64-bit hex digest".to_string(), + )); + } + if self.basis.len() > u16::MAX as usize { + return Err(invalid("freshness basis exceeds u16 bytes".to_string())); + } + Ok(self) + } +} + +/// Opaque accepted-basis evidence returned by [`begin_row_repair`] and required by +/// [`finish_row_repair`]. +/// +/// The digest identifies the unified freshness state established before +/// publication, and the selected-row bitmaps bound which rows finalization +/// may change. One accepted wave can finalize disjoint fragments together; +/// later serialized waves preserve clean rows from earlier accepted waves. +/// Each begin persists a fresh intent identity in the sidecar, so repeating +/// the same basis and rows still fences stale non-noop finalization. There is +/// no per-row lease. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RowStateToken { + pub basis: String, + pub intent_digest: String, + pub selected_rows: BTreeMap, +} + /// Every field an input covers, keyed by column path: the field's own id /// first, then its ancestors', because a packed file records the physical /// column under an ancestor's id. @@ -270,12 +379,24 @@ pub enum StoredSignatures { Unreadable, } -/// Directory of signature sidecars, under the dataset root. +/// What the column's stored row-level state says. +#[derive(Debug, PartialEq, Eq)] +pub enum StoredRowStates { + /// No row-level state has been written; every live value is clean. + Absent, + /// Explicit dirty state for the fragments named in the map. + Present(RowStateMap), + /// The owning freshness sidecar cannot be read. + Unreadable, +} + +/// Directory of freshness sidecars, under the dataset root. const SIDECAR_DIR: &str = "_computed"; /// Metadata value prefix referencing a sidecar by its content digest. const SIDECAR_REF: &str = "sidecar:"; const SIDECAR_MAGIC: &[u8; 4] = b"CSIG"; -const SIDECAR_FORMAT: u8 = 1; +const SIDECAR_FORMAT_V1: u8 = 1; +const SIDECAR_FORMAT: u8 = 2; /// How long an unreferenced sidecar is presumed to be a stamp in flight: /// lance's own threshold for unverified files, independent of how much /// version history a cleanup keeps. @@ -293,12 +414,19 @@ fn sidecar_path(dataset: &Dataset, digest: &str) -> Result { .join(format!("{digest}.sig"))) } -/// `CSIG`, format byte, entry count, then one fragment id and 8-byte -/// signature per entry, all little-endian; 12 bytes per fragment. -fn encode_sidecar(map: &SignatureMap) -> Result> { +fn is_sha256_hex(value: &str) -> bool { + value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn is_signature_hex(value: &str) -> bool { + value.len() == 16 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +#[cfg(test)] +fn encode_legacy_sidecar(map: &SignatureMap) -> Result> { let mut bytes = Vec::with_capacity(9 + map.len() * 12); bytes.extend_from_slice(SIDECAR_MAGIC); - bytes.push(SIDECAR_FORMAT); + bytes.push(SIDECAR_FORMAT_V1); bytes.extend_from_slice( &u32::try_from(map.len()) .map_err(|_| invalid("too many fragments for a signature sidecar".to_string()))? @@ -316,9 +444,55 @@ fn encode_sidecar(map: &SignatureMap) -> Result> { Ok(bytes) } -fn decode_sidecar(bytes: &[u8]) -> Result { +/// `CSIG`, format byte, 16-byte intent UUID, basis, entry count, then for each fragment its id, +/// 8-byte signature, dirty-row mode and serialized bitmap. All integers are +/// little-endian. Format 1 remains readable as clean row state. +fn encode_sidecar(state: &FreshnessState) -> Result> { + let state = state.clone().normalize()?; + let basis_len = u16::try_from(state.basis.len()) + .map_err(|_| invalid("freshness basis exceeds u16 bytes".to_string()))?; + let fragment_count = u32::try_from(state.signatures.len()) + .map_err(|_| invalid("too many fragments for a freshness sidecar".to_string()))?; + let mut bytes = Vec::new(); + bytes.extend_from_slice(SIDECAR_MAGIC); + bytes.push(SIDECAR_FORMAT); + bytes.extend_from_slice(state.intent_id.as_bytes()); + bytes.extend_from_slice(&basis_len.to_le_bytes()); + bytes.extend_from_slice(state.basis.as_bytes()); + bytes.extend_from_slice(&fragment_count.to_le_bytes()); + for (fragment_id, signature) in &state.signatures { + let hash = u64::from_str_radix(signature, 16).map_err(|_| { + invalid(format!( + "signature '{signature}' is not a 64-bit hex digest" + )) + })?; + let rows = state + .row_state + .get(fragment_id) + .cloned() + .unwrap_or_else(|| DirtyRows::Rows(RoaringBitmap::new())); + let (kind, bitmap) = match rows { + DirtyRows::Rows(bitmap) => (0u8, bitmap), + DirtyRows::AllExcept(clean) => (1u8, clean), + }; + let mut encoded = Vec::with_capacity(bitmap.serialized_size()); + bitmap + .serialize_into(&mut encoded) + .map_err(|error| invalid(format!("encoding freshness bitmap: {error}")))?; + let bitmap_len = u32::try_from(encoded.len()) + .map_err(|_| invalid("freshness bitmap exceeds u32 bytes".to_string()))?; + bytes.extend_from_slice(&fragment_id.to_le_bytes()); + bytes.extend_from_slice(&hash.to_le_bytes()); + bytes.push(kind); + bytes.extend_from_slice(&bitmap_len.to_le_bytes()); + bytes.extend_from_slice(&encoded); + } + Ok(bytes) +} + +fn decode_legacy_sidecar(bytes: &[u8]) -> Result { let malformed = || invalid("signature sidecar is malformed".to_string()); - if bytes.len() < 9 || &bytes[..4] != SIDECAR_MAGIC || bytes[4] != SIDECAR_FORMAT { + if bytes.len() < 9 || &bytes[..4] != SIDECAR_MAGIC || bytes[4] != SIDECAR_FORMAT_V1 { return Err(malformed()); } let count = u32::from_le_bytes(bytes[5..9].try_into().map_err(|_| malformed())?) as usize; @@ -326,14 +500,91 @@ fn decode_sidecar(bytes: &[u8]) -> Result { if body.len() != count * 12 { return Err(malformed()); } - Ok(body + let signatures = body .chunks_exact(12) .map(|entry| { let fragment_id = u32::from_le_bytes(entry[..4].try_into().unwrap()); let hash = u64::from_le_bytes(entry[4..].try_into().unwrap()); (fragment_id, format!("{hash:016x}")) }) - .collect()) + .collect(); + Ok(FreshnessState { + signatures, + ..Default::default() + }) +} + +fn decode_sidecar(bytes: &[u8]) -> Result { + if bytes.len() >= 5 && &bytes[..4] == SIDECAR_MAGIC && bytes[4] == SIDECAR_FORMAT_V1 { + return decode_legacy_sidecar(bytes); + } + let malformed = || invalid("freshness sidecar is malformed".to_string()); + let mut cursor = Cursor::new(bytes); + let mut magic = [0u8; 4]; + cursor.read_exact(&mut magic).map_err(|_| malformed())?; + let mut format = [0u8; 1]; + cursor.read_exact(&mut format).map_err(|_| malformed())?; + if &magic != SIDECAR_MAGIC || format[0] != SIDECAR_FORMAT { + return Err(malformed()); + } + let mut intent_id = [0u8; 16]; + cursor.read_exact(&mut intent_id).map_err(|_| malformed())?; + let mut basis_len = [0u8; 2]; + cursor.read_exact(&mut basis_len).map_err(|_| malformed())?; + let mut basis = vec![0u8; u16::from_le_bytes(basis_len) as usize]; + cursor.read_exact(&mut basis).map_err(|_| malformed())?; + let basis = String::from_utf8(basis).map_err(|_| malformed())?; + let mut count = [0u8; 4]; + cursor.read_exact(&mut count).map_err(|_| malformed())?; + let count = u32::from_le_bytes(count) as usize; + let mut state = FreshnessState { + basis, + intent_id: Uuid::from_bytes(intent_id), + ..Default::default() + }; + for _ in 0..count { + let mut fragment_id = [0u8; 4]; + cursor + .read_exact(&mut fragment_id) + .map_err(|_| malformed())?; + let fragment_id = u32::from_le_bytes(fragment_id); + let mut signature = [0u8; 8]; + cursor.read_exact(&mut signature).map_err(|_| malformed())?; + let mut kind = [0u8; 1]; + cursor.read_exact(&mut kind).map_err(|_| malformed())?; + let mut bitmap_len = [0u8; 4]; + cursor + .read_exact(&mut bitmap_len) + .map_err(|_| malformed())?; + let bitmap_len = u32::from_le_bytes(bitmap_len) as usize; + let mut encoded = vec![0u8; bitmap_len]; + cursor.read_exact(&mut encoded).map_err(|_| malformed())?; + let mut bitmap_reader = Cursor::new(encoded.as_slice()); + let bitmap = + RoaringBitmap::deserialize_from(&mut bitmap_reader).map_err(|_| malformed())?; + if bitmap_reader.position() != bitmap_len as u64 { + return Err(malformed()); + } + let dirty = match kind[0] { + 0 => DirtyRows::Rows(bitmap), + 1 => DirtyRows::AllExcept(bitmap), + _ => return Err(malformed()), + }; + if state.signatures.contains_key(&fragment_id) { + return Err(malformed()); + } + state.signatures.insert( + fragment_id, + format!("{:016x}", u64::from_le_bytes(signature)), + ); + if !dirty.is_explicitly_empty() { + state.row_state.insert(fragment_id, dirty); + } + } + if cursor.position() != bytes.len() as u64 { + return Err(malformed()); + } + state.normalize() } fn digest_of(bytes: &[u8]) -> String { @@ -347,11 +598,14 @@ async fn store(dataset: &Dataset) -> Result> { Ok(dataset.object_store(None).await?) } -/// Write `map` as a sidecar and return the metadata value referencing it. -/// The object is named by its digest, so two columns with the same map +/// Write `state` as a sidecar and return the metadata value referencing it. +/// The object is named by its digest, so two columns with the same state /// share one object and a rewrite is idempotent. -async fn write_sidecar(dataset: &Dataset, map: &SignatureMap) -> Result { - let bytes = encode_sidecar(map)?; +async fn write_sidecar(dataset: &Dataset, state: &FreshnessState) -> Result { + write_sidecar_bytes(dataset, encode_sidecar(state)?).await +} + +async fn write_sidecar_bytes(dataset: &Dataset, bytes: Vec) -> Result { let digest = digest_of(&bytes); store(dataset) .await? @@ -360,11 +614,11 @@ async fn write_sidecar(dataset: &Dataset, map: &SignatureMap) -> Result Ok(format!("{SIDECAR_REF}{digest}")) } -/// A map is read from the table's own directory, then through the bases a +/// A sidecar is read from the table's own directory, then through the bases a /// shallow clone reads its data from, where the source stamped it. A copy /// found through a base is put in the table's own directory so it outlives /// the source's pruning; a failed copy only costs the next lookup. -async fn read_sidecar(dataset: &Dataset, digest: &str) -> Result { +async fn read_sidecar_bytes(dataset: &Dataset, digest: &str) -> Result { let own = sidecar_path(dataset, digest)?; let store = store(dataset).await?; let bytes = match store.read_one_all(&own).await { @@ -373,7 +627,7 @@ async fn read_sidecar(dataset: &Dataset, digest: &str) -> Result { let bytes = read_sidecar_through_bases(dataset, digest).await?; if let Err(error) = store.put(&own, &bytes).await { log::warn!( - "computed column signature sidecar {digest} could not be copied to {own}: {error}" + "computed column freshness sidecar {digest} could not be copied to {own}: {error}" ); } bytes @@ -382,10 +636,14 @@ async fn read_sidecar(dataset: &Dataset, digest: &str) -> Result { }; if digest_of(&bytes) != digest { return Err(invalid(format!( - "signature sidecar {digest} does not match its digest" + "freshness sidecar {digest} does not match its digest" ))); } - decode_sidecar(&bytes) + Ok(bytes) +} + +async fn read_sidecar(dataset: &Dataset, digest: &str) -> Result { + decode_sidecar(&read_sidecar_bytes(dataset, digest).await?) } async fn read_sidecar_through_bases(dataset: &Dataset, digest: &str) -> Result { @@ -416,11 +674,11 @@ async fn read_sidecar_through_bases(dataset: &Dataset, digest: &str) -> Result) -> Re Ok(()) } -/// Read the column's stored map. An unreadable map is a state, not an error: -/// failing here would make the column permanently unrefreshable, and the -/// unknown recomputes like every other unknown here. -pub async fn stored_signatures(dataset: &Dataset, column: &str) -> StoredSignatures { +enum StoredFreshnessState { + Absent, + Present { + state: FreshnessState, + digest: Option, + }, + Unreadable, +} + +async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshnessState { let Some(encoded) = field_meta(dataset, column, SOURCE_SIGNATURE_META_KEY) else { - return StoredSignatures::Absent; + return StoredFreshnessState::Absent; }; // Inline JSON is the declaration's empty seed and the pre-sidecar form. - let read = match encoded.strip_prefix(SIDECAR_REF) { - Some(digest) => read_sidecar(dataset, digest).await, - None => serde_json::from_str(&encoded).map_err(|e| invalid(e.to_string())), + let (read, digest) = match encoded.strip_prefix(SIDECAR_REF) { + Some(digest) => ( + read_sidecar(dataset, digest).await, + Some(digest.to_string()), + ), + None => ( + serde_json::from_str::(&encoded) + .map(|signatures| FreshnessState { + signatures, + ..Default::default() + }) + .map_err(|e| invalid(e.to_string())), + None, + ), }; match read { - Ok(map) => StoredSignatures::Present(map), + Ok(state) => StoredFreshnessState::Present { state, digest }, Err(error) => { log::warn!( - "computed column '{column}' source signature map is unreadable ({error}); every fragment will be recomputed" + "computed column '{column}' freshness state is unreadable ({error}); every fragment will be recomputed" ); - StoredSignatures::Unreadable + StoredFreshnessState::Unreadable } } } +/// Read the column's stored signature map through the versioned freshness +/// state. An unreadable sidecar remains a distinct fail-closed state. +pub async fn stored_signatures(dataset: &Dataset, column: &str) -> StoredSignatures { + match stored_freshness_state(dataset, column).await { + StoredFreshnessState::Absent => StoredSignatures::Absent, + StoredFreshnessState::Present { state, .. } => StoredSignatures::Present(state.signatures), + StoredFreshnessState::Unreadable => StoredSignatures::Unreadable, + } +} + +/// Read the explicit row-level dirty state associated with the column's +/// current signature map. +pub async fn stored_row_states(dataset: &Dataset, column: &str) -> StoredRowStates { + match stored_freshness_state(dataset, column).await { + StoredFreshnessState::Absent => StoredRowStates::Absent, + StoredFreshnessState::Present { state, .. } => StoredRowStates::Present(state.row_state), + StoredFreshnessState::Unreadable => StoredRowStates::Unreadable, + } +} + /// What a refresh must recompute beyond the null rows. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct StalenessPlan { @@ -523,6 +818,8 @@ pub struct StalenessPlan { /// Fragments whose inputs moved since they were computed, or that were /// never recorded. pub dirty: HashSet, + /// Current-signature fragments with only some rows dirty. + pub row_dirty: RowStateMap, /// Fragments a compaction produced from fresh ones, at their current /// signature: not dirty, and for the seal to record. pub inherited: SignatureMap, @@ -532,6 +829,20 @@ impl StalenessPlan { pub fn is_dirty(&self, fragment_id: u32) -> bool { self.recompute_all || self.dirty.contains(&fragment_id) } + + /// Whether any retained row in the fragment is known to be non-current. + pub fn has_dirty_rows(&self, fragment_id: u32) -> bool { + !self.recompute_all + && self + .row_dirty + .get(&fragment_id) + .is_some_and(|rows| !rows.is_explicitly_empty()) + } + + /// Whether the fragment requires any recomputation, whole or row-level. + pub fn needs_recompute(&self, fragment_id: u32) -> bool { + self.is_dirty(fragment_id) || self.has_dirty_rows(fragment_id) + } } /// A version of the log since the stamp that bears on carrying freshness @@ -691,23 +1002,32 @@ async fn holds_values_in( /// compaction since, so a chain of them carries too. Returns the produced /// fragments' signatures at production; the caller compares each with the /// current manifest, which catches anything written to them afterwards. +#[derive(Default)] +struct CarriedForward { + inherited: SignatureMap, + dirty_products: HashSet, +} + async fn carried_forward( dataset: &Dataset, column: &str, stored: &SignatureMap, + row_state: &RowStateMap, inputs: &InputFields, -) -> Result { +) -> Result { let Some(recorded_at) = field_meta(dataset, column, RECORDED_AT_VERSION_META_KEY) .and_then(|version| version.parse::().ok()) else { - return Ok(SignatureMap::new()); + return Ok(CarriedForward::default()); }; let to = dataset.version().version; if to <= recorded_at || to - recorded_at > MAX_CARRY_FORWARD_VERSIONS { - return Ok(SignatureMap::new()); + return Ok(CarriedForward::default()); } let mut fresh = stored.clone(); let mut inherited = SignatureMap::new(); + let mut dirty_products = HashSet::new(); + let mut known_dirty: HashSet = row_state.keys().copied().collect(); let mut appends = Vec::new(); let mut manifests = Manifests { dataset, @@ -723,6 +1043,7 @@ async fn carried_forward( Some(Step::Compaction(compactions)) => compactions, }; for (consumed, produced) in compactions { + let source_dirty = consumed.iter().any(|id| known_dirty.contains(id)); // Each source's signature and live rows just before the // compaction; live rows place its contribution in the product. let mut sources = Vec::with_capacity(consumed.len()); @@ -787,11 +1108,21 @@ async fn carried_forward( if let Some(signature) = signature_of(after, *id, inputs)? { fresh.insert(*id, signature.clone()); inherited.insert(*id, signature); + if source_dirty { + inherited.remove(id); + dirty_products.insert(*id); + known_dirty.insert(*id); + } else { + known_dirty.remove(id); + } } } } } - Ok(inherited) + Ok(CarriedForward { + inherited, + dirty_products, + }) } /// Decide what is stale, from the manifest alone. @@ -809,15 +1140,15 @@ pub async fn staleness_against( definition_version: &str, inputs: &InputFields, ) -> Result { - let stored = match stored_signatures(dataset, column).await { - StoredSignatures::Absent => return Ok(StalenessPlan::default()), - StoredSignatures::Unreadable => { + let stored = match stored_freshness_state(dataset, column).await { + StoredFreshnessState::Absent => return Ok(StalenessPlan::default()), + StoredFreshnessState::Unreadable => { return Ok(StalenessPlan { recompute_all: true, ..Default::default() }); } - StoredSignatures::Present(stored) => stored, + StoredFreshnessState::Present { state: stored, .. } => stored, }; let stored_version = field_meta(dataset, column, DEFINITION_VERSION_META_KEY); if stored_version.is_some_and(|version| version != definition_version) { @@ -826,16 +1157,23 @@ pub async fn staleness_against( ..Default::default() }); } + let FreshnessState { + signatures: stored, + row_state, + .. + } = stored; let unrecorded = dataset .get_fragments() .iter() .any(|fragment| !stored.contains_key(&(fragment.id() as u32))); - let mut inherited = if unrecorded { - carried_forward(dataset, column, &stored, inputs).await? + let carried = if unrecorded { + carried_forward(dataset, column, &stored, &row_state, inputs).await? } else { - SignatureMap::new() + CarriedForward::default() }; - let mut dirty = HashSet::new(); + let mut inherited = carried.inherited; + let mut dirty = carried.dirty_products; + let mut row_dirty = RowStateMap::new(); let mut live = HashSet::new(); let bases = Bases::of(dataset)?; for fragment in dataset.get_fragments() { @@ -844,12 +1182,16 @@ pub async fn staleness_against( let current = fragment_input_signature(&bases, fragment.metadata(), inputs)?; if stored.get(&id).or_else(|| inherited.get(&id)) != Some(¤t) { dirty.insert(id); + } else if let Some(rows) = row_state.get(&id) { + row_dirty.insert(id, rows.clone()); } } inherited.retain(|id, _| live.contains(id) && !dirty.contains(id)); + row_dirty.retain(|id, _| live.contains(id) && !dirty.contains(id)); Ok(StalenessPlan { recompute_all: false, dirty, + row_dirty, inherited, }) } @@ -938,40 +1280,448 @@ pub async fn write_signatures( .iter() .map(|fragment| fragment.id() as u32) .collect(); - // An unreadable map is discarded rather than merged: nothing in it can be - // trusted, and its fragments recompute until a later refresh records them. - let mut merged = match stored_signatures(dataset, column).await { - StoredSignatures::Present(stored) => stored, - StoredSignatures::Absent | StoredSignatures::Unreadable => SignatureMap::new(), + // An unreadable state is discarded rather than merged: nothing in it can + // be trusted, and its fragments recompute until a later refresh records + // them. + let stored = stored_freshness_state(dataset, column).await; + let state_unreadable = matches!(&stored, StoredFreshnessState::Unreadable); + let mut state = match stored { + StoredFreshnessState::Present { state, .. } => state, + StoredFreshnessState::Absent | StoredFreshnessState::Unreadable => { + FreshnessState::default() + } }; - merged.extend(entries); - merged.retain(|fragment_id, _| live.contains(fragment_id)); - // The sidecar is durable before the commit references it; a failure in - // between leaves an unreferenced object for `prune_sidecars`. - let encoded = if merged.is_empty() { - "{}".to_string() + let recomputed: HashSet = entries.keys().copied().collect(); + let signatures_changed = entries + .iter() + .any(|(fragment_id, signature)| state.signatures.get(fragment_id) != Some(signature)); + if state_unreadable + && !live + .iter() + .all(|fragment_id| recomputed.contains(fragment_id)) + { + return Err(invalid( + "cannot replace an unreadable freshness state from a partial signature stamp" + .to_string(), + )); + } + // A signature entry written through this API means the fragment was + // recomputed in full. Whole callers keep their old semantics while + // clearing any partial retry state left by a previous publication. + for fragment_id in &recomputed { + state.row_state.remove(fragment_id); + } + state.signatures.extend(entries); + state + .signatures + .retain(|fragment_id, _| live.contains(fragment_id)); + state + .row_state + .retain(|fragment_id, _| live.contains(fragment_id)); + if state.row_state.is_empty() || state_unreadable || signatures_changed { + state.basis.clear(); + } + Ok( + write_freshness_state(dataset, column, definition_version, state, false, None) + .await? + .version, + ) +} + +struct FreshnessWrite { + version: u64, + intent_digest: Option, +} + +async fn write_freshness_state( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + state: FreshnessState, + retain_empty_sidecar: bool, + expected_latest_version: Option, +) -> Result { + let state = state.normalize()?; + let inline_empty = state.signatures.is_empty() + && state.row_state.is_empty() + && state.basis.is_empty() + && !retain_empty_sidecar; + // The sidecar is durable before the metadata commit references it. + // Unreferenced objects are removed by `prune_sidecars`. + let (signature_ref, intent_digest) = if inline_empty { + ("{}".to_string(), None) } else { - write_sidecar(dataset, &merged).await? + let reference = write_sidecar(dataset, &state).await?; + let digest = reference + .strip_prefix(SIDECAR_REF) + .expect("sidecar reference has its prefix") + .to_string(); + (reference, Some(digest)) }; let describes = dataset.version().version; - dataset - .update_field_metadata() - .update( - column, - [ - (SOURCE_SIGNATURE_META_KEY.to_string(), encoded), - ( - DEFINITION_VERSION_META_KEY.to_string(), - definition_version.to_string(), - ), - ( - RECORDED_AT_VERSION_META_KEY.to_string(), - describes.to_string(), - ), - ], - )? - .await?; - Ok(dataset.version().version) + let updates = vec![ + (SOURCE_SIGNATURE_META_KEY.to_string(), Some(signature_ref)), + ( + DEFINITION_VERSION_META_KEY.to_string(), + Some(definition_version.to_string()), + ), + ( + RECORDED_AT_VERSION_META_KEY.to_string(), + Some(describes.to_string()), + ), + ]; + let builder = dataset.update_field_metadata().update(column, updates)?; + match expected_latest_version { + Some(expected) => builder.with_expected_latest_version(expected).await?, + None => builder.await?, + }; + Ok(FreshnessWrite { + version: dataset.version().version, + intent_digest, + }) +} + +/// One fragment's rows selected by an accepted refresh request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RowRepair { + /// Input signature of the request's pinned source. + pub signature: String, + /// Selected physical offsets. They become dirty before publication. + pub rows: RoaringBitmap, +} + +/// Durably mark every selected row dirty before its data publication. +/// +/// The returned token binds the subsequent filled-row clear to the accepted +/// input basis and selected rows. This function checks the accepted +/// signatures against the latest manifest and does not retry a concurrent +/// metadata conflict with stale state. +/// +/// `basis` identifies the request's accepted input snapshot. It may be reused +/// when retrying the same inputs: each successful begin records a new intent +/// identity independently of that basis. +/// +/// Publication and verification belong to the caller. In this example, +/// `publish_values` writes the selected computed values and retains a receipt; +/// `verify_survival` checks that receipt against the latest snapshot, including +/// any intervening Restore. These two helpers are application-defined. +/// +/// ``` +/// use std::collections::BTreeMap; +/// use lance::Dataset; +/// use lancedb::Result; +/// use lancedb::table::freshness::{ +/// begin_row_repair, finish_row_repair, InputFields, RowRepair, RowStateToken, +/// }; +/// use roaring::RoaringBitmap; +/// # struct Publication { +/// # filled: BTreeMap, +/// # skipped: BTreeMap, +/// # } +/// # async fn publish_values(_: &mut Dataset, _: &RowStateToken) -> Result { +/// # unimplemented!() +/// # } +/// # async fn verify_survival(_: &Dataset, _: &Publication) -> Result<()> { +/// # unimplemented!() +/// # } +/// async fn repair( +/// dataset: &mut Dataset, +/// inputs: &InputFields, +/// selected: &BTreeMap, +/// ) -> Result { +/// let token = begin_row_repair( +/// dataset, "embedding", "definition-v1", inputs, +/// "accepted-input-snapshot", selected, +/// ).await?; +/// let publication = publish_values(dataset, &token).await?; +/// dataset.checkout_latest().await?; +/// verify_survival(dataset, &publication).await?; +/// let verified_version = dataset.version().version; +/// finish_row_repair( +/// dataset, "embedding", "definition-v1", inputs, &token, +/// &publication.filled, &publication.skipped, Some(verified_version), +/// ).await +/// } +/// ``` +/// +/// `verified_version` is the snapshot just checked for publication survival, +/// not the version returned by begin or the original publication. Passing it +/// to [`finish_row_repair`] prevents a later version change from silently +/// rebasing the clean-row update. `None` omits that version fence. +pub async fn begin_row_repair( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + basis: impl Into, + repairs: &BTreeMap, +) -> Result { + let basis = basis.into(); + if basis.is_empty() { + return Err(invalid("row repair basis must not be empty".to_string())); + } + if repairs.is_empty() { + return Err(invalid("row repair has no fragments".to_string())); + } + for repair in repairs.values() { + if !is_signature_hex(&repair.signature) { + return Err(invalid( + "row repair signature is not a 64-bit hex digest".to_string(), + )); + } + } + dataset.checkout_latest().await?; + let live: HashSet = dataset + .get_fragments() + .iter() + .map(|fragment| fragment.id() as u32) + .collect(); + if let Some(missing) = repairs.keys().find(|id| !live.contains(id)) { + return Err(invalid(format!( + "row repair names fragment {missing}, which is not live" + ))); + } + + let stored_version = field_meta(dataset, column, DEFINITION_VERSION_META_KEY); + let definition_changed = stored_version.is_some_and(|version| version != definition_version); + let stored = stored_freshness_state(dataset, column).await; + let was_absent = matches!(&stored, StoredFreshnessState::Absent); + let state_unreadable = matches!(&stored, StoredFreshnessState::Unreadable); + let mut freshness = match stored { + StoredFreshnessState::Present { state, .. } => state, + StoredFreshnessState::Absent | StoredFreshnessState::Unreadable => { + FreshnessState::default() + } + }; + + if was_absent && !state_unreadable { + freshness.signatures = + signatures_for(dataset, &live.iter().copied().collect::>(), inputs)?; + freshness.row_state.clear(); + freshness.basis.clear(); + } + if state_unreadable || definition_changed { + freshness.signatures = + signatures_for(dataset, &live.iter().copied().collect::>(), inputs)?; + freshness.row_state = live + .iter() + .map(|id| (*id, DirtyRows::AllExcept(RoaringBitmap::new()))) + .collect(); + } + + for (fragment_id, repair) in repairs { + let current = signature_of(dataset, *fragment_id, inputs)?.ok_or_else(|| { + invalid(format!( + "row repair fragment {fragment_id} disappeared from the latest manifest" + )) + })?; + if current != repair.signature { + return Err(invalid(format!( + "row repair fragment {fragment_id} input basis changed before dirty intent" + ))); + } + let preserve = !state_unreadable + && !definition_changed + && freshness.signatures.get(fragment_id) == Some(¤t); + let dirty = if preserve { + freshness + .row_state + .entry(*fragment_id) + .or_insert_with(|| DirtyRows::Rows(RoaringBitmap::new())) + } else { + freshness + .row_state + .insert(*fragment_id, DirtyRows::AllExcept(RoaringBitmap::new())); + freshness + .row_state + .get_mut(fragment_id) + .expect("row state was just inserted") + }; + dirty.mark_dirty(&repair.rows); + freshness.signatures.insert(*fragment_id, current); + } + freshness + .signatures + .retain(|fragment_id, _| live.contains(fragment_id)); + freshness + .row_state + .retain(|fragment_id, _| live.contains(fragment_id)); + freshness.basis = basis.clone(); + freshness.intent_id = Uuid::new_v4(); + + let write = + write_freshness_state(dataset, column, definition_version, freshness, true, None).await?; + let intent_digest = write + .intent_digest + .ok_or_else(|| invalid("row repair dirty intent produced no sidecar".to_string()))?; + Ok(RowStateToken { + basis, + intent_digest, + selected_rows: repairs + .iter() + .map(|(fragment_id, repair)| (*fragment_id, repair.rows.clone())) + .collect(), + }) +} + +fn apply_row_repair( + rows: &mut RowStateMap, + selections: &BTreeMap, + filled_rows: &BTreeMap, + skipped_rows: &BTreeMap, +) -> Result<()> { + if filled_rows + .keys() + .chain(skipped_rows.keys()) + .any(|fragment_id| !selections.contains_key(fragment_id)) + { + return Err(invalid( + "row repair result names a fragment outside its token".to_string(), + )); + } + for (fragment_id, selected) in selections { + if filled_rows + .get(fragment_id) + .zip(skipped_rows.get(fragment_id)) + .is_some_and(|(filled, skipped)| !(filled & skipped).is_empty()) + { + return Err(invalid(format!( + "row repair fragment {fragment_id} marks a row both filled and skipped" + ))); + } + if filled_rows + .get(fragment_id) + .is_some_and(|filled| !filled.is_subset(selected)) + || skipped_rows + .get(fragment_id) + .is_some_and(|skipped| !skipped.is_subset(selected)) + { + return Err(invalid(format!( + "row repair fragment {fragment_id} changes a row outside its selected set" + ))); + } + let state = rows + .entry(*fragment_id) + .or_insert_with(|| DirtyRows::Rows(RoaringBitmap::new())); + if let Some(filled) = filled_rows.get(fragment_id) { + state.mark_clean(filled); + } + if let Some(skipped) = skipped_rows.get(fragment_id) { + state.mark_dirty(skipped); + } + } + rows.retain(|_, state| !state.is_explicitly_empty()); + Ok(()) +} + +/// Clear rows whose publication was accepted and keep every skipped row dirty. +/// +/// The token names the accepted input basis and the exact rows it may change. +/// One accepted wave can finalize disjoint fragments together, and later +/// serialized waves preserve clean rows from earlier accepted waves. A newer +/// dirty intent fences a stale non-noop finalization; exact replay of the +/// accepted transition is idempotent. This API deliberately does not invent a +/// second per-row lease. +/// +/// `verified_version` is the latest version whose publication survival the +/// caller verified. With `Some`, finalization commits field metadata +/// conditionally from that exact version, so a Restore before or during the +/// commit fails instead of being rebased underneath the verified publication; +/// with `None`, it uses ordinary metadata-commit semantics and provides no +/// version fence. +#[allow(clippy::too_many_arguments)] +pub async fn finish_row_repair( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + token: &RowStateToken, + filled_rows: &BTreeMap, + skipped_rows: &BTreeMap, + verified_version: Option, +) -> Result { + if !is_sha256_hex(&token.intent_digest) { + return Err(invalid("row repair token is malformed".to_string())); + } + if filled_rows + .keys() + .chain(skipped_rows.keys()) + .any(|fragment_id| !token.selected_rows.contains_key(fragment_id)) + { + return Err(invalid( + "row repair result names a fragment outside its token".to_string(), + )); + } + dataset.checkout_latest().await?; + if verified_version.is_some_and(|version| dataset.version().version != version) { + return Err(invalid( + "row repair latest version changed after publication verification".to_string(), + )); + } + let (mut state, current_digest) = match stored_freshness_state(dataset, column).await { + StoredFreshnessState::Present { + state, + digest: Some(digest), + } => (state, digest), + StoredFreshnessState::Present { digest: None, .. } => { + return Err(invalid( + "row repair token cannot name an inline freshness state".to_string(), + )); + } + StoredFreshnessState::Absent | StoredFreshnessState::Unreadable => { + return Err(invalid( + "row repair freshness state disappeared before finalization".to_string(), + )); + } + }; + if state.basis != token.basis { + return Err(invalid( + "row repair token does not match the current dirty intent".to_string(), + )); + } + for fragment_id in token.selected_rows.keys() { + let expected = state.signatures.get(fragment_id).ok_or_else(|| { + invalid(format!( + "row repair fragment {fragment_id} lost its signature" + )) + })?; + let current = signature_of(dataset, *fragment_id, inputs)?.ok_or_else(|| { + invalid(format!( + "row repair fragment {fragment_id} disappeared before finalization" + )) + })?; + if expected != ¤t { + return Err(invalid(format!( + "row repair fragment {fragment_id} input basis changed before finalization" + ))); + } + } + let before = state.row_state.clone(); + apply_row_repair( + &mut state.row_state, + &token.selected_rows, + filled_rows, + skipped_rows, + )?; + if state.row_state == before { + return Ok(dataset.version().version); + } + if current_digest != token.intent_digest.as_str() { + return Err(invalid( + "row repair dirty intent changed before finalization".to_string(), + )); + } + state.basis = token.basis.clone(); + let write = write_freshness_state( + dataset, + column, + definition_version, + state, + true, + verified_version, + ) + .await?; + Ok(write.version) } #[cfg(test)] @@ -1063,6 +1813,737 @@ mod tests { .unwrap(); } + fn fragment_signature(dataset: &Dataset, fragment_id: u32) -> String { + signature_of(dataset, fragment_id, &inputs(dataset)) + .unwrap() + .unwrap() + } + + fn repair(dataset: &Dataset, fragment_id: u32, rows: RoaringBitmap) -> RowRepair { + RowRepair { + signature: fragment_signature(dataset, fragment_id), + rows, + } + } + + #[test] + fn unified_sidecar_round_trips_partial_clean_exceptions() { + let state = FreshnessState { + signatures: SignatureMap::from([ + (3, "0000000000000003".to_string()), + (7, "0000000000000007".to_string()), + ]), + basis: "job-generation".to_string(), + intent_id: Uuid::from_u128(7), + row_state: RowStateMap::from([ + (3, DirtyRows::Rows(RoaringBitmap::from_iter([1, 4, 9]))), + (7, DirtyRows::AllExcept(RoaringBitmap::from_iter([0, 2]))), + ]), + }; + let encoded = encode_sidecar(&state).unwrap(); + assert_eq!(encoded[4], SIDECAR_FORMAT); + assert!( + decode_legacy_sidecar(&encoded).is_err(), + "an old reader must reject the row-aware format" + ); + assert_eq!(decode_sidecar(&encoded).unwrap(), state); + } + + #[test] + fn legacy_sidecar_is_read_as_clean_rows() { + let signatures = SignatureMap::from([ + (1, "0000000000000001".to_string()), + (2, "0000000000000002".to_string()), + ]); + let state = decode_sidecar(&encode_legacy_sidecar(&signatures).unwrap()).unwrap(); + assert_eq!(state.signatures, signatures); + assert!(state.row_state.is_empty()); + assert!(state.basis.is_empty()); + } + + #[tokio::test] + async fn a_row_repair_clears_filled_rows_and_retains_skipped_rows() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1, 2])))]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-job-generation-a", + &repairs, + ) + .await + .unwrap(); + + let before = plan(&dataset).await; + assert!(before.dirty.is_empty()); + assert_eq!( + before.row_dirty.get(&0), + Some(&DirtyRows::Rows(RoaringBitmap::from_iter([1, 2]))) + ); + + let version = finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + None, + ) + .await + .unwrap(); + assert_eq!( + stored_row_states(&dataset, COLUMN).await, + StoredRowStates::Present(RowStateMap::from([( + 0, + DirtyRows::Rows(RoaringBitmap::from_iter([2])), + )])) + ); + assert_eq!( + plan(&dataset).await.row_dirty.get(&0), + Some(&DirtyRows::Rows(RoaringBitmap::from_iter([2]))) + ); + + // Replaying the accepted transition changes nothing. + assert_eq!( + finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + None, + ) + .await + .unwrap(), + version + ); + } + + #[tokio::test] + async fn a_definition_change_preserves_filled_clean_exceptions() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let ids = inputs(&dataset); + let definition = "definition-generation-b"; + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([0])))]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + definition, + &ids, + "accepted-job-generation-b", + &repairs, + ) + .await + .unwrap(); + finish_row_repair( + &mut dataset, + COLUMN, + definition, + &ids, + &token, + &BTreeMap::from([(0, RoaringBitmap::from_iter([0]))]), + &BTreeMap::new(), + None, + ) + .await + .unwrap(); + + let plan = staleness_against(&dataset, COLUMN, definition, &ids) + .await + .unwrap(); + assert!(plan.dirty.is_empty()); + assert_eq!( + plan.row_dirty.get(&0), + Some(&DirtyRows::AllExcept(RoaringBitmap::from_iter([0]))) + ); + assert_eq!( + plan.row_dirty.get(&1), + Some(&DirtyRows::AllExcept(RoaringBitmap::new())) + ); + } + + #[tokio::test] + async fn one_token_finishes_disjoint_fragments_without_clearing_other_rows() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([ + (0, repair(&dataset, 0, RoaringBitmap::from_iter([1]))), + (1, repair(&dataset, 1, RoaringBitmap::from_iter([2]))), + ]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &repairs, + ) + .await + .unwrap(); + finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &BTreeMap::from([(1, RoaringBitmap::from_iter([2]))]), + None, + ) + .await + .unwrap(); + assert_eq!( + stored_row_states(&dataset, COLUMN).await, + StoredRowStates::Present(RowStateMap::from([( + 1, + DirtyRows::Rows(RoaringBitmap::from_iter([2])), + )])) + ); + } + + #[tokio::test] + async fn a_new_intent_blocks_a_stale_non_noop_finish() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let first_repair = + BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1])))]); + let first = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &first_repair, + ) + .await + .unwrap(); + let second_repair = + BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([3])))]); + begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &second_repair, + ) + .await + .unwrap(); + let before = stored_row_states(&dataset, COLUMN).await; + let error = finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &first, + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &BTreeMap::new(), + None, + ) + .await + .expect_err("a newer dirty intent must fence a non-noop finish"); + assert!( + error.to_string().contains("dirty intent changed"), + "{error}" + ); + assert_eq!(stored_row_states(&dataset, COLUMN).await, before); + } + + #[tokio::test] + async fn repeated_row_repair_intent_fences_old_completion() { + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let mut dataset = table(uri).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1])))]); + let selected = BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]); + let first = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &repairs, + ) + .await + .unwrap(); + finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &first, + &selected, + &BTreeMap::new(), + None, + ) + .await + .unwrap(); + + let second = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &repairs, + ) + .await + .unwrap(); + let verified = dataset.version().version; + finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &second, + &BTreeMap::new(), + &selected, + Some(verified), + ) + .await + .unwrap(); + + let expected = StoredRowStates::Present(RowStateMap::from([( + 0, + DirtyRows::Rows(RoaringBitmap::from_iter([1])), + )])); + let mut reopened = Dataset::open(uri).await.unwrap(); + assert_eq!(stored_row_states(&reopened, COLUMN).await, expected); + let verified = reopened.version().version; + let error = finish_row_repair( + &mut reopened, + COLUMN, + &definition, + &ids, + &first, + &selected, + &BTreeMap::new(), + Some(verified), + ) + .await + .expect_err("an old completion must not clear a newer skipped repair of the same rows"); + assert!( + error.to_string().contains("dirty intent changed"), + "{error}" + ); + assert_eq!(reopened.version().version, verified); + let reopened = Dataset::open(uri).await.unwrap(); + assert_eq!(stored_row_states(&reopened, COLUMN).await, expected); + } + + #[tokio::test] + async fn recovery_rejects_a_restore_after_publication_verification() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1])))]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &repairs, + ) + .await + .unwrap(); + let intent_version = dataset.version().version; + let mut publication = dataset.clone(); + publication + .update_field_metadata() + .update(COLUMN, [("fixture.publication", "1")]) + .unwrap() + .await + .unwrap(); + let verified = publication.version().version; + + let mut intent = dataset.checkout_version(intent_version).await.unwrap(); + intent.restore().await.unwrap(); + let before = stored_row_states(&dataset, COLUMN).await; + let error = finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &BTreeMap::new(), + Some(verified), + ) + .await + .expect_err("a restore after verification must fence recovery finalization"); + + assert!( + error + .to_string() + .contains("latest version changed after publication verification"), + "{error}" + ); + assert_eq!(stored_row_states(&dataset, COLUMN).await, before); + assert_eq!( + plan(&dataset).await.row_dirty.get(&0), + Some(&DirtyRows::Rows(RoaringBitmap::from_iter([1]))), + "the recovered row must remain retryable" + ); + } + + #[tokio::test] + async fn an_all_success_finish_replays_without_a_legacy_sidecar() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1])))]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &repairs, + ) + .await + .unwrap(); + let filled = BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]); + let version = finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &filled, + &BTreeMap::new(), + None, + ) + .await + .unwrap(); + assert_eq!( + stored_row_states(&dataset, COLUMN).await, + StoredRowStates::Present(RowStateMap::new()), + "an accepted all-success transition keeps an empty freshness sidecar for replay" + ); + assert_eq!( + finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &filled, + &BTreeMap::new(), + None, + ) + .await + .unwrap(), + version + ); + + corrupt_current_sidecar(&dataset).await; + let error = finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &filled, + &BTreeMap::new(), + None, + ) + .await + .expect_err("legacy absence cannot prove an accepted generation"); + assert!( + error + .to_string() + .contains("disappeared before finalization"), + "{error}" + ); + } + + #[tokio::test] + async fn finish_rejects_rows_outside_the_token_selection() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1])))]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &repairs, + ) + .await + .unwrap(); + let before = stored_row_states(&dataset, COLUMN).await; + let error = finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + &BTreeMap::new(), + None, + ) + .await + .expect_err("a token must not clear rows it did not select"); + assert!( + error + .to_string() + .contains("changes a row outside its selected set"), + "{error}" + ); + assert_eq!(stored_row_states(&dataset, COLUMN).await, before); + } + + #[tokio::test] + async fn unreadable_row_state_keeps_unselected_fragments_dirty() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1])))]); + let stale = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &repairs, + ) + .await + .unwrap(); + finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &stale, + &BTreeMap::new(), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + None, + ) + .await + .unwrap(); + corrupt_current_sidecar(&dataset).await; + + let retry = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([2])))]); + begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "retry-input-basis", + &retry, + ) + .await + .unwrap(); + let plan = plan(&dataset).await; + assert_eq!( + plan.row_dirty.get(&0), + Some(&DirtyRows::AllExcept(RoaringBitmap::new())) + ); + assert_eq!( + plan.row_dirty.get(&1), + Some(&DirtyRows::AllExcept(RoaringBitmap::new())), + "unreadable state outside the selected fragment must stay dirty" + ); + } + + #[tokio::test] + async fn write_signatures_fails_closed_for_unreadable_row_state() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1])))]); + let stale = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &repairs, + ) + .await + .unwrap(); + finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &stale, + &BTreeMap::new(), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + None, + ) + .await + .unwrap(); + corrupt_current_sidecar(&dataset).await; + + let partial = SignatureMap::from([(0, fragment_signature(&dataset, 0))]); + let error = write_signatures(&mut dataset, COLUMN, &definition, partial) + .await + .expect_err("a partial stamp cannot replace unreadable state"); + assert!( + error.to_string().contains("partial signature stamp"), + "{error}" + ); + assert!(plan(&dataset).await.recompute_all); + } + + #[tokio::test] + async fn concurrent_field_metadata_writes_on_one_field_conflict() { + let dir = tempfile::tempdir().unwrap(); + let dataset = table(dir.path().to_str().unwrap()).await; + let mut left = dataset.clone(); + let mut right = dataset.clone(); + let left_write = async { + left.update_field_metadata() + .update(COLUMN, [("computed_refresh.concurrent_a", "1")]) + .unwrap() + .await + }; + let right_write = async { + right + .update_field_metadata() + .update(COLUMN, [("computed_refresh.concurrent_b", "2")]) + .unwrap() + .await + }; + let (left_result, right_result) = tokio::join!(left_write, right_write); + assert_eq!( + usize::from(left_result.is_ok()) + usize::from(right_result.is_ok()), + 1, + "same-field metadata writes must conflict: {left_result:?} {right_result:?}" + ); + } + + #[tokio::test] + async fn pruning_tracks_unified_freshness_sidecars() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1])))]); + begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-input-basis", + &repairs, + ) + .await + .unwrap(); + assert_eq!(sidecar_names(&dataset).await.len(), 2); + assert_eq!(prune_sidecars(&dataset, true).await.unwrap(), 0); + + dataset + .update_field_metadata() + .update( + COLUMN, + [(SOURCE_SIGNATURE_META_KEY.to_string(), "{}".to_string())], + ) + .unwrap() + .await + .unwrap(); + dataset + .cleanup_old_versions(chrono::Duration::zero(), Some(true), None) + .await + .unwrap(); + assert_eq!(prune_sidecars(&dataset, true).await.unwrap(), 2); + assert!(sidecar_names(&dataset).await.is_empty()); + } + + #[tokio::test] + async fn corrupt_unified_freshness_state_fails_closed() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1])))]); + begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-job-generation-a", + &repairs, + ) + .await + .unwrap(); + corrupt_current_sidecar(&dataset).await; + assert!(plan(&dataset).await.recompute_all); + } + + #[tokio::test] + async fn compaction_from_a_partially_dirty_source_recomputes_the_product() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, RoaringBitmap::from_iter([1])))]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "accepted-job-generation-a", + &repairs, + ) + .await + .unwrap(); + finish_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &BTreeMap::new(), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + None, + ) + .await + .unwrap(); + let product = compact(&mut dataset).await; + let plan = plan(&dataset).await; + assert!(plan.dirty.contains(&product), "{plan:?}"); + assert!(!plan.row_dirty.contains_key(&product), "{plan:?}"); + } + /// Strip the refresh's own keys: a column from before signatures existed. async fn make_legacy(dataset: &mut Dataset) { let declaration = dataset @@ -1255,6 +2736,19 @@ mod tests { field_meta(dataset, column, SOURCE_SIGNATURE_META_KEY).unwrap() } + async fn corrupt_current_sidecar(dataset: &Dataset) { + let digest = signature_ref(dataset, COLUMN) + .strip_prefix(SIDECAR_REF) + .unwrap() + .to_string(); + store(dataset) + .await + .unwrap() + .put(&sidecar_path(dataset, &digest).unwrap(), b"CSIG garbage") + .await + .unwrap(); + } + /// The manifest carries only a digest; the map itself is a sidecar the /// reader fetches and verifies. The declaration's empty seed stays inline. #[tokio::test] @@ -1399,7 +2893,15 @@ mod tests { let mut dataset = table(dir.path().to_str().unwrap()).await; let ids = inputs(&dataset); let entries = signatures_for(&dataset, &[0, 1], &ids).unwrap(); - let reference = write_sidecar(&dataset, &entries).await.unwrap(); + let reference = write_sidecar( + &dataset, + &FreshnessState { + signatures: entries, + ..Default::default() + }, + ) + .await + .unwrap(); let removed = prune_sidecars(&dataset, false).await.unwrap(); assert_eq!(removed, 0); @@ -1414,9 +2916,15 @@ mod tests { StoredSignatures::Present(_) )); - let orphan = write_sidecar(&dataset, &SignatureMap::from([(9, "0".repeat(16))])) - .await - .unwrap(); + let orphan = write_sidecar( + &dataset, + &FreshnessState { + signatures: SignatureMap::from([(9, "0".repeat(16))]), + ..Default::default() + }, + ) + .await + .unwrap(); assert_eq!( prune_sidecars(&dataset, false).await.unwrap(), 0, diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 9e1869376..f6063e8ca 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -2603,7 +2603,7 @@ mod lsm_tests { } fn insert_batches( &self, - batches: &[lance::dataset::mem_wal::write::StoredBatch], + batches: &[lance::dataset::mem_wal::memtable::batch_store::StoredBatch], ) -> lance_core::Result<()> { self.0.insert_batches(batches) } diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index 657385762..ab34e05c6 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -184,6 +184,53 @@ async fn validate_sq_index_remapping( Ok(plan) } +/// Optional compaction tuning. Remote tables inherit omitted values from table +/// policy, then deployment/built-in defaults. Explicit values, including a zero +/// I/O budget, take precedence. Local tables use Lance defaults for omissions. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CompactionOverrides { + pub target_rows_per_fragment: Option, + pub max_source_rows: Option, + /// Read-ahead budget in bytes; zero disables byte-based I/O backpressure. + pub io_buffer_size: Option, + pub batch_size: Option, +} + +impl CompactionOverrides { + pub(crate) fn into_options(self) -> CompactionOptions { + let mut options = CompactionOptions::default(); + if let Some(target) = self.target_rows_per_fragment { + options.target_rows_per_fragment = target; + } + options.max_source_rows = self.max_source_rows; + options.io_buffer_size = self.io_buffer_size; + options.batch_size = self.batch_size; + options + } +} + +impl TryFrom for CompactionOverrides { + type Error = Error; + + fn try_from(options: CompactionOptions) -> Result { + let mut remaining = options.clone(); + let defaults = CompactionOptions::default(); + remaining.target_rows_per_fragment = defaults.target_rows_per_fragment; + remaining.max_source_rows = defaults.max_source_rows; + remaining.io_buffer_size = defaults.io_buffer_size; + remaining.batch_size = defaults.batch_size; + if remaining != defaults { + return Err(Error::NotSupported { message: "remote CompactionOptions support only target_rows_per_fragment, max_source_rows, io_buffer_size, and batch_size; other options must retain their defaults".into() }); + } + Ok(Self { + target_rows_per_fragment: Some(options.target_rows_per_fragment), + max_source_rows: options.max_source_rows, + io_buffer_size: options.io_buffer_size, + batch_size: options.batch_size, + }) + } +} + /// Optimize the dataset. /// /// Similar to `VACUUM` in PostgreSQL, it offers different options to @@ -206,6 +253,55 @@ pub enum OptimizeAction { /// new files. If these operations are run frequently then compaction should run frequently. /// /// If these operations are never run (search only) then compaction is not necessary. + /// + /// # LanceDB Enterprise (remote tables) + /// + /// A remote table supports per-job `target_rows_per_fragment`, + /// `max_source_rows`, `io_buffer_size`, and `batch_size`. Other non-default + /// options and custom `remap_options` return [`crate::Error::NotSupported`] + /// before submission. The server must support these SQL options; errors + /// from older servers are returned without dropping the settings. + /// The source-row budget admits whole tasks and may perform no work when + /// the first task exceeds it. Zero I/O buffer size disables byte-based I/O + /// backpressure. Use a positive size to limit I/O read-ahead; this is not a + /// total-memory limit. Row targets, source-row budgets, and batch sizes must + /// be positive. + /// The legacy Lance options type cannot distinguish an omitted fragment target + /// from its default value; that default is treated as unspecified remotely. + /// Use [`crate::Table::compact`] with [`CompactionOverrides`] to explicitly + /// override a table target with the Lance default value. + /// Omitted options inherit table tuning, then deployment/built-in defaults; options + /// affect only this job, without changing ongoing table policy. + /// + /// It submits a durable + /// compaction job to the server over SQL and waits for that submission to + /// be confirmed, not for compaction itself to finish: the job then runs + /// asynchronously on the server, so this call can return well before the + /// data is actually compacted. Because of that, the returned + /// [`OptimizeStats::compaction`] is a zeroed [`CompactionMetrics`] + /// placeholder rather than the real counts a local table reports. + /// + /// ``` + /// use lancedb::{Table, table::{CompactionOptions, OptimizeAction}}; + /// # async fn compact(table: &Table) -> lancedb::Result<()> { + /// table.optimize(OptimizeAction::Compact { + /// options: CompactionOptions { + /// target_rows_per_fragment: 100_000, + /// max_source_rows: Some(1_000_000), + /// io_buffer_size: Some(64 * 1024 * 1024), + /// batch_size: Some(1024), + /// ..Default::default() + /// }, + /// remap_options: None, + /// }).await?; + /// # Ok(()) + /// # } + /// ``` + /// + /// A branch-scoped table handle compacts that branch. 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. Compact { options: CompactionOptions, remap_options: Option>, @@ -430,19 +526,27 @@ pub(crate) async fn execute_optimize( #[cfg(test)] mod tests { use super::{oversized_sq_partition, segment_touches_fragments, sq_vector_dimension}; + use arrow::compute::concat_batches; use arrow_array::{ Array, FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray, + cast::AsArray, + types::{Float32Type, Int32Type}, }; use arrow_schema::{DataType, Field, Schema}; + use lance::index::DatasetIndexExt; use lance_arrow::FixedSizeListArrayExt; + use lance_index::frag_reuse::FRAG_REUSE_INDEX_NAME; use rstest::rstest; use std::{collections::HashSet, sync::Arc}; use crate::connect; use crate::database::listing::OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS; - use crate::index::vector::IvfRqIndexBuilder; - use crate::index::{Index, scalar::BTreeIndexBuilder}; - use crate::query::ExecutableQuery; + use crate::index::{ + Index, + scalar::BTreeIndexBuilder, + vector::{IvfHnswSqIndexBuilder, IvfRqIndexBuilder}, + }; + use crate::query::{ExecutableQuery, QueryBase}; use crate::table::{CompactionOptions, OptimizeAction, OptimizeStats}; use futures::TryStreamExt; @@ -691,6 +795,68 @@ mod tests { assert_eq!(all_values, expected); } + #[tokio::test] + async fn test_parallel_compaction_reserves_fragment_ids_once() { + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from_iter_values(0..10))]) + .unwrap(); + + let table = conn + .create_table("test_parallel_compaction", batch.clone()) + .execute() + .await + .unwrap(); + + // Create 64 fragments. With a 20-row target, compaction plans 32 tasks, + // which is more than the commit retry limit that used to be exhausted + // when each parallel task reserved fragment IDs independently. + for _ in 1..64 { + table.add(batch.clone()).execute().await.unwrap(); + } + + // Legacy row IDs require fragment IDs before an index can be remapped. + assert!( + !table + .as_native() + .unwrap() + .manifest() + .await + .unwrap() + .uses_stable_row_ids() + ); + table + .create_index(&["i"], Index::BTree(BTreeIndexBuilder::default())) + .execute() + .await + .unwrap(); + + let version_before = table.version().await.unwrap(); + let stats = table + .optimize(OptimizeAction::Compact { + options: CompactionOptions { + target_rows_per_fragment: 20, + num_threads: Some(64), + ..Default::default() + }, + remap_options: None, + }) + .await + .unwrap() + .compaction + .unwrap(); + + assert_eq!(stats.fragments_removed, 64); + assert_eq!(stats.fragments_added, 32); + assert_eq!(table.count_rows(None).await.unwrap(), 640); + assert_eq!( + table.version().await.unwrap(), + version_before + 2, + "parallel compaction should use one fragment reservation commit and one rewrite commit" + ); + } + #[tokio::test] async fn test_compact_with_concurrent_add() { const NUM_FRAGMENTS: usize = 5; @@ -1116,6 +1282,60 @@ mod tests { assert_eq!(all_values, expected); } + #[tokio::test] + async fn test_optimize_all_with_hnsw_index() { + let conn = connect("memory://").execute().await.unwrap(); + + let dimension = 8; + let item_field = Arc::new(Field::new("item", DataType::Float32, true)); + let schema = Arc::new(Schema::new(vec![Field::new( + "vector", + DataType::FixedSizeList(item_field.clone(), dimension), + false, + )])); + + let make_batch = |offset: usize| { + let values = Float32Array::from_iter_values( + (offset * dimension as usize..(offset + 128) * dimension as usize) + .map(|value| value as f32), + ); + let vectors = + FixedSizeListArray::try_new(item_field.clone(), dimension, Arc::new(values), None) + .unwrap(); + RecordBatch::try_new(schema.clone(), vec![Arc::new(vectors)]).unwrap() + }; + + let table = conn + .create_table("test_hnsw_optimize", make_batch(0)) + .execute() + .await + .unwrap(); + for offset in [128, 256, 384] { + table.add(make_batch(offset)).execute().await.unwrap(); + } + + table + .create_index( + &["vector"], + Index::IvfHnswSq(IvfHnswSqIndexBuilder::default()), + ) + .execute() + .await + .unwrap(); + + let stats = table.optimize(OptimizeAction::All).await.unwrap(); + assert!(stats.compaction.unwrap().fragments_removed > 0); + + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + assert_eq!(indices[0].index_type, crate::index::IndexType::IvfHnswSq); + + let index_stats = table.index_stats(&indices[0].name).await.unwrap().unwrap(); + assert_eq!(index_stats.num_indexed_rows, 512); + assert_eq!(index_stats.num_unindexed_rows, 0); + assert_eq!(table.count_rows(None).await.unwrap(), 512); + } + #[tokio::test] async fn test_optimize_default_action() { // Verify that default action is All @@ -1204,6 +1424,138 @@ mod tests { assert_eq!(all_values, expected); } + #[tokio::test] + async fn test_refined_rq_query_after_deferred_compaction() { + const ROWS: i32 = 128; + const DIMENSION: i32 = 32; + let conn = connect("memory://").execute().await.unwrap(); + let vectors = FixedSizeListArray::try_new_from_values( + Float32Array::from_iter_values((0..ROWS).flat_map(|id| { + (0..DIMENSION).map(move |offset| (id as f32 * 0.1 + offset as f32 * 0.3).sin()) + })), + DIMENSION, + ) + .unwrap(); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("vector", vectors.data_type().clone(), false), + ])), + vec![ + Arc::new(Int32Array::from_iter_values(0..ROWS)), + Arc::new(vectors), + ], + ) + .unwrap(); + let table = conn + .create_table("refined_rq_compaction", batch.slice(0, 64)) + .storage_option(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, "false") + .execute() + .await + .unwrap(); + table.add(batch.slice(64, 64)).execute().await.unwrap(); + table + .create_index( + &["vector"], + Index::IvfRq( + IvfRqIndexBuilder::default() + .num_partitions(4) + .num_bits(7) + .max_iterations(5), + ), + ) + .name("rq".to_string()) + .execute() + .await + .unwrap(); + table.delete("id % 7 = 0").await.unwrap(); + let dataset = table.dataset().unwrap().get().await.unwrap(); + assert_eq!(dataset.fragments().len(), 2); + let original_index = dataset.load_indices_by_name("rq").await.unwrap()[0].uuid; + + let key = (0..DIMENSION) + .map(|offset| (0.5 + offset as f32 * 0.3).sin()) + .collect::>(); + let query = || { + table + .query() + .only_if("id % 3 != 0") + .nearest_to(key.as_slice()) + .unwrap() + .nprobes(4) + .unwrap() + .limit(8) + }; + let before = query() + .fast_search() + .refine_factor(4) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let before = concat_batches(&before[0].schema(), &before).unwrap(); + + let stats = table + .optimize(OptimizeAction::Compact { + options: CompactionOptions { + target_rows_per_fragment: 256, + defer_index_remap: true, + ..Default::default() + }, + remap_options: None, + }) + .await + .unwrap(); + assert_eq!(stats.compaction.unwrap().fragments_removed, 2); + let dataset = table.dataset().unwrap().get().await.unwrap(); + assert_eq!(dataset.fragments().len(), 1); + assert_eq!( + dataset.load_indices_by_name("rq").await.unwrap()[0].uuid, + original_index + ); + assert!( + dataset + .load_indices() + .await + .unwrap() + .iter() + .any(|index| index.name == FRAG_REUSE_INDEX_NAME) + ); + + let refined = query().fast_search().refine_factor(4); + let plan = refined.explain_plan(false).await.unwrap(); + assert!(plan.contains("ANNIvf"), "{plan}"); + let after = refined + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let after = concat_batches(&after[0].schema(), &after).unwrap(); + assert_eq!(after.num_rows(), 8); + assert_eq!(after["id"].as_ref(), before["id"].as_ref()); + assert_eq!(after["_distance"].as_ref(), before["_distance"].as_ref()); + let found = after["id"].as_primitive::().values(); + assert!(found.iter().all(|id| id % 7 != 0 && id % 3 != 0)); + assert!(after["_distance"].as_primitive::().values()[0] < 1e-5); + + let exact = query() + .bypass_vector_index() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let exact = concat_batches(&exact[0].schema(), &exact).unwrap(); + let truth = exact["id"].as_primitive::().values(); + let recall = found.iter().filter(|id| truth.contains(id)).count() as f64 / 8.0; + assert!(recall >= 0.5, "recall={recall}"); + } + #[tokio::test] async fn test_compaction_preserves_schema() { let conn = connect("memory://").execute().await.unwrap(); diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 2f5c75766..e9bcd380d 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -121,7 +121,7 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool { // The namespace QueryTable request cannot represent approx_mode, search_effort or use_rte. // For use_rte that is worse than a tuning miss: RTE read routing lives only // in `create_plan`, so a pushed-down query would return stale base-only data. - if query.base().use_rte.is_some() || query.base().take_offsets.is_some() { + if query.base().use_rte.is_some() || query.base().has_take() { return true; } matches!( @@ -164,10 +164,9 @@ pub async fn create_plan( ) -> Result> { let query = query.canonicalized()?; if let AnyQuery::Query(request) = &query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - return crate::query::create_take_offsets_plan(table, request, offsets, options, false) - .await; + return crate::query::create_take_plan(table, request, options, false).await; } let query = match query { @@ -460,6 +459,7 @@ fn enrich_lance_field_not_found( let Some(field) = find_missing_field(&error) else { return error.into(); }; + log::info!("Query field rejected: {error}"); field_not_found_error(field, &Schema::from(schema)) } @@ -480,7 +480,14 @@ fn field_not_found_error(field: &Column, schema: &Schema) -> Error { } message.push('.'); - Error::InvalidInput { message } + Error::FieldNotFound { + name: field.name.clone(), + message, + source: Box::new(lance::Error::field_not_found( + field.name.clone(), + valid_fields, + )), + } } fn find_missing_field<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a Column> { @@ -1603,6 +1610,13 @@ mod tests { Box::new(None), ); let error = field_not_found_diagnostic(&source, &schema).unwrap(); + assert!(matches!(&error, Error::FieldNotFound { name, .. } if name == "missing")); + assert!(matches!( + std::error::Error::source(&error) + .unwrap() + .downcast_ref::(), + Some(lance::Error::FieldNotFound { .. }) + )); assert!( error.to_string().contains( "Valid fields are `a`.`b`.`c`.`d`.`e`, `metadata`.`child.with.dot`, `metadata`.`Title`, `metadata`.`123child`, `metadata`.`child``tick`" diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index d348a6668..400df6c82 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -161,6 +161,19 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { if !query.query_vector.is_empty() && query.base.full_text_search.is_some() { return unsupported("hybrid (vector + full-text) search"); } + // Take lookups add with_row_id internally to restore requested order. Report + // the unsupported take before that implementation detail. Neither _rowid nor + // _rowoffset is exposed by the LSM scanner, which only exposes _rowaddr. + if let Some(QueryFilter::Datafusion(expr)) = &query.base.filter + && expr + .column_refs() + .iter() + .any(|c| c.name == "_rowid" || c.name == "_rowoffset") + { + return unsupported( + "take by row id or row offset (the LSM scanner has no stable _rowid / _rowoffset)", + ); + } if query.base.with_row_id { return unsupported("with_row_id (the LSM scanner exposes _rowaddr, not a stable _rowid)"); } @@ -204,19 +217,6 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { if let Some(QueryFilter::Substrait(_)) = &query.base.filter { return unsupported("Substrait filters"); } - // Take-by-row-id / row-offset queries carry a `_rowid` / `_rowoffset` filter, - // columns the LSM scanner never exposes (only `_rowaddr`); reject with guidance - // rather than failing deep in datafusion with a column-not-found error. - if let Some(QueryFilter::Datafusion(expr)) = &query.base.filter - && expr - .column_refs() - .iter() - .any(|c| c.name == "_rowid" || c.name == "_rowoffset") - { - return unsupported( - "take by row id or row offset (the LSM scanner has no stable _rowid / _rowoffset)", - ); - } Ok(()) } diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index c896d6427..6191c60db 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -51,9 +51,220 @@ use serde::{Deserialize, Serialize}; use super::computed_columns::{BoundExpression, ComputedColumnKind, computed_column_from_field}; use super::freshness::{self, SignatureMap, StalenessPlan}; use super::{BaseTable, NativeTable}; +use crate::function::validate_gpu_class_name; use crate::job::Job; use crate::{Error, Result}; +/// Options for refreshing a computed column. +/// +/// Serializes to the Enterprise backfill request body, one key per set +/// option; the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form takes the +/// same names. +#[derive(Debug, Clone, Default, Serialize)] +#[non_exhaustive] +pub struct RefreshColumnOptions { + /// Only refresh the rows matching this SQL filter. Enterprise only. + #[serde(rename = "where", skip_serializing_if = "Option::is_none")] + pub where_clause: Option, + /// Override the Function's default user-code retry policy. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_policy: Option, + /// Action after user-code failure or retry exhaustion. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub error_policy: Option, + /// Under a skip policy, fail the job once more than this share of rows + /// has failed, 0 to 1. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_failed_fraction: Option, + /// Under a skip policy, fail the job once more than this many rows have + /// failed. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_failed_rows: Option, + /// Deadline for one Function call, in seconds. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub row_timeout_seconds: Option, + /// Deadline for Function initialization, in seconds. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub init_timeout_seconds: Option, + /// Worker count for an expression column in LanceDB Enterprise; + /// registered Function columns reject it. + #[serde(skip_serializing_if = "Option::is_none")] + pub num_workers: Option, + /// At most this many executor processes per Function worker. Enterprise + /// only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_executor_processes_per_worker: Option, + /// Maximum rows per Function call in LanceDB Enterprise. + /// + /// Must be greater than zero. `None` uses the server default. This has no + /// effect on expression-backed columns in LanceDB Embedded. + #[serde(skip_serializing_if = "Option::is_none")] + pub batch_size: Option, + /// GPU class for Function workers in LanceDB Enterprise. + /// + /// `None` keeps the Function's registered class, or the deployment default + /// when the Function does not declare one. + #[serde(skip_serializing_if = "Option::is_none")] + pub gpu_class: Option, + /// Positive aggregate GPU budget for Function workers in LanceDB + /// Enterprise. + /// + /// `None` leaves the server's configured budget unchanged. + #[serde(skip_serializing_if = "Option::is_none")] + pub gpu_count: Option, +} + +impl RefreshColumnOptions { + /// Only refresh the rows matching `filter`. + pub fn where_clause(mut self, filter: impl Into) -> Self { + self.where_clause = Some(filter.into()); + self + } + + /// Fail the job once more than `fraction` of its rows has failed. + pub fn max_failed_fraction(mut self, fraction: f64) -> Self { + self.max_failed_fraction = Some(fraction); + self + } + + /// Fail the job once more than `rows` rows have failed. + pub fn max_failed_rows(mut self, rows: u64) -> Self { + self.max_failed_rows = Some(rows); + self + } + + /// Give each Function call at most `seconds` to return. + pub fn row_timeout_seconds(mut self, seconds: f64) -> Self { + self.row_timeout_seconds = Some(seconds); + self + } + + /// Give Function initialization at most `seconds` to complete. + pub fn init_timeout_seconds(mut self, seconds: f64) -> Self { + self.init_timeout_seconds = Some(seconds); + self + } + + /// Request `num_workers` workers for an expression column refresh. + pub fn num_workers(mut self, num_workers: usize) -> Self { + self.num_workers = Some(num_workers); + self + } + + /// Cap executor processes per Function worker at `processes`. + pub fn max_executor_processes_per_worker(mut self, processes: u32) -> Self { + self.max_executor_processes_per_worker = Some(processes); + self + } + + /// Override retries of failed Function calls for this refresh. + pub fn retry_policy(mut self, policy: crate::function::FunctionRetryPolicy) -> Self { + self.retry_policy = Some(policy); + self + } + + /// Select fail or skip after the retry policy is exhausted. + pub fn error_policy(mut self, policy: crate::function::FunctionErrorPolicy) -> Self { + self.error_policy = Some(policy); + self + } + /// Limit each Function call to at most `batch_size` rows. + pub fn batch_size(mut self, batch_size: usize) -> Self { + self.batch_size = Some(batch_size); + self + } + + /// Request Function workers from `gpu_class`. + pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { + self.gpu_class = Some(gpu_class.into()); + self + } + + /// Request an aggregate GPU budget of `gpu_count`. + pub fn gpu_count(mut self, gpu_count: u32) -> Self { + self.gpu_count = Some(gpu_count); + self + } + + /// The first set option a LanceDB Embedded refresh cannot honor, if any. + pub fn enterprise_only_option(&self) -> Option<&'static str> { + [ + ("where", self.where_clause.is_some()), + ("retry_policy", self.retry_policy.is_some()), + ("error_policy", self.error_policy.is_some()), + ("max_failed_fraction", self.max_failed_fraction.is_some()), + ("max_failed_rows", self.max_failed_rows.is_some()), + ("row_timeout_seconds", self.row_timeout_seconds.is_some()), + ("init_timeout_seconds", self.init_timeout_seconds.is_some()), + ("num_workers", self.num_workers.is_some()), + ( + "max_executor_processes_per_worker", + self.max_executor_processes_per_worker.is_some(), + ), + ] + .into_iter() + .find_map(|(name, set)| set.then_some(name)) + } + + /// Validate client-side constraints before any request is sent. + pub fn validate(&self) -> Result<()> { + if self + .where_clause + .as_deref() + .is_some_and(|f| f.trim().is_empty()) + { + return Err(Error::InvalidInput { + message: "where must not be empty".into(), + }); + } + if let Some(policy) = &self.retry_policy { + policy.validate()?; + } + if self + .max_failed_fraction + .is_some_and(|f| !f.is_finite() || !(0.0..=1.0).contains(&f)) + { + return Err(Error::InvalidInput { + message: "max_failed_fraction must be a finite number between 0 and 1".into(), + }); + } + for (name, seconds) in [ + ("row_timeout_seconds", self.row_timeout_seconds), + ("init_timeout_seconds", self.init_timeout_seconds), + ] { + if seconds.is_some_and(|s| !s.is_finite() || s <= 0.0) { + return Err(Error::InvalidInput { + message: format!("{name} must be a positive finite number"), + }); + } + } + if self.num_workers == Some(0) { + return Err(Error::InvalidInput { + message: "num_workers must be greater than zero".into(), + }); + } + if self.max_executor_processes_per_worker == Some(0) { + return Err(Error::InvalidInput { + message: "max_executor_processes_per_worker must be greater than zero".into(), + }); + } + if self.batch_size == Some(0) { + return Err(Error::InvalidInput { + message: "batch_size must be greater than zero".into(), + }); + } + if let Some(gpu_class) = &self.gpu_class { + validate_gpu_class_name(gpu_class)?; + } + if self.gpu_count == Some(0) { + return Err(Error::InvalidInput { + message: "gpu_count must be greater than zero".into(), + }); + } + Ok(()) + } +} + /// The result of refreshing a computed column. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] pub struct RefreshColumnResult { @@ -132,7 +343,9 @@ async fn execute_refresh_column_with_source( // A recompute rewrites every live row, so it is staged without the // probe and counted as it fills; a null fill probes first, since a // fragment with nothing to gain is not worth a write. - let recompute = staleness.is_dirty(fragment_id); + // Expression refreshes replace a whole column file, so any row-level + // dirty state makes this fragment a whole-fragment recompute here. + let recompute = staleness.needs_recompute(fragment_id); let whole = recompute || { let (gained, unfilled) = count_fragment_gains(&dataset, &fragment, &bound, column).await?; @@ -368,7 +581,7 @@ fn declared_expression(dataset: &Dataset, column: &str) -> Result { match declaration.kind { ComputedColumnKind::Sql { expression } => Ok(expression), ComputedColumnKind::Function { .. } => Err(Error::NotSupported { - message: "registered Function columns are refreshed only by a LanceDB Distributed job" + message: "registered Function columns are refreshed only by a LanceDB Enterprise job" .into(), }), ComputedColumnKind::Unrecognized { kind } => Err(Error::NotSupported { diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index d78fc5102..db4d6b91f 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -8,7 +8,7 @@ //! - [`alter_columns`](execute_alter_columns): Rename columns, change types, or modify nullability //! - [`drop_columns`](execute_drop_columns): Remove columns from the table -use arrow_schema::Schema as ArrowSchema; +use arrow_schema::{Schema as ArrowSchema, SchemaRef}; use lance::dataset::transaction::{Operation, Transaction, UpdateMap, UpdateMapEntry}; use lance::dataset::{ColumnAlteration, CommitBuilder, Dataset, NewColumnTransform}; use serde::{Deserialize, Serialize}; @@ -16,7 +16,7 @@ use std::collections::HashMap; use std::sync::Arc; use super::computed_columns; -use super::{BaseTable, NativeTable}; +use super::{BaseTable, ColumnKind, NativeTable, TableDefinition}; use crate::{Error, Result}; /// The result of an add columns operation. @@ -119,6 +119,12 @@ pub(crate) async fn execute_add_columns( NewColumnTransform::BatchUDF(udf) => { computed_columns::ensure_no_foreign_declarations(udf.output_schema.fields())? } + NewColumnTransform::Reader(reader) => { + computed_columns::ensure_no_foreign_declarations(reader.schema().fields())? + } + NewColumnTransform::Stream(stream) => { + computed_columns::ensure_no_foreign_declarations(stream.schema().fields())? + } _ => {} } commit_add_columns(table, transforms, read_columns).await @@ -201,6 +207,63 @@ pub(crate) async fn commit_add_columns( Ok(AddColumnsResult { version }) } +/// Native and SDK embedding configurations refer to top-level columns by name. +/// Lance's schema evolution preserves this metadata, so reject operations that +/// would leave those names dangling without loading an embedding function. +fn ensure_not_embedding_column<'a>( + schema: &SchemaRef, + operation: &str, + paths: impl IntoIterator, +) -> Result<()> { + #[derive(Deserialize)] + struct EmbeddingColumns { + #[serde(alias = "sourceColumn")] + source_column: String, + #[serde(alias = "vectorColumn", alias = "dest_column", alias = "destColumn")] + vector_column: String, + } + let mut embeddings: Vec = match schema.metadata.get("embedding_functions") { + Some(raw) => serde_json::from_str(raw).map_err(|error| Error::InvalidInput { + message: format!("Invalid embedding_functions metadata: {error}"), + })?, + None => Vec::new(), + }; + let definition = TableDefinition::try_from_rich_schema(schema.clone())?; + embeddings.extend( + definition + .column_definitions + .into_iter() + .filter_map(|column| { + let ColumnKind::Embedding(embedding) = column.kind else { + return None; + }; + let vector_column = embedding + .dest_column + .unwrap_or_else(|| format!("{}_embedding", embedding.source_column)); + Some(EmbeddingColumns { + source_column: embedding.source_column, + vector_column, + }) + }), + ); + for path in paths { + // Use Lance's path grammar so quoting or a nested path cannot bypass + // the check. Altering a child also changes the embedding's input. + let column = computed_columns::field_root(path)?; + if embeddings + .iter() + .any(|embedding| embedding.source_column == column || embedding.vector_column == column) + { + return Err(Error::InvalidInput { + message: format!( + "Cannot {operation} column '{path}' because it is used by an embedding function" + ), + }); + } + } + Ok(()) +} + /// Internal implementation of the alter columns logic. /// /// Alters existing columns in the table (rename, change type, or modify nullability). @@ -229,6 +292,14 @@ pub(crate) async fn execute_alter_columns( std::iter::once(alteration.path.as_str()).chain(alteration.rename.as_deref()) }), )?; + ensure_not_embedding_column( + &schema, + "rename", + alterations + .iter() + .filter(|alteration| alteration.rename.is_some()) + .map(|alteration| alteration.path.as_str()), + )?; // Nullability is not part of what an expression resolves against, so only // a rename or a retype can invalidate a binding. let rebinding = alterations @@ -271,6 +342,7 @@ pub(crate) async fn execute_drop_columns( let mut names = columns.iter().map(|c| c.to_string()).collect::>(); names.extend(unbinding.assignment_columns.iter().cloned()); let dropped = names.iter().map(String::as_str).collect::>(); + ensure_not_embedding_column(&schema, "drop", dropped.iter().copied())?; computed_columns::ensure_not_bound_by(&unbinding.retained, "schema evolution", &dropped)?; computed_columns::ensure_not_an_input_of(&schema, &dropped, &dropped)?; @@ -783,6 +855,85 @@ mod tests { // Alter Columns Tests + #[rstest::rstest] + #[case("source_column", "vector_column", "text")] + #[case("sourceColumn", "vectorColumn", "text")] + #[case("source_column", "vector_column", "text with space")] + #[tokio::test] + async fn test_schema_evolution_preserves_embedding_bindings( + #[case] source_key: &str, + #[case] vector_key: &str, + #[case] source_column: &str, + ) { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!( + ("id", Int32, [1]), + (source_column, Utf8, ["hello"]), + ("vector", Int32, [1]) + ) + .unwrap(); + let metadata = serde_json::json!([{ + "name": "test", + (source_key): source_column, + (vector_key): "vector", + "model": {}, + }]); + let schema = batch + .schema() + .as_ref() + .clone() + .with_metadata(HashMap::from([( + "embedding_functions".to_string(), + metadata.to_string(), + )])); + let batch = batch.with_schema(std::sync::Arc::new(schema)).unwrap(); + let table = conn + .create_table("test", batch.clone()) + .execute() + .await + .unwrap(); + let schema = table.schema().await.unwrap(); + let version = table.version().await.unwrap(); + + for path in [format!("`{source_column}`"), "vector".to_string()] { + let err = table + .alter_columns(&[ + ColumnAlteration::new("id".into()).rename("new_id".into()), + ColumnAlteration::new(path.clone()).rename("renamed".into()), + ]) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. }), "got {err:?}"); + assert!(err.to_string().contains("used by an embedding function")); + + let err = table.drop_columns(&["id", &path]).await.unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. }), "got {err:?}"); + assert!(err.to_string().contains("used by an embedding function")); + assert_eq!(table.schema().await.unwrap(), schema); + assert_eq!(table.version().await.unwrap(), version); + } + + let reopened = conn.open_table("test").execute().await.unwrap(); + assert_eq!(reopened.schema().await.unwrap(), schema); + reopened.add(batch).execute().await.unwrap(); + assert_eq!(reopened.count_rows(None).await.unwrap(), 2); + + // Nullability and operations on unrelated columns remain supported. + reopened + .alter_columns(&[ColumnAlteration::new("vector".into()).set_nullable(true)]) + .await + .unwrap(); + reopened + .alter_columns(&[ColumnAlteration::new("id".into()).rename("new_id".into())]) + .await + .unwrap(); + reopened.drop_columns(&["new_id"]).await.unwrap(); + assert_eq!( + reopened.schema().await.unwrap().metadata(), + schema.metadata() + ); + } + #[tokio::test] async fn test_alter_columns_rejects_missing_changes() { let conn = connect("memory://").execute().await.unwrap(); diff --git a/rust/lancedb/src/utils/mod.rs b/rust/lancedb/src/utils/mod.rs index ebf3f697b..eedff924d 100644 --- a/rust/lancedb/src/utils/mod.rs +++ b/rust/lancedb/src/utils/mod.rs @@ -38,6 +38,9 @@ const MAX_SECRET_NAME_CHARS: usize = 128; /// The maximum length of a function name. const MAX_FUNCTION_NAME_CHARS: usize = 128; +/// The maximum length of a property graph name. +const MAX_PROPERTY_GRAPH_NAME_CHARS: usize = 128; + /// The maximum length of a database name. const MAX_DB_NAME_CHARS: usize = 64; @@ -125,7 +128,7 @@ pub fn validate_table_name(name: &str) -> Result<()> { { return Err(Error::InvalidTableName { name: sanitize(name), - reason: "Only alphanumeric characters, dashes, underscores, and\ + reason: "Only alphanumeric characters, dashes, underscores, and \ periods are allowed in table names." .to_string(), }); @@ -214,6 +217,18 @@ pub fn validate_view_reference(name: &str, namespace_path: &[String]) -> Result< validate_view_name(name) } +/// Validate a property graph name. +pub fn validate_property_graph_name(name: &str) -> Result<()> { + validate_view_or_namespace_or_secret(name, "property graph name", MAX_PROPERTY_GRAPH_NAME_CHARS) +} + +/// Validate a property graph name and every segment of the namespace path +/// holding it. +pub fn validate_property_graph_reference(name: &str, namespace_path: &[String]) -> Result<()> { + validate_namespace(namespace_path)?; + validate_property_graph_name(name) +} + /// Validate a function name. These do not allow dashes or periods. pub fn validate_function_name(name: &str) -> Result<()> { if name.is_empty() { @@ -665,6 +680,22 @@ impl TimeoutStream { Box::pin(Self::new(inner, timeout)) } + /// Like [`Self::new`], but the stream expires at `deadline` rather than + /// `timeout` after its first poll. `timeout` is only used in the error. + pub fn with_deadline( + inner: SendableRecordBatchStream, + timeout: std::time::Duration, + deadline: tokio::time::Instant, + ) -> Self { + Self { + inner, + state: TimeoutState::Started { + deadline: Box::pin(tokio::time::sleep_until(deadline)), + timeout, + }, + } + } + fn timeout_error(timeout: &std::time::Duration) -> DataFusionError { DataFusionError::Execution(format!("Query timeout after {} ms", timeout.as_millis())) } @@ -1052,6 +1083,15 @@ mod tests { assert!(validate_table_name("name with space").is_err()); } + #[test] + fn test_validate_table_name_invalid_character_message() { + let err = validate_table_name("my/table").unwrap_err().to_string(); + assert!( + err.contains("underscores, and periods are allowed"), + "unexpected message: {err}" + ); + } + #[test] fn test_validate_namespace_component() { // Valid namespace names diff --git a/rust/lancedb/tests/duplicate_pairs.rs b/rust/lancedb/tests/duplicate_pairs.rs index 6b602ac4f..ef47102e9 100644 --- a/rust/lancedb/tests/duplicate_pairs.rs +++ b/rust/lancedb/tests/duplicate_pairs.rs @@ -168,7 +168,7 @@ async fn sql_pairs_match_native_snapshot_and_partition_tasks() -> anyhow::Result let ctx = SessionContext::new_with_config_rt(datafusion::prelude::SessionConfig::new(), runtime); ctx.register_udtf( - "vector_duplicate_pairs", + "duplicate_pairs", Arc::new(DuplicatePairsTableFunction::new(resolver.clone())), ); ctx.register_udtf( @@ -192,7 +192,7 @@ async fn sql_pairs_match_native_snapshot_and_partition_tasks() -> anyhow::Result .try_collect::>() .await?; let sql = format!( - "SELECT * FROM vector_duplicate_pairs('source', {version}, 'vector', {threshold})" + "SELECT * FROM duplicate_pairs('source', {version}, 'vector', {threshold})" ); let actual = ctx.sql(&sql).await?.collect().await?; assert_eq!(pairs(&actual), pairs(&expected)); @@ -361,7 +361,7 @@ async fn sql_pairs_match_native_snapshot_and_partition_tasks() -> anyhow::Result table.delete("id = 1").await?; let actual = ctx .sql(&format!( - "SELECT * FROM vector_duplicate_pairs('source', {version}, 'vector', 1.0)" + "SELECT * FROM duplicate_pairs('source', {version}, 'vector', 1.0)" )) .await? .collect() @@ -369,7 +369,7 @@ async fn sql_pairs_match_native_snapshot_and_partition_tasks() -> anyhow::Result assert_eq!(pairs(&actual).len(), 8); assert!( ctx.sql(&format!( - "SELECT * FROM vector_duplicate_pairs('source', {version}, 'missing', 1.0)" + "SELECT * FROM duplicate_pairs('source', {version}, 'missing', 1.0)" )) .await? .collect() diff --git a/rust/lancedb/tests/embedding_registry_test.rs b/rust/lancedb/tests/embedding_registry_test.rs index 8e1a80ec4..e06f5e5b5 100644 --- a/rust/lancedb/tests/embedding_registry_test.rs +++ b/rust/lancedb/tests/embedding_registry_test.rs @@ -14,6 +14,7 @@ use arrow_array::{ }; use arrow_schema::{DataType, Field, Schema}; use futures::StreamExt; +use lance::dataset::ColumnAlteration; use lancedb::{ Error, Result, connect, embeddings::{EmbeddingDefinition, EmbeddingFunction, EmbeddingRegistry}, @@ -194,6 +195,69 @@ async fn test_open_table_embeddings() -> Result<()> { Ok(()) } +#[rstest::rstest] +#[case(Some("embeddings"), "embeddings")] +#[case(None, "text_embedding")] +#[tokio::test] +async fn test_schema_evolution_preserves_native_embeddings( + #[case] dest_column: Option<&str>, + #[case] vector_column: &str, +) -> Result<()> { + let tempdir = tempfile::tempdir().unwrap(); + let uri = tempdir.path().to_str().unwrap(); + let db = connect(uri).execute().await?; + db.embedding_registry() + .register("embed_fun", Arc::new(MockEmbed::new("embed_fun".into(), 2)))?; + let table = db + .create_table("test", create_some_records()?) + .add_embedding(EmbeddingDefinition::new("text", "embed_fun", dest_column))? + .execute() + .await?; + let schema = table.schema().await?; + let version = table.version().await?; + assert!( + schema + .metadata() + .contains_key("lancedb::column_definitions") + ); + assert!(!schema.metadata().contains_key("embedding_functions")); + + // Schema protection must not require the embedding function to be loaded. + let unregistered_db = connect(uri).execute().await?; + let table = unregistered_db.open_table("test").execute().await?; + for column in ["text", vector_column] { + let err = table + .alter_columns(&[ + ColumnAlteration::new("id".into()).rename("new_id".into()), + ColumnAlteration::new(column.into()).rename("renamed".into()), + ]) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. }), "got {err:?}"); + assert!(err.to_string().contains("used by an embedding function")); + assert_eq!(table.schema().await?, schema); + assert_eq!(table.version().await?, version); + + let err = table.drop_columns(&["id", column]).await.unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. }), "got {err:?}"); + assert!(err.to_string().contains("used by an embedding function")); + assert_eq!(table.schema().await?, schema); + assert_eq!(table.version().await?, version); + } + + let table = db.open_table("test").execute().await?; + assert_eq!(table.schema().await?, schema); + table.add(create_some_records()?).execute().await?; + assert_eq!(table.count_rows(None).await?, 4); + + table + .alter_columns(&[ColumnAlteration::new("id".into()).rename("new_id".into())]) + .await?; + table.drop_columns(&["new_id"]).await?; + assert_eq!(table.schema().await?.metadata(), schema.metadata()); + Ok(()) +} + #[tokio::test] async fn test_no_func_in_registry() -> Result<()> { let tempdir = tempfile::tempdir().unwrap(); diff --git a/rust/lancedb/tests/first_class_function_slice1.rs b/rust/lancedb/tests/first_class_function_slice1.rs index 86ccea1cc..878e74bb0 100644 --- a/rust/lancedb/tests/first_class_function_slice1.rs +++ b/rust/lancedb/tests/first_class_function_slice1.rs @@ -182,13 +182,17 @@ fn unknown_fields_and_discriminators_are_forward_decodable() { let version = FunctionVersion::from_json(&result.to_string()).expect("future remote value"); assert_eq!(version.image().descriptor["future_interface"]["version"], 2); assert_eq!(version.signature().output.kind, "future_output_shape"); - assert_eq!( - serde_json::from_str::( - &version.to_canonical_json().expect("canonical future value") - ) - .expect("canonical JSON")["image"]["descriptor"]["future_interface"], - serde_json::json!({"version": 2}) - ); + let canonical: Value = + serde_json::from_str(&version.to_canonical_json().expect("canonical future value")) + .expect("canonical JSON"); + + let mut expected: Value = + serde_json::from_str(fixture("remote_function_version.canonical.json").trim()) + .expect("canonical FunctionVersion fixture"); + expected["image"]["descriptor"]["future_interface"] = serde_json::json!({"version": 2}); + expected["signature"]["output"]["kind"] = Value::String("future_output_shape".to_string()); + assert_eq!(canonical, expected); + assert!(canonical.get("future_version_metadata").is_none()); } #[test] diff --git a/rust/lancedb/tests/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs index 380766e03..fe8fc27c5 100644 --- a/rust/lancedb/tests/first_class_function_slice2.rs +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -58,7 +58,58 @@ fn registration_request_matches_shared_canonical_golden() { assert_no_secret_values(&value); } -/// The same shared golden as the Python suite builds from `@udf(secrets=...)` +#[test] +fn execution_controls_match_shared_canonical_golden() { + let request = FunctionRegistrationRequest::from_json(&fixture( + "remote_function_controlled_registration_request.json", + )) + .expect("controlled registration request"); + assert_eq!( + request.to_canonical_json().expect("canonical request"), + fixture("remote_function_controlled_registration_request.canonical.json").trim() + ); + + let value: Value = serde_json::from_str(&request.to_canonical_json().unwrap()).unwrap(); + assert_eq!(value["batch_size"], 2); + assert_eq!(value["row_timeout_seconds"], 0.75); +} + +#[test] +fn execution_controls_require_their_positive_ranges() { + let source = fixture("remote_function_registration_request.json"); + for (field, value) in [ + ("batch_size", Value::from(0)), + ("batch_size", Value::from(4_294_967_296_u64)), + ("row_timeout_seconds", Value::from(0)), + ("row_timeout_seconds", Value::from(-0.25)), + ] { + let mut request: Value = serde_json::from_str(&source).unwrap(); + request[field] = value; + let error = FunctionRegistrationRequest::from_json(&request.to_string()).unwrap_err(); + assert!( + error.to_string().contains(field), + "{field} validation error was {error}" + ); + } +} + +#[test] +fn execution_controls_are_validated_before_canonical_serialization() { + let source = fixture("remote_function_controlled_registration_request.json"); + for timeout in [f64::NAN, f64::INFINITY, -0.25] { + let mut request = FunctionRegistrationRequest::from_json(&source).unwrap(); + request.row_timeout_seconds = Some(timeout); + let error = request.to_canonical_json().unwrap_err(); + assert!(error.to_string().contains("row_timeout_seconds"), "{error}"); + } + + let mut request = FunctionRegistrationRequest::from_json(&source).unwrap(); + request.batch_size = Some(0); + let error = request.to_canonical_json().unwrap_err(); + assert!(error.to_string().contains("batch_size"), "{error}"); +} + +/// The same shared golden as the Python suite builds from `@function(secrets=...)` /// plus `bind_secrets`, so both clients agree byte for byte on a bound request. #[test] fn secret_bound_registration_request_matches_shared_canonical_golden() { @@ -113,7 +164,8 @@ async fn local_function_catalog_operations_return_stable_not_supported() { assert!(matches!( error, Error::NotSupported { message } - if message == "Function catalog operations are not supported by this database" + if message.starts_with("Function catalog operations are not supported by this database") + && message.contains("utm_campaign=functions") )); } } diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json new file mode 100644 index 000000000..9ce9a289f --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json @@ -0,0 +1 @@ +{"artifact":{"adapter":{"kind":"scalar_to_arrow_batch","version":1},"content":{"data":"ZnJvbSBfX2Z1dHVyZV9fIGltcG9ydCBhbm5vdGF0aW9ucwoKZGVmIG5vcm1hbGl6ZV9zY29yZSh2YWx1ZTogZmxvYXQpIC0+IGZsb2F0OgogICAgcmV0dXJuIHZhbHVlIC8gMTAwLjAK","encoding":"base64"},"digest":"sha256:760784bdcef57b802f389b97804cc0b618aae39e86044733451bcd0b13089a7f","entrypoint":"normalize_score","kind":"python_callable"},"batch_size":2,"name":"normalize_score","row_timeout_seconds":0.75,"runtime":{"env":{"MODE":"test"},"environment":{"kind":"pip","packages":["numpy>=2"]},"kind":"python","python_version":"3.12"},"signature":{"inputs":[{"arrow_type":"float64","name":"value","nullable":false}],"output":{"arrow_type":"float64","kind":"scalar","nullable":false}}} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json new file mode 100644 index 000000000..cb0961eba --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json @@ -0,0 +1,45 @@ +{ + "name": "normalize_score", + "batch_size": 2, + "row_timeout_seconds": 0.75, + "artifact": { + "kind": "python_callable", + "digest": "sha256:760784bdcef57b802f389b97804cc0b618aae39e86044733451bcd0b13089a7f", + "entrypoint": "normalize_score", + "content": { + "encoding": "base64", + "data": "ZnJvbSBfX2Z1dHVyZV9fIGltcG9ydCBhbm5vdGF0aW9ucwoKZGVmIG5vcm1hbGl6ZV9zY29yZSh2YWx1ZTogZmxvYXQpIC0+IGZsb2F0OgogICAgcmV0dXJuIHZhbHVlIC8gMTAwLjAK" + }, + "adapter": { + "kind": "scalar_to_arrow_batch", + "version": 1 + } + }, + "signature": { + "inputs": [ + { + "name": "value", + "arrow_type": "float64", + "nullable": false + } + ], + "output": { + "kind": "scalar", + "arrow_type": "float64", + "nullable": false + } + }, + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "numpy>=2" + ] + }, + "env": { + "MODE": "test" + } + } +} diff --git a/rust/lancedb/tests/fixtures/storage_integration.json b/rust/lancedb/tests/fixtures/storage_integration.json new file mode 100644 index 000000000..4b131ebe1 --- /dev/null +++ b/rust/lancedb/tests/fixtures/storage_integration.json @@ -0,0 +1,36 @@ +{ + "name": "raw", + "storage_provider": "S3", + "storage_prefix": "s3://customer-bucket/raw/", + "aws_role_arn": "arn:aws:iam::123456789012:role/access", + "aws_region": null, + "aws_account_id": "001122334455", + "aws_iam_principal_arn": "arn:aws:iam::001122334455:role/lancedb-storage-access", + "aws_external_id": "55b54d68-4686-4d38-97da-9d77e54a643e", + "created_at_millis": 1, + "access_verified": false, + "trust_policy": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "sts:AssumeRole", + "sts:TagSession" + ], + "Principal": { + "AWS": "arn:aws:iam::001122334455:role/lancedb-storage-access" + }, + "Condition": { + "StringEquals": { + "sts:ExternalId": "55b54d68-4686-4d38-97da-9d77e54a643e" + } + } + } + ] + }, + "permissions_policy": {}, + "configuration_instructions": "Update IAM role arn:aws:iam::123456789012:role/access to trust arn:aws:iam::001122334455:role/lancedb-storage-access with external ID 55b54d68-4686-4d38-97da-9d77e54a643e and attach the S3 permissions policy for s3://customer-bucket/raw/.", + "database": "default", + "namespace_path": [] +} diff --git a/rust/lancedb/tests/indexed_delete_test.rs b/rust/lancedb/tests/indexed_delete_test.rs new file mode 100644 index 000000000..4ebaf5238 --- /dev/null +++ b/rust/lancedb/tests/indexed_delete_test.rs @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::{ + alloc::{GlobalAlloc, Layout, System}, + cell::Cell, + future::Future, + sync::Arc, +}; + +use arrow_array::{RecordBatch, StringArray}; +use arrow_schema::{DataType, Field, Schema}; +use futures::TryStreamExt; +use lancedb::{ + Table, connect, + index::Index, + query::{ExecutableQuery, QueryBase}, +}; + +struct ThreadCountingAllocator; + +thread_local! { + static COUNT_ALLOCATIONS: Cell = const { Cell::new(false) }; + static ALLOCATED_BYTES: Cell = const { Cell::new(0) }; +} + +unsafe impl GlobalAlloc for ThreadCountingAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let ptr = unsafe { System.alloc(layout) }; + if !ptr.is_null() { + record_allocation(layout.size()); + } + ptr + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + let ptr = unsafe { System.alloc_zeroed(layout) }; + if !ptr.is_null() { + record_allocation(layout.size()); + } + ptr + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) }; + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + let new_ptr = unsafe { System.realloc(ptr, layout, new_size) }; + if !new_ptr.is_null() { + record_allocation(new_size); + } + new_ptr + } +} + +#[global_allocator] +static ALLOCATOR: ThreadCountingAllocator = ThreadCountingAllocator; + +const ROW_COUNT: usize = 262_144; +const VALUE_COUNT: usize = 1_000; + +fn record_allocation(bytes: usize) { + COUNT_ALLOCATIONS.with(|enabled| { + if enabled.get() { + ALLOCATED_BYTES.with(|allocated| allocated.set(allocated.get() + bytes)); + } + }); +} + +async fn measure_allocated_bytes(future: F) -> (F::Output, usize) { + ALLOCATED_BYTES.with(|allocated| allocated.set(0)); + COUNT_ALLOCATIONS.with(|enabled| enabled.set(true)); + let output = future.await; + COUNT_ALLOCATIONS.with(|enabled| enabled.set(false)); + let allocated = ALLOCATED_BYTES.with(Cell::get); + (output, allocated) +} + +fn in_predicate(ids: impl Iterator) -> String { + let values = ids + .map(|id| format!("'id_{id:06}'")) + .collect::>() + .join(","); + format!("id IN ({values})") +} + +async fn create_indexed_table(name: &str) -> Table { + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Utf8, false)])); + let ids = StringArray::from_iter_values((0..ROW_COUNT).map(|id| format!("id_{id:06}"))); + let batch = RecordBatch::try_new(schema, vec![Arc::new(ids)]).unwrap(); + let table = conn.create_table(name, batch).execute().await.unwrap(); + table + .create_index(&["id"], Index::BTree(Default::default())) + .execute() + .await + .unwrap(); + table +} + +async fn warm_index(table: &Table, predicate: &str) { + table + .query() + .only_if(predicate) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); +} + +#[tokio::test(flavor = "current_thread")] +async fn large_in_delete_compiles_predicate_once() { + let clustered = in_predicate(0..VALUE_COUNT); + let spread = in_predicate((0..VALUE_COUNT).map(|id| id * (ROW_COUNT / VALUE_COUNT))); + let clustered_table = create_indexed_table("clustered_ids").await; + let spread_table = create_indexed_table("spread_ids").await; + + let plan = spread_table + .query() + .only_if(&spread) + .explain_plan(false) + .await + .unwrap(); + assert!(plan.contains("ScalarIndexQuery"), "unexpected plan: {plan}"); + + // Remove page-loading noise from the allocation comparison. Predicate + // compilation is deliberately not cached, so each delete still compiles it. + warm_index(&clustered_table, &spread).await; + warm_index(&spread_table, &spread).await; + + let (clustered_result, clustered_bytes) = + measure_allocated_bytes(clustered_table.delete(&clustered)).await; + let (spread_result, spread_bytes) = measure_allocated_bytes(spread_table.delete(&spread)).await; + + assert_eq!( + clustered_result.unwrap().num_deleted_rows, + VALUE_COUNT as u64 + ); + assert_eq!(spread_result.unwrap().num_deleted_rows, VALUE_COUNT as u64); + + // Both predicates contain the same number and size of values. Spreading them + // across BTree pages may add modest page-processing overhead, but it must not + // rematerialize all values per page. This ratio fails by a wide margin if + // Lance's compile-once path is moved back inside the per-page loop. + assert!( + spread_bytes * 2 < clustered_bytes * 3, + "spread delete allocated {spread_bytes} bytes versus {clustered_bytes} for one page" + ); +}