diff --git a/.agents/skills/lancedb-update-lance-dependency/SKILL.md b/.agents/skills/lancedb-update-lance-dependency/SKILL.md index e97fae7ac..3cba2ae75 100644 --- a/.agents/skills/lancedb-update-lance-dependency/SKILL.md +++ b/.agents/skills/lancedb-update-lance-dependency/SKILL.md @@ -48,6 +48,23 @@ Inputs can be a version (`7.2.0-beta.1`), a tag (`v7.2.0-beta.1`), a tag ref (`r This updates the Rust workspace Lance dependencies through `ci/set_lance_version.py`, updates `java/pom.xml`, refreshes Cargo metadata, and prints JSON metadata containing `branch_name`, `commit_message`, and `pr_title`. + Also synchronize the Python requirements in `python/pyproject.toml`: set the + `tests` extra's exact `pylance` pin to the matching published Python release, + and update the `pylance` extra's minimum when needed to exclude older bundled + Lance majors. The minimum must still accept the test pin. Python prerelease + spelling differs from Rust (for example, `15.0.0-beta.1` becomes `15.0.0b1`). + Confirm the matching Python release is published before changing the pin. + + Refresh and check `python/uv.lock` from the repository root: + + ```bash + uv lock --project python --index https://pypi.fury.io/lancedb/ --index https://pypi.fury.io/lance-format/ --index-strategy unsafe-best-match + uv lock --project python --check --index https://pypi.fury.io/lancedb/ --index https://pypi.fury.io/lance-format/ --index-strategy unsafe-best-match + ``` + + This strategy considers versions across indexes; use it only with trusted + indexes. Commit the Python requirements and lockfile together with the bump. + 5. Run validation: ```bash @@ -57,6 +74,16 @@ Inputs can be a version (`7.2.0-beta.1`), a tag (`v7.2.0-beta.1`), a tag ref (`r Fix real diagnostics and rerun clippy until it succeeds. Do not skip warnings. + Run the Python dependency guards with Python 3.11+ and `packaging` installed: + + ```bash + python3 -m unittest discover -s ci/tests -p test_python_dependencies.py -v + ``` + + These checks reject older Lance majors and ensure the `pylance` and `tests` + extras remain compatible. The full CI-script suite uses + `python3 -m unittest discover -s ci/tests -v`. + 6. Inspect `git status --short` and `git diff` to ensure only the Lance dependency update and required compatibility fixes are present. 7. If the task only asks to prepare local changes, stop here and report the changed files and validation result. diff --git a/.bumpversion.toml b/.bumpversion.toml index f5be5a9ab..af2f32902 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.9" +current_version = "0.41.0-beta.17" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index bfc6290db..f5d93eb0a 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -8,7 +8,7 @@ { "name": "lancedb", "source": "./plugins/lancedb", - "description": "Write, review, debug, and document LanceDB pipelines in Python and TypeScript that work across local LanceDB OSS tables and remote LanceDB Enterprise/Cloud tables.", + "description": "Write, review, debug, and document LanceDB pipelines in Python and TypeScript that work with both LanceDB Embedded and LanceDB Enterprise.", "version": "0.1.0", "author": { "name": "LanceDB" diff --git a/.github/vale/README.md b/.github/vale/README.md new file mode 100644 index 000000000..2cfbd1633 --- /dev/null +++ b/.github/vale/README.md @@ -0,0 +1,25 @@ +# LanceDB prose rules + +`Dashes`, `PlainLanguage`, `ProductNames`, `VagueHeadings` and `VaguePhrases` +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". + +The product-terminology rules were added here: `EmbeddedName`, +`RemoteExecution`, `OSSProduct`, `DistributedEnterprise`, `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`. + +Keeping the rules here lets contributors and CI run Vale without access to the +source repository. The root `.vale.ini` preserves the release's MDX settings +and built-in repeated-word check. No `vale sync` is needed. + +The rules check product names, dashes, plain language, vague headings and vague +phrases. Findings are suggestions and do not fail the CI check. + +To update, a maintainer downloads the next published package, verifies its +checksum and replaces `styles/LanceDB` with the release's files. Check the +package's `.vale.ini` for configuration changes, and update the version and +checksum here in the same PR. diff --git a/.github/vale/styles/LanceDB/Dashes.yml b/.github/vale/styles/LanceDB/Dashes.yml new file mode 100644 index 000000000..7bb10c96f --- /dev/null +++ b/.github/vale/styles/LanceDB/Dashes.yml @@ -0,0 +1,40 @@ +extends: existence +message: "Avoid '%s' in prose. Use a comma, a colon, parentheses or two sentences." +link: https://github.com/lancedb/docs/blob/main/STYLE.md#punctuation +level: warning +nonword: true +# An em dash in prose, and a double hyphen or en dash used as one, with a +# space on each side. A table cell holding only an em dash, meaning "none", +# ranges such as 1–3 and flags such as --force are left alone, and code is +# never prose. +raw: + - '(?> "$GITHUB_PATH" - - name: Annotate changed lines uses: vale-cli/vale-action@518a9136acc6e6668ce7c00d367051e0941e87ff # v3.0.0 with: - version: none + version: '3.24.0' + sync: false files: docs/web reporter: github-pr-annotations filter_mode: added diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index d0ec583bf..fb3fb1d6a 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -38,6 +38,7 @@ jobs: uses: actions/checkout@v6 - name: Install dependencies needed for ubuntu run: | + sudo apt update sudo apt install -y protobuf-compiler libssl-dev rustup update && rustup default - name: Set up Python diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index 7739489cb..6140afbc5 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -28,9 +28,9 @@ permissions: contents: read jobs: - build-java: + style-check: runs-on: ubuntu-24.04 - name: Build + name: Style Check defaults: run: working-directory: ./java @@ -45,5 +45,24 @@ jobs: cache: "maven" - name: Java Style Check run: ./mvnw checkstyle:check + + build-java: + runs-on: ubuntu-24.04 + name: Build (Java ${{ matrix.java-version }}) + strategy: + matrix: + java-version: [11, 17] + defaults: + run: + working-directory: ./java + steps: + - name: Checkout repository + uses: actions/checkout@v6 + - name: Set up Java ${{ matrix.java-version }} + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ matrix.java-version }} + cache: "maven" - name: Build and install - run: ./mvnw clean install + run: ./mvnw clean install -Dcheckstyle.skip=true diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 2e290166e..e83c8d29f 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -79,11 +79,15 @@ jobs: # that dir is missing, so create an empty one for lint-only runs. run: mkdir -p ../dist && pnpm install --frozen-lockfile && pnpm lint-ci linux: - name: Linux (NodeJS ${{ matrix.node-version }}) + name: Linux (NodeJS ${{ matrix.node-version }}, ${{ matrix.features }}) timeout-minutes: 30 strategy: matrix: node-version: [ "22", "24", "26" ] + features: [ "default" ] + include: + - node-version: "24" + features: "experimental-functions" runs-on: "ubuntu-22.04" defaults: run: @@ -121,7 +125,7 @@ jobs: pnpm install --frozen-lockfile # No `--` separator: pnpm forwards it literally, which would # make napi-rs treat `--profile ci` as a cargo passthrough arg. - pnpm build:debug --profile ci + pnpm build:debug --profile ci --features ${{ matrix.features }} pnpm tsc - name: Setup examples working-directory: nodejs/examples diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index c3724de8d..a8dd3993e 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -71,9 +71,9 @@ jobs: # https://github.com/napi-rs/napi-rs/blob/main/debian.Dockerfile docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-debian pre_build: |- - set -e && - apt-get update && - apt-get install -y protobuf-compiler pkg-config && + set -e + apt-get update + apt-get install -y protobuf-compiler pkg-config # The base image (manylinux2014-cross) sets TARGET_CC to the old # GCC 4.8 cross-compiler. aws-lc-sys checks TARGET_CC before CC, # so it picks up GCC even though the napi-rs image sets CC=clang. @@ -84,10 +84,10 @@ jobs: host: ubuntu-2404-8x-x64 features: fp16kernels pre_build: |- - set -e && - sudo apt-get update && - sudo apt-get install -y protobuf-compiler pkg-config && - rustup target add x86_64-unknown-linux-musl && + set -e + sudo apt-get update + sudo apt-get install -y protobuf-compiler pkg-config + rustup target add x86_64-unknown-linux-musl export EXTRA_ARGS="-x" - target: aarch64-unknown-linux-gnu host: ubuntu-2404-8x-x64 @@ -103,13 +103,13 @@ jobs: # linker process 7.0 -> 4.0 GiB (lancedb/sophon#7313). linker: /tmp/aarch64-lld-clang pre_build: |- - set -e && - apt-get update && - apt-get install -y protobuf-compiler pkg-config && - export TARGET_CC=clang TARGET_CXX=clang++ && + set -e + apt-get update + apt-get install -y protobuf-compiler pkg-config + export TARGET_CC=clang TARGET_CXX=clang++ # The manylinux2014 sysroot has glibc 2.17 headers which lack # AT_HWCAP2 (added in Linux 3.17). Define it for aws-lc-sys. - export CFLAGS="$CFLAGS -DAT_HWCAP2=26" && + export CFLAGS="$CFLAGS -DAT_HWCAP2=26" rustup target add aarch64-unknown-linux-gnu # Not `&&`-chained: in dash, errexit does not fire for a # non-final command in an `&&` list, so failures were ignored. @@ -136,10 +136,10 @@ jobs: lto: thin codegen_units: 16 pre_build: |- - set -e && - sudo apt-get update && - sudo apt-get install -y protobuf-compiler && - rustup target add aarch64-unknown-linux-musl && + set -e + sudo apt-get update + sudo apt-get install -y protobuf-compiler + rustup target add aarch64-unknown-linux-musl export EXTRA_ARGS="-x" name: build - ${{ matrix.settings.target }} runs-on: ${{ matrix.settings.host }} diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index e71564473..d45833def 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -15,6 +15,9 @@ on: - ci/check_cargo_lock.py - ci/check_sdist.py - python/pyproject.toml + - python/Cargo.toml + - python/vendor/** + - rust/lancedb/Cargo.toml - Cargo.toml # Change in dependency frequently breaks builds - Cargo.lock @@ -184,12 +187,14 @@ jobs: command: sdist working-directory: python args: --out dist - # maturin ships the nodejs-only pins in Cargo.lock. Remove this step when - # the pinned maturin fixes https://github.com/PyO3/maturin/issues/2609. + # maturin ships pins used only by other workspace members in Cargo.lock. + # Remove this step when the pinned maturin fixes + # https://github.com/PyO3/maturin/issues/2609. - name: Sync Cargo.lock to the packaged workspace shell: bash run: | - # A repo lock in sync with every manifest means the prune only drops pins. + # A synced repo lock lets the prune drop packages and optional edges + # without changing the remaining pins or adding dependency edges. cargo metadata --locked --format-version 1 > /dev/null mkdir "$RUNNER_TEMP/sdist-src" tar -xzf python/dist/lancedb-*.tar.gz -C "$RUNNER_TEMP/sdist-src" diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 3608c24ca..fa6ac4741 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -122,6 +122,10 @@ jobs: run: | pip install --extra-index-url https://pypi.fury.io/lance-format/ --extra-index-url https://pypi.fury.io/lancedb/ -e .[tests,dev,embeddings] pip install mlx + - name: Test remote torch data loader + run: | + python -c "import torch" + pytest python/tests/test_torch.py::test_remote_permutation_dataloader_multiprocessing -q -rs - name: Doctest run: pytest --doctest-modules python/lancedb linux: @@ -162,7 +166,10 @@ jobs: - name: Delete wheels run: rm -rf target/wheels platform: - name: "Mac" + name: "Mac: ${{ matrix.features }}" + strategy: + matrix: + features: ["default", "experimental-functions"] timeout-minutes: 30 runs-on: macos-14 defaults: @@ -188,7 +195,7 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' }} - uses: ./.github/workflows/build_mac_wheel with: - args: --profile ci + args: --profile ci --features ${{ matrix.features }} - uses: ./.github/workflows/run_tests # Make sure wheels are not included in the Rust cache - name: Delete wheels diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index cbfefc83d..f65123f78 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -11,6 +11,7 @@ on: - rust-toolchain.toml - deny.toml - rust/** + - docs/web-tests/blob-v2/rs/** - nodejs/Cargo.toml - python/Cargo.toml - .github/workflows/rust.yml @@ -29,6 +30,63 @@ env: RUST_BACKTRACE: "1" jobs: + dependency-overrides: + name: Downstream Lance override + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v6 + - uses: actions-rust-lang/setup-rust-toolchain@v1 + - name: Read the pinned Lance tag + id: lance + run: | + python3 - <<'PYTHON' + import os + import tomllib + from pathlib import Path + + manifest = tomllib.loads(Path("Cargo.toml").read_text()) + tag = manifest["workspace"]["dependencies"]["lance"]["tag"] + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + output.write(f"tag={tag}\n") + PYTHON + - uses: actions/checkout@v6 + with: + repository: lance-format/lance + ref: ${{ steps.lance.outputs.tag }} + path: local-lance + - name: Resolve a downstream workspace with a local Lance override + run: | + mkdir -p downstream/src + touch downstream/src/lib.rs + cat > downstream/Cargo.toml <<'TOML' + [package] + name = "lancedb-local-lance-consumer" + version = "0.1.0" + edition = "2024" + + [workspace] + + [dependencies] + lancedb = { path = "../rust/lancedb", default-features = false } + lance-arrow = { path = "../local-lance/rust/lance-arrow" } + + [patch."https://github.com/lance-format/lance.git"] + lance-arrow = { path = "../local-lance/rust/lance-arrow" } + TOML + cargo metadata --manifest-path downstream/Cargo.toml --format-version 1 > downstream/graph.json + python3 - <<'PYTHON' + import json + from pathlib import Path + + graph = json.loads(Path("downstream/graph.json").read_text()) + packages = [p for p in graph["packages"] if p["name"] == "lance-arrow"] + assert len(packages) == 1, [p["id"] for p in packages] + assert Path(packages[0]["manifest_path"]).resolve() == Path( + "local-lance/rust/lance-arrow/Cargo.toml" + ).resolve() + PYTHON + lint: timeout-minutes: 30 runs-on: ubuntu-24.04 @@ -165,6 +223,11 @@ jobs: run: CARGO_ARGS="--profile ci" make -C ./lancedb feature-tests - name: Run examples run: cargo run --profile ci --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 remote: timeout-minutes: 30 @@ -198,6 +261,8 @@ jobs: sudo apt update sudo apt install -y protobuf-compiler libssl-dev - uses: rui314/setup-mold@v1 + - name: Test the default local Functions gate + run: cargo test --profile ci -p lancedb --features remote --test experimental_functions --locked - name: Run remote tests run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests @@ -245,12 +310,6 @@ jobs: include: - target: x86_64-pc-windows-msvc runner: windows-2022 - # windows-11-arm is a standard runner, so it is free on public repos. - # Running natively lets the aarch64 tests actually execute -- this - # job used to cross-compile them and then skip the test step, paying - # full codegen and link cost for a compile check. - - target: aarch64-pc-windows-msvc - runner: windows-11-arm runs-on: ${{ matrix.runner }} defaults: run: @@ -279,13 +338,50 @@ jobs: # dependency graph a second time. cargo test --profile ci --features aws,remote --locked --target ${{ matrix.target }} + # Run the aarch64 Windows tests only on main so PRs wait for a single + # Windows platform. windows-11-arm is a standard runner, so it is free on + # public repos. Running natively lets the aarch64 tests actually execute -- + # this job used to cross-compile them and then skip the test step, paying + # full codegen and link cost for a compile check. + windows-arm: + # Keep the historical name so the check shows up as before on main. + name: windows (aarch64-pc-windows-msvc, windows-11-arm) + if: github.ref == 'refs/heads/main' + runs-on: windows-11-arm + defaults: + run: + working-directory: rust/lancedb + steps: + - uses: actions/checkout@v6 + - name: Set target + run: rustup target add aarch64-pc-windows-msvc + - uses: Swatinem/rust-cache@v2 + with: + # Restore everywhere, but only save from main. Per-PR saves are + # unreadable outside their own branch anyway, since GitHub scopes + # caches to the creating ref. + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Install Protoc v21.12 + run: choco install --no-progress protoc + - name: Build + run: | + $env:VCPKG_ROOT = $env:VCPKG_INSTALLATION_ROOT + cargo build --profile ci --features aws,remote --tests --locked --target aarch64-pc-windows-msvc + - name: Run tests + run: | + $env:VCPKG_ROOT = $env:VCPKG_INSTALLATION_ROOT + # `--target` has to match the build step above. Without it cargo uses + # target/ci/ rather than target//ci/ and rebuilds the entire + # dependency graph a second time. + cargo test --profile ci --features aws,remote --locked --target aarch64-pc-windows-msvc + msrv: # Check the minimum supported Rust version name: MSRV Check - Rust v${{ matrix.msrv }} runs-on: ubuntu-24.04 strategy: matrix: - msrv: ["1.94.0"] # This should match up with rust-version in Cargo.toml + msrv: ["1.95.0"] # This should match up with rust-version in Cargo.toml env: # Need up-to-date compilers for kernels CC: clang-18 @@ -308,10 +404,18 @@ jobs: # unreadable outside their own branch anyway, since GitHub scopes # caches to the creating ref. save-if: ${{ github.ref == 'refs/heads/main' }} - - name: Downgrade dependencies - # aws-smithy-types 1.6.1+ requires rustc 1.94.1 - run: cargo update -p aws-smithy-types --precise 1.5.0 + - name: Resolve MSRV-compatible dependencies + # Resolve the AWS SDK and Smithy crates together: newer SDK releases + # require newer Smithy versions, so downgrading only Smithy can fail. + run: cargo +${{ matrix.msrv }} update --config 'resolver.incompatible-rust-versions="fallback"' + - name: Keep Xet dependencies compatible with the MSRV + # Xet 1.7 does not declare its MSRV, but requires sysinfo 0.39 (Rust 1.95). + # Downgrade parents before their dependencies to satisfy their constraints. + run: | + for crate in hf-xet xet-data xet-client xet-core-structures xet-runtime; do + cargo +${{ matrix.msrv }} update -p "$crate" --precise 1.6.0 + done - name: cargo +${{ matrix.msrv }} check env: RUSTUP_TOOLCHAIN: ${{ matrix.msrv }} - run: cargo check --profile ci --workspace --tests --benches --all-features + run: cargo check --locked --profile ci --workspace --tests --benches --all-features diff --git a/.vale.ini b/.vale.ini index 13b421863..bbac95eb3 100644 --- a/.vale.ini +++ b/.vale.ini @@ -1,5 +1,6 @@ -# Prose style for the pages in docs/web: the shared LanceDB package, pinned by -# release. The rules and guide live in lancedb/docs (STYLE.md and vale/). -# Run `vale sync` once, then `vale docs/web/.mdx`. -StylesPath = .vale/styles -Packages = https://github.com/lancedb/docs/releases/download/vale-lancedb-v0.1.0/LanceDB.zip +StylesPath = .github/vale/styles +MinAlertLevel = suggestion + +[*.mdx] +BasedOnStyles = LanceDB +Vale.Repetition = warning diff --git a/AGENTS.md b/AGENTS.md index f6d01db03..24465a28f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,8 +102,8 @@ TypeScript bindings changes: 1. Add napi-rs method binding on `Table` in `nodejs/src/table.rs`. 2. Run `pnpm build` to generate TypeScript definitions. -3. Add typescript method on abstract class `Table` in `nodejs/src/table.ts`. -4. Add concrete method on `LocalTable` class in `nodejs/src/native_table.ts`. +3. Add typescript method on abstract class `Table` in `nodejs/lancedb/table.ts`. +4. Add concrete method on `LocalTable` class in `nodejs/lancedb/table.ts`. * Note: despite the name, this class is also used for remote tables. 5. Add test in `nodejs/__test__/table.test.ts`. 6. Run `pnpm run docs` to generate TypeScript documentation. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f7aeac21a..c3bf61471 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,96 +72,128 @@ 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`: the open-source pages of [docs.lancedb.com](https://docs.lancedb.com) +* `docs/web`: website guides for LanceDB Embedded and the APIs used by both Embedded and Distributed * `docs/web-tests`: the tests the documentation's code examples are extracted from ## Documentation -The open-source pages of [docs.lancedb.com](https://docs.lancedb.com) live in -`docs/web`, so a change to behaviour and the change to the page describing it -belong in the same pull request. +Update the docs in the same pull request as the behavior they describe. You can +merge docs before a feature launches; keep the unfinished material hidden until +it is ready for readers. -Preview them locally — this serves `docs/web` on its own, with no other checkout: +### Choose the right place + +- `docs/web/` holds website guides for LanceDB Embedded and the APIs used by both + Embedded and Distributed. +- `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. +Put Enterprise-specific deployment and operating instructions in the Enterprise +documentation. + +Some pages are placeholders that the website build replaces with an Enterprise +page. Changes to a placeholder won't appear on the combined site. Put +instructions that both products need on a separate page and link to it. + +### Preview and check your change + +From the repository root: ```bash -npm i -g mint # https://mintlify.com/docs/installation -cd docs/web && mint dev +npm i -g mint@4.2.888 +(cd docs/web && mint dev) ``` -Wording, names and punctuation follow the -[LanceDB style guide](https://github.com/lancedb/docs/blob/main/STYLE.md). -[Vale](https://vale.sh) checks part of it, and pull requests show its -suggestions on the lines they change. To check a page yourself: +This previews this checkout, including your uncommitted changes. It doesn't +include the other documentation sources or render the availability labels. +Use the [combined preview](https://github.com/lancedb/docs#development) when +checking Enterprise replacements or links to pages from another source. +Staging shows saved release editions, so it won't show a new source change +just because that change merged. + +Follow the [style guide](https://github.com/lancedb/docs/blob/main/STYLE.md). +[Vale](https://vale.sh) checks wording, names and punctuation using the +[bundled LanceDB rules](.github/vale/README.md). Pull requests show suggestions +on the lines they change. With Vale 3.24.0 installed, check a page locally with: ```bash -vale sync && vale docs/web/indexing/vector-index.mdx +vale docs/web/indexing/vector-index.mdx ``` -This repository holds a page at every path the site publishes, so the whole -navigation resolves locally. Enterprise pages exist here as open-source pages -- -what the capability is, and what the embedded form does instead. A separate -private repository supplies the fuller version of each, which replaces the page -at the same path when the published site is assembled. +Keep existing `{#anchor}` values when changing headings, so links to those +sections keep working. Give new headings stable anchors. For links in rendered +components, write the path directly, such as `href="/quickstart"`, and spell out +attributes rather than using property spreads. That lets versioned docs keep +links inside the selected edition. Code examples aren't subject to this rule. -Four things to know before editing: +### Code examples -**Code examples are not written into the pages.** They live in real tests under -`docs/web-tests/{py,ts,rs}`, are extracted into `docs/web/snippets/`, and are -imported by the pages. Edit the test, then regenerate from the repository root: +Edit the test that produces an example, then regenerate its snippet. The +sources are `docs/web-tests/{py,ts,rs}`, `docs/web-tests/blob-v2/{py,ts,rs}` and +`rust/lancedb/tests`. Run this from the repository root: ```bash -uv run docs/web-tests/mdx_snippets_gen.py -s docs/web-tests/py -s docs/web-tests/ts -s docs/web-tests/rs -o docs/web/snippets +uv run docs/web-tests/mdx_snippets_gen.py \ + -s docs/web-tests/py -s docs/web-tests/ts -s docs/web-tests/rs \ + -s docs/web-tests/blob-v2/py -s docs/web-tests/blob-v2/ts -s docs/web-tests/blob-v2/rs \ + -s rust/lancedb/tests -o docs/web/snippets ``` -Review the diff before committing: a few modules currently regenerate with -unrelated changes, so commit only the snippets for the examples you changed. +Run the tests for the examples you changed; generating a snippet doesn't run +its example. Review the generated diff and commit only the relevant snippets +with their tests. Don't assume the PR checks execute every documentation +example. -Run the Python, TypeScript and Rust examples in `docs/web-tests/{py,ts,rs}` -locally before submitting the change. These examples are not yet wired into -pull-request CI; that integration remains follow-up work. +### Say where a feature works -**Every heading carries an explicit `{#anchor}`.** Those anchors are how the -Enterprise pages attach their additions to the right section, so they are -assigned once and never regenerated. Leave an existing anchor alone even when -you reword the heading above it; only new headings need a new one. - -**A page can declare where it applies.** Its frontmatter says whether LanceDB -OSS and LanceDB Enterprise support the feature: use only `available` or -`unavailable`, and one sentence that explains its scope. Availability describes -product support, not whether a particular deployment has enabled or configured -the feature. A supported feature stays `available` when it requires setup, a -supported SDK or server version, or has differences between offerings. State -those requirements in the summary or the relevant section, including unsupported -subfeatures. Do not use `varies`, infer support from an unknown status, or mark an -absent capability available. Narrow a page to the capability it actually covers -when necessary. For example: +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: ```yaml availability: oss: unavailable enterprise: available summary: >- - Requests to a deployment carry an API key or an OAuth token. Embedded - LanceDB has no server to sign in to. + These sign-in instructions apply to LanceDB Enterprise. LanceDB + Embedded has no server to sign in to. ``` -The assembled site renders this as a label above the page's content and as a -sidebar tag when only one offering has the feature. Do not also open the page -with a badge of its own, and keep a qualification that only one section needs -in that section's text. A `mint dev` preview of `docs/web` alone renders -neither the labels nor the tags. +Check these claims with the feature owner. Don't use `varies`, treat an API +stub as working support, or mark a supported feature unavailable just because +it needs configuration. If one label can't describe the whole page accurately, +make the page's scope narrower and explain the differences. -**A feature can be documented before its release.** List a draft page in -`docs/web/.mintignore`, keep it out of the navigation in `docs.json`, and do not -link to it from published pages. Wrap a draft section in an MDX comment, -`{/* ... */}`, whose first line names the release, such as -`Draft for the Feature X release.` Keep draft table rows and list items in a -comment below the table or list, since a comment between rows or items breaks -it. Drafts are hidden from readers but stay in the source, and availability does -not change what is published. At release, remove the comments and the -`.mintignore` entries, and restore the navigation and links. See +Assembly turns this declaration into a page label and, for a feature supported +by only one product, a sidebar tag. Don't add those badges by hand. Availability +labels do not hide unreleased content. + +### Write docs before launch + +You don't need to hold a documentation PR until launch. Use these controls: + +- For a whole page, add its path to `docs/web/.mintignore`. Leave it out of + `docs/web/docs.json`, redirects and links from published pages. Removing a + sidebar entry alone doesn't hide a page. +- For a section, wrap it in an MDX comment, `{/* ... */}`, with a note such as + `Draft for the Feature X release.` Put draft table rows and list items in a + comment below the table or list, not between entries. + +Drafts remain in the source. Use them to avoid advertising an unfinished +feature, not to keep information confidential. See [Writing docs before release](https://github.com/lancedb/docs#writing-docs-before-release) -in the documentation repository's README for previews and release checks. +for examples and how to preview a draft. + +Before the intended release, remove the draft controls, restore the navigation +and links, and check the result. Those changes must be in the source commit the +edition uses. A later change to `main` doesn't update an edition already saved. +For a mistake in an existing edition, fix the source and request a +[recorded correction](https://github.com/lancedb/docs#correcting-a-saved-edition). ## Release process diff --git a/Cargo.lock b/Cargo.lock index b339cf454..bf7b12213 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -181,9 +181,9 @@ dependencies = [ [[package]] name = "arc-swap" -version = "1.9.2" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" dependencies = [ "rustversion", ] @@ -197,6 +197,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "argminmax" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "088a9c28ca36500c581f9f54b63460492d2b4f71e1e61d176e8fb79565109b01" +dependencies = [ + "num-traits", +] + [[package]] name = "array-init-cursor" version = "0.2.1" @@ -217,9 +226,9 @@ checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[package]] name = "arrow" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cfdd0833e32a9874d2b55089333ad310c0be208aafa277385ce2461dec90be3" +checksum = "3f04e0a89cc175eaf3740282537851e6fd9d7276f97730b9d0ea2859c11a85df" dependencies = [ "arrow-arith", "arrow-array", @@ -239,9 +248,9 @@ dependencies = [ [[package]] name = "arrow-arith" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a41203398f0eaa6f7ec8e62c0da742a21abf282c148fc157f6c35c90e29981a" +checksum = "157943c720919e8f5b6731407ce5cd4c9a5ef47a75bf10edaf24b7081b5763ef" dependencies = [ "arrow-array", "arrow-buffer", @@ -253,9 +262,9 @@ dependencies = [ [[package]] name = "arrow-array" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae33dad492b7df00a217563a7b0ef2874df68a0deea1b1a3acf628152f7f7a69" +checksum = "72b5b1682924f11ecf6929689c16cbc69efbb6dd141b06ad98ee1cb10d858c43" dependencies = [ "ahash", "arrow-buffer", @@ -265,6 +274,7 @@ dependencies = [ "chrono-tz 0.10.4", "half", "hashbrown 0.17.1", + "libc", "num-complex", "num-integer", "num-traits", @@ -272,21 +282,21 @@ dependencies = [ [[package]] name = "arrow-buffer" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9552f96391c005e6ab449fa941420935e7e062489b12b8b1b08879b2163f5b5" +checksum = "b5d687afc6c927965a8a759f3b68de91933d9dfa2e1bb6e156bac84b85665e92" dependencies = [ "bytes", "half", - "num-bigint", + "num-bigint 0.5.1", "num-traits", ] [[package]] name = "arrow-cast" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a8a327c9649f30d8406995f27642b68df354713cca3baaaf100f076f18d5f34" +checksum = "3f23c3379feede42135ef27ca60e67f6e643cd4343ae74e4c8b16c83f55afd85" dependencies = [ "arrow-array", "arrow-buffer", @@ -295,7 +305,7 @@ dependencies = [ "arrow-schema", "arrow-select", "atoi", - "base64 0.22.1", + "base64 0.23.1", "chrono", "comfy-table", "half", @@ -306,9 +316,9 @@ dependencies = [ [[package]] name = "arrow-csv" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af0dd6d90d1955e9f9a014c1e563ee8aeffc21909085d25623e1da44d96eca26" +checksum = "85b1984628b091b8319b3c305fce21d04f9e9b2578bb733b0d0108462ae1d698" dependencies = [ "arrow-array", "arrow-cast", @@ -321,9 +331,9 @@ dependencies = [ [[package]] name = "arrow-data" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b24852db04738907e06c04ea61e42fe7fda962a34513022dc0d0e754fb7976b" +checksum = "bb0a031c7ff5e2bdb443117054fb466af1d4df5b7f0ecbe197713dc8b113b1ba" dependencies = [ "arrow-buffer", "arrow-schema", @@ -334,9 +344,9 @@ dependencies = [ [[package]] name = "arrow-flight" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2dbe34824c639e43136af8f106992792ab456540d54b880bc320a3192502d2e" +checksum = "43f998a8cc9ffdc37731b66c0414dccf4f4f11a03d9136d383ef10f95181cd7d" dependencies = [ "arrow-arith", "arrow-array", @@ -349,11 +359,10 @@ dependencies = [ "arrow-schema", "arrow-select", "arrow-string", - "base64 0.22.1", + "base64 0.23.1", "bytes", "futures", "once_cell", - "paste", "prost", "prost-types", "tonic", @@ -362,9 +371,9 @@ dependencies = [ [[package]] name = "arrow-ipc" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29a908a11fcfb3fb2f6730f4ac15e367bc644e419155e96238f68cf3adde572b" +checksum = "f5dd1afadda2eb821aaf851bb4c0adef60c30cc0f1a29bd02fb99dd07fb9f58d" dependencies = [ "arrow-array", "arrow-buffer", @@ -372,15 +381,15 @@ dependencies = [ "arrow-schema", "arrow-select", "flatbuffers", - "lz4_flex", - "zstd", + "lz4_flex 0.14.0", + "zstd 0.13.3", ] [[package]] name = "arrow-json" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8a96aed3931c076adee39ec2a40d8219fc7f09e79bcdaca1df16272993e1e14" +checksum = "e2bc4d56a0dad84cc51c5812ccff48b642047a1f3be80349cd84318983e79edb" dependencies = [ "arrow-array", "arrow-buffer", @@ -403,9 +412,9 @@ dependencies = [ [[package]] name = "arrow-ord" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63a083ec750f5c043f02946b4baf05fcdbb55f4560a3277055caca5cc99f3eb0" +checksum = "561b8209faa2cd489764b7fd07d7cb9e8d274d78048c38de59f77c41140cb834" dependencies = [ "arrow-array", "arrow-buffer", @@ -416,9 +425,9 @@ dependencies = [ [[package]] name = "arrow-pyarrow" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ffb9be5a873590f825aef50df20e0f8dff5fd42a77058e28bbe7bd44bb53dec" +checksum = "ba037102b3f52163f96db970209ada931c2a6f46c4607d3170950d075db68773" dependencies = [ "arrow-array", "arrow-data", @@ -428,9 +437,9 @@ dependencies = [ [[package]] name = "arrow-row" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "514ba0ef0d4c5896202dae736251ce415abb43a950bed570fb7981b8716c0e4c" +checksum = "0d8c68b87a569f92b90c46cb0a09d86bd9609ddc9b1bf1fc5a503c8c6907c14e" dependencies = [ "arrow-array", "arrow-buffer", @@ -441,9 +450,9 @@ dependencies = [ [[package]] name = "arrow-schema" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21ca356ad6425cecb6eb7b28e4f659f1ee7880fbb1a16127de7dd62901efee9e" +checksum = "e87acb0c6bf6237fca7a50d7b51e801c98a18a5fe6f3bb34f7d77b85ca165388" dependencies = [ "bitflags 2.11.1", "serde_core", @@ -452,9 +461,9 @@ dependencies = [ [[package]] name = "arrow-select" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c58da39eb3d8350ad4a549e5c2bc49284dac554016c69829310350f1731b0aad" +checksum = "c844141958d805b47d1208e0d12aac53fcf388ce8011639fe82aa492adde0bb4" dependencies = [ "ahash", "arrow-array", @@ -466,9 +475,9 @@ dependencies = [ [[package]] name = "arrow-string" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6789b388467525e3271326b6b4915666ecfdf5142aef09779445c954b67543c" +checksum = "bc130892b1a9552da77971924b390e06cf375d1f7e4344a7b7b40ca4426fa470" dependencies = [ "arrow-array", "arrow-buffer", @@ -1195,10 +1204,13 @@ checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core 0.5.6", "bytes", + "form_urlencoded", "futures-util", "http 1.5.0", "http-body 1.1.0", "http-body-util", + "hyper", + "hyper-util", "itoa", "matchit 0.8.4", "memchr", @@ -1206,10 +1218,15 @@ dependencies = [ "percent-encoding", "pin-project-lite", "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", "sync_wrapper", + "tokio", "tower", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -1249,6 +1266,7 @@ dependencies = [ "sync_wrapper", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -1345,7 +1363,7 @@ checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695" dependencies = [ "autocfg", "libm", - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", ] @@ -1663,6 +1681,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + [[package]] name = "cfg_aliases" version = "0.2.1" @@ -1770,6 +1794,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" dependencies = [ "clap_builder", + "clap_derive", ] [[package]] @@ -1778,8 +1803,22 @@ version = "4.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" dependencies = [ + "anstream", "anstyle", "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] @@ -1788,6 +1827,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + [[package]] name = "cmake" version = "0.1.58" @@ -1815,7 +1863,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1836,7 +1884,7 @@ checksum = "958c5d6ecf1f214b4c2bbbbf6ab9523a864bd136dcf71a7e8904799acfe1ad47" dependencies = [ "crossterm", "unicode-segmentation", - "unicode-width", + "unicode-width 0.2.2", ] [[package]] @@ -1874,7 +1922,7 @@ dependencies = [ "encode_unicode", "libc", "once_cell", - "unicode-width", + "unicode-width 0.2.2", "windows-sys 0.59.0", ] @@ -2137,7 +2185,7 @@ dependencies = [ "crossterm_winapi", "document-features", "parking_lot", - "rustix", + "rustix 1.1.4", "winapi", ] @@ -2230,9 +2278,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.2" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +checksum = "12218662ccac37d9714f2191252553d67585b97df8c839cbe49e0bde278dc865" dependencies = [ "cmov", ] @@ -2314,9 +2362,9 @@ dependencies = [ [[package]] name = "dashmap" -version = "6.1.0" +version = "6.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" dependencies = [ "cfg-if 1.0.4", "crossbeam-utils", @@ -2328,9 +2376,9 @@ dependencies = [ [[package]] name = "datafusion" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "754ef4e8f073922a26f5b23133b9db4829342362b09be0bc94309cf261c2f098" +checksum = "4cd5317db77ba6bca25c761a8091b9d294a9f4188e4f9dcd0243e6a57de862ac" dependencies = [ "arrow", "arrow-schema", @@ -2362,7 +2410,7 @@ dependencies = [ "datafusion-sql", "futures", "indexmap 2.14.0", - "itertools 0.14.0", + "itertools 0.15.0", "log", "object_store 0.13.2", "parking_lot", @@ -2375,9 +2423,9 @@ dependencies = [ [[package]] name = "datafusion-catalog" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06afd1e38dd27bbb1258685a1fc6524df6aff4e07b25b393a47de59635178d99" +checksum = "f35d36794509b7bfcbf90e11a1b5e4d047123c34610105e2e80a2048351cdb2f" dependencies = [ "arrow", "async-trait", @@ -2391,7 +2439,7 @@ dependencies = [ "datafusion-physical-plan", "datafusion-session", "futures", - "itertools 0.14.0", + "itertools 0.15.0", "log", "object_store 0.13.2", "parking_lot", @@ -2400,9 +2448,9 @@ dependencies = [ [[package]] name = "datafusion-catalog-listing" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0668fb32c12065ec242be0e5b4bc62bd7a06a0be3ecd83791ef877e4be67e02" +checksum = "a6454bfb7f43b83942e2ca2576fd09342eedbd0d323e1eef72c3c8e4d57d7203" dependencies = [ "arrow", "async-trait", @@ -2416,16 +2464,17 @@ dependencies = [ "datafusion-physical-expr-common", "datafusion-physical-plan", "futures", - "itertools 0.14.0", + "itertools 0.15.0", "log", "object_store 0.13.2", + "percent-encoding", ] [[package]] name = "datafusion-common" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca43b263cdff57042cfa8fb817fb3469f4878933380dccff25f5e793580abbf9" +checksum = "d26626e12b224b83351239465dcd00f72d47b02fb5e5b65a643e2dc8ed37f687" dependencies = [ "arrow", "arrow-ipc", @@ -2435,9 +2484,10 @@ dependencies = [ "half", "hashbrown 0.17.1", "indexmap 2.14.0", - "itertools 0.14.0", + "itertools 0.15.0", "libc", "log", + "num-traits", "object_store 0.13.2", "sqlparser 0.62.0", "tokio", @@ -2447,9 +2497,9 @@ dependencies = [ [[package]] name = "datafusion-common-runtime" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f0ba2b864792bdca4d76c59a1de0ab6e1b61946596b9936888dbd6360035f2" +checksum = "a106420cbfa980f242c22243ae9a6cce661d4d86ce96cff87dacabf7754a4470" dependencies = [ "futures", "log", @@ -2458,9 +2508,9 @@ dependencies = [ [[package]] name = "datafusion-datasource" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b840a8bce0bcbf5afad02946d438591e7c373f7afccaf3d874c04485772514dd" +checksum = "210aa1e9525e9454f2399dbb8b0b95510145bd8c1fdc35de74e9ccbf81bcb699" dependencies = [ "arrow", "async-trait", @@ -2477,7 +2527,7 @@ dependencies = [ "datafusion-session", "futures", "glob", - "itertools 0.14.0", + "itertools 0.15.0", "log", "object_store 0.13.2", "parking_lot", @@ -2488,9 +2538,9 @@ dependencies = [ [[package]] name = "datafusion-datasource-arrow" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a24cc0b9cf6e367f27f27406eff13abf48a11b72446aaa40b3105c0ded5c17d9" +checksum = "65b1b041688cad707fa103c3e7f4c6d89b3134ebf67da0129070dad3381851eb" dependencies = [ "arrow", "arrow-ipc", @@ -2505,16 +2555,16 @@ dependencies = [ "datafusion-physical-plan", "datafusion-session", "futures", - "itertools 0.14.0", + "itertools 0.15.0", "object_store 0.13.2", "tokio", ] [[package]] name = "datafusion-datasource-csv" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1abe56b2a7a2d1d6de5117dd1a203181e267f28529faa5da546947621b697d7" +checksum = "2a7b34e253c4fa5251f174977af910a2f2ec831ec39dbbb56b29ce505cff278b" dependencies = [ "arrow", "async-trait", @@ -2535,9 +2585,9 @@ dependencies = [ [[package]] name = "datafusion-datasource-json" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3e467f0611ad7bdd5aad17c63c9bb6182d04e5282e5496d897ea2b49c024ba" +checksum = "1663338f43be6a5746473008e2d0fbde282577ddf0bae90d6c7386e988d71b29" dependencies = [ "arrow", "async-trait", @@ -2558,19 +2608,20 @@ dependencies = [ [[package]] name = "datafusion-doc" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d69bb69d8769e34f76839c960dbde24c1ac0c885a79b6c3c2287bdc56ec67891" +checksum = "0c2569c2e74a34fcae3a369ab3912d61e41a062592510f11e31b1dae2725ecdc" [[package]] name = "datafusion-execution" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8eac0a09bc8d263f52025cad9e001da4d8138d633fa288edda4d06b1772eae6" +checksum = "39cfdd5ac0769d1e74a885450e49fde8f63ca7ab41eb479a068564aaea80b837" dependencies = [ "arrow", "arrow-buffer", "async-trait", + "bytes", "dashmap", "datafusion-common", "datafusion-expr", @@ -2579,16 +2630,19 @@ dependencies = [ "log", "object_store 0.13.2", "parking_lot", + "pin-project-lite", "rand 0.9.5", "tempfile", + "tokio", + "tokio-util", "url", ] [[package]] name = "datafusion-expr" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eeb14d374767ee0fc62dc79a5ba8bcf8a63c14e993c7d992d0e63adfa23d77d3" +checksum = "86560fd7df4dda924f5474b588c56e7ae8e96dcf158c7327c9cfe9daff448ec5" dependencies = [ "arrow", "arrow-schema", @@ -2601,32 +2655,33 @@ dependencies = [ "datafusion-functions-window-common", "datafusion-physical-expr-common", "indexmap 2.14.0", - "itertools 0.14.0", + "itertools 0.15.0", + "serde", "serde_json", "sqlparser 0.62.0", ] [[package]] name = "datafusion-expr-common" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7b19a8c95522bee8cbb313d74263b85e355d2b52f42e67ef5694bf5de9e9356" +checksum = "e82e313cf655cf6bc2dce6cbd23bcb0d20236a54a1b09c436615e4bac4d8c49f" dependencies = [ "arrow", "datafusion-common", "indexmap 2.14.0", - "itertools 0.14.0", + "itertools 0.15.0", ] [[package]] name = "datafusion-functions" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f64c983bbbdcb729d921a2b2ac3375598719b5cc0c30345ad664936f3176fc7" +checksum = "939ae2771da8a3fdc23ab4de610ae8fef9515476626b49d96d0d5c782b105771" dependencies = [ "arrow", "arrow-buffer", - "base64 0.22.1", + "base64 0.23.1", "blake2", "blake3", "chrono", @@ -2639,7 +2694,7 @@ dependencies = [ "datafusion-macros", "datafusion-physical-expr-common", "hex", - "itertools 0.14.0", + "itertools 0.15.0", "log", "md-5", "memchr", @@ -2652,9 +2707,9 @@ dependencies = [ [[package]] name = "datafusion-functions-aggregate" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89bc17041e424a47ed062f43df24d84aab8b57c4c3221e5c1a5eef46d6c5718b" +checksum = "fd6c3aee9f2bc65716787d651e023743a90b4efbc57a2f679f036632e16fb110" dependencies = [ "arrow", "datafusion-common", @@ -2665,17 +2720,17 @@ dependencies = [ "datafusion-macros", "datafusion-physical-expr", "datafusion-physical-expr-common", - "foldhash 0.2.0", "half", + "hashbrown 0.17.1", "log", "num-traits", ] [[package]] name = "datafusion-functions-aggregate-common" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97dd2a9e865c6108059f5b37b77934f84b50bfb108f837bd0e5c9536e03f0545" +checksum = "988b5d3dfb4939d81c2f9fab267063610fe52a843620f2fa6cb2a1598e43369c" dependencies = [ "arrow", "datafusion-common", @@ -2685,9 +2740,9 @@ dependencies = [ [[package]] name = "datafusion-functions-nested" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75f0bdfeef16d96417b9632ef855645376b242e9006a126dfd0bedfc54a93f5f" +checksum = "08149d433a97c9ea3cdf80de06480ab5c7f5453485f1e452d5b3583c81d5c0dd" dependencies = [ "arrow", "arrow-ord", @@ -2702,7 +2757,7 @@ dependencies = [ "datafusion-macros", "datafusion-physical-expr-common", "hashbrown 0.17.1", - "itertools 0.14.0", + "itertools 0.15.0", "itoa", "log", "memchr", @@ -2710,9 +2765,9 @@ dependencies = [ [[package]] name = "datafusion-functions-table" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4e4941673c917819616877e9993da4503e4f4739812be0bc32c5356184c6383" +checksum = "2c767567cce2782d4d0bdfa55fab010aaba0bdbe533509e9e0b9a6a3ee29ed59" dependencies = [ "arrow", "async-trait", @@ -2726,9 +2781,9 @@ dependencies = [ [[package]] name = "datafusion-functions-window" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12dd2e16c12b84b6f6b41b19f55b366dd1c46876bb35b86896c6349067379e8d" +checksum = "0a311c1f558d1f792f1f631c3670da12ee72a20fbf5d6ca151325d66191c03c1" dependencies = [ "arrow", "datafusion-common", @@ -2743,9 +2798,9 @@ dependencies = [ [[package]] name = "datafusion-functions-window-common" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cdc5e4b6f8b6ef823cc1c761f85088ad4c884fe8df64df3cbcc6b2b84698441" +checksum = "fffd54b8acf6ecef284cc0677e01e1b8c71be64fec50612ba00a0ff0d9b41a52" dependencies = [ "datafusion-common", "datafusion-physical-expr-common", @@ -2753,20 +2808,20 @@ dependencies = [ [[package]] name = "datafusion-macros" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a3614234dd93578c92428cb4f408e020874f0d2b7e6c90c928d9d28b5df2ceb" +checksum = "14d6df9763c8fb968b2417d797aef4c55ac2e4a895aaef38c72c16a287aa4a40" dependencies = [ "datafusion-doc", "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] name = "datafusion-optimizer" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0635620b050b81bb92764e99250868f654e2cd5ad1bece413283b3f73c83179" +checksum = "acfb8cea6e05e2e75bae183340cf7d53cccb3db0449e2f1fbc07654d980fd19f" dependencies = [ "arrow", "chrono", @@ -2775,7 +2830,7 @@ dependencies = [ "datafusion-expr-common", "datafusion-physical-expr", "indexmap 2.14.0", - "itertools 0.14.0", + "itertools 0.15.0", "log", "regex", "regex-syntax", @@ -2783,11 +2838,12 @@ dependencies = [ [[package]] name = "datafusion-physical-expr" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cabf7a86eb70b816729e33c81bf7767c936ee1226f607a114f5dac2decac8d0" +checksum = "9f002cef849e10c0597a217ec7891c2796c0f8b42d739f5d24abc24496373406" dependencies = [ "arrow", + "arrow-schema", "datafusion-common", "datafusion-expr", "datafusion-expr-common", @@ -2796,7 +2852,7 @@ dependencies = [ "half", "hashbrown 0.17.1", "indexmap 2.14.0", - "itertools 0.14.0", + "itertools 0.15.0", "parking_lot", "petgraph", "tokio", @@ -2804,9 +2860,9 @@ dependencies = [ [[package]] name = "datafusion-physical-expr-adapter" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de222e04f7e6744501555a54ab0abe26bfdfebee380af79a9bdc175704246859" +checksum = "82761522c4536e7059d3b185cd99f10525c2bf48f1bd26a0a57e73e19eadc0fb" dependencies = [ "arrow", "datafusion-common", @@ -2814,14 +2870,14 @@ dependencies = [ "datafusion-functions", "datafusion-physical-expr", "datafusion-physical-expr-common", - "itertools 0.14.0", + "itertools 0.15.0", ] [[package]] name = "datafusion-physical-expr-common" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d0d0057fc5a502d45c870cb6d47c66eb7bdd5edb1bd71ad6f3f724975ac2a8" +checksum = "f8c5c67aa252886f4d6b331c8114797f5b140464e774c4da36889269a1bf1bd8" dependencies = [ "arrow", "chrono", @@ -2829,16 +2885,16 @@ dependencies = [ "datafusion-expr-common", "hashbrown 0.17.1", "indexmap 2.14.0", - "itertools 0.14.0", + "itertools 0.15.0", "parking_lot", "pin-project", ] [[package]] name = "datafusion-physical-optimizer" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86046eed10950c5f9aaed9acfd148e9bd2e1dfdfe4f9aef607d1447b271e4183" +checksum = "f1a49dd3a76e4879012682c59dc3735282e60640c97483546a4113564a60bf8f" dependencies = [ "arrow", "datafusion-common", @@ -2849,14 +2905,15 @@ dependencies = [ "datafusion-physical-expr-common", "datafusion-physical-plan", "datafusion-pruning", - "itertools 0.14.0", + "datafusion-session", + "itertools 0.15.0", ] [[package]] name = "datafusion-physical-plan" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bc84da934c903407ba297971ebcc020c4c1a38aafd765d6c144c76eff3fa6a1" +checksum = "b1451d6817e5ac0dd21819b19949d1c420ab51d748f55dd9a96ecb5418a24c97" dependencies = [ "arrow", "arrow-data", @@ -2864,6 +2921,7 @@ dependencies = [ "arrow-ord", "arrow-schema", "async-trait", + "bytes", "datafusion-common", "datafusion-common-runtime", "datafusion-execution", @@ -2877,19 +2935,21 @@ dependencies = [ "half", "hashbrown 0.17.1", "indexmap 2.14.0", - "itertools 0.14.0", + "itertools 0.15.0", "log", "num-traits", "parking_lot", "pin-project-lite", + "serde", + "serde_json", "tokio", ] [[package]] name = "datafusion-pruning" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb63eeac6de19be40f487b65dd84e546195f783c5a9928618e0c4f2a3569b0d7" +checksum = "f11f0dbe2b5a642f6106e44de8bbd6654fa7220ca14f32313d4efd5514a86968" dependencies = [ "arrow", "datafusion-common", @@ -2903,10 +2963,11 @@ dependencies = [ [[package]] name = "datafusion-session" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f961d209177f91bd014db5cbb2c33b7d28a2597b9003e77f17aeb712964315a" +checksum = "62dc5ce37a5ce1ff5362949776829aded2529a11dbaa13d24b0ffa6a059e106a" dependencies = [ + "arrow-schema", "async-trait", "datafusion-common", "datafusion-execution", @@ -2917,9 +2978,9 @@ dependencies = [ [[package]] name = "datafusion-sql" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1d71cb454da682b2af7488e1fc1ddd72ee1b28f19297b8ccad73f0a21ee9a69" +checksum = "816c224a0ef5469a32a562b5d4830544f714f97c5f50142109286d40a288c7db" dependencies = [ "arrow", "bigdecimal", @@ -3065,13 +3126,34 @@ dependencies = [ "ctutils", ] +[[package]] +name = "directories" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a49173b84e034382284f27f1af4dcbbd231ffa358c0fe316541a7337f376a35" +dependencies = [ + "dirs-sys 0.4.1", +] + [[package]] name = "dirs" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" dependencies = [ - "dirs-sys", + "dirs-sys 0.5.0", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.4.6", + "windows-sys 0.48.0", ] [[package]] @@ -3082,8 +3164,8 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users", - "windows-sys 0.60.2", + "redox_users 0.5.2", + "windows-sys 0.61.2", ] [[package]] @@ -3154,12 +3236,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9" [[package]] -name = "earcutr" -version = "0.4.3" +name = "earcut" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79127ed59a85d7687c409e9978547cffb7dc79675355ed22da6b66fd5f6ead01" +checksum = "88459a2a8e3a514b6e6de38cf3aaa9250a894cb098f74a932db77fcc8341b6d0" dependencies = [ - "itertools 0.11.0", "num-traits", ] @@ -3311,9 +3392,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + [[package]] name = "esaxx-rs" version = "0.1.10" @@ -3396,6 +3483,17 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "fd-lock" +version = "4.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78" +dependencies = [ + "cfg-if 1.0.4", + "rustix 1.1.4", + "windows-sys 0.59.0", +] + [[package]] name = "ff" version = "0.12.1" @@ -3464,9 +3562,9 @@ dependencies = [ [[package]] name = "float_next_after" -version = "1.0.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" +checksum = "37007738a80ea34f969af54a3390dd72cacdef654974cfd449c9f6f72dbaac10" [[package]] name = "fnv" @@ -3486,6 +3584,21 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + [[package]] name = "foreign_vec" version = "0.1.0" @@ -3572,7 +3685,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" dependencies = [ - "rustix", + "rustix 1.1.4", "windows-sys 0.59.0", ] @@ -3584,8 +3697,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "rand 0.9.5", @@ -3855,19 +3968,22 @@ dependencies = [ [[package]] name = "geo" -version = "0.31.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fc1a1678e54befc9b4bcab6cd43b8e7f834ae8ea121118b0fd8c42747675b4a" +checksum = "30eb1fdc57c1e5cfd11826fe0caec4b9dc7901f3758263bb506228d88c8d9e9a" dependencies = [ - "earcutr", + "earcut", "float_next_after", "geo-types", "geographiclib-rs", "i_overlay", "log", "num-traits", + "rand 0.10.1", + "rand_pcg", "robust", "rstar", + "sif-itree", "spade", ] @@ -3891,13 +4007,14 @@ dependencies = [ "rayon", "rstar", "serde", + "spade", ] [[package]] name = "geoarrow-array" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dafe7b7de3fab1a8b7099fd6a6434ca955fa65065f9c19f0f8a133693f3c2b0e" +checksum = "d3e4cb9aceb3985c450742846920af226c3d37249f8d6e70a96cb8fb2aa1c1f7" dependencies = [ "arrow-array", "arrow-buffer", @@ -3911,9 +4028,9 @@ dependencies = [ [[package]] name = "geoarrow-expr-geo" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e4a62ac19c86827c6ec81ea584594b3ee96db5a8119b9774d3466c6b373c434" +checksum = "4d0e3db05f5b28dc0a7e4df1fa507cbfcb08c79098620c306c556d7b030a9dbe" dependencies = [ "arrow-array", "arrow-buffer", @@ -3925,9 +4042,9 @@ dependencies = [ [[package]] name = "geoarrow-schema" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d4a7edb2a1d87024a93805332a9c8184a0354836271d42c0d18cf628a5e3cd0" +checksum = "6ec8b1c883eac8a4f163bfd59c4cbfcc4d857948b7a7a9b38482e537482354c5" dependencies = [ "arrow-schema", "geo-traits", @@ -3938,9 +4055,9 @@ dependencies = [ [[package]] name = "geodatafusion" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fecbdd00d0fff2b04635c1b1e4129c217908f0c2d17539e0a2275308afce2552" +checksum = "6ec9c5155e8679cb1b78e5fd020c17163adf72a032a1bb42b86e10b08cc7a2ae" dependencies = [ "arrow-arith", "arrow-array", @@ -4441,7 +4558,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots 1.0.7", + "webpki-roots 1.0.10", ] [[package]] @@ -4457,6 +4574,22 @@ dependencies = [ "tower-service", ] +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + [[package]] name = "hyper-util" version = "0.1.20" @@ -4493,24 +4626,27 @@ dependencies = [ [[package]] name = "i_float" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "010025c2c532c8d82e42d0b8bb5184afa449fa6f06c709ea9adcb16c49ae405b" +checksum = "813145bb0ad5b60f55cbbf3c74cdceda1c0a9d253b35c4cc36ae0df7887cb78f" dependencies = [ "libm", ] [[package]] name = "i_key_sort" -version = "0.6.0" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9190f86706ca38ac8add223b2aed8b1330002b5cdbbce28fb58b10914d38fc27" +checksum = "d73d122b937fca067feb0ad74f62388920272b27c356d4df2d0cfdd59e044cf0" +dependencies = [ + "rayon", +] [[package]] name = "i_overlay" -version = "4.0.7" +version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413183068e6e0289e18d7d0a1f661b81546e6918d5453a44570b9ab30cbed1b3" +checksum = "8dd314b4668e2b3a12508f2e125558c82a6c0a8636fa5107a900f79ce414e450" dependencies = [ "i_float", "i_key_sort", @@ -4521,18 +4657,18 @@ dependencies = [ [[package]] name = "i_shape" -version = "1.14.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ea154b742f7d43dae2897fcd5ead86bc7b5eefcedd305a7ebf9f69d44d61082" +checksum = "bfa9eac533d7509a8ab87672b60ac610c17240f9ea4851d26227689fdfe349c8" dependencies = [ "i_float", ] [[package]] name = "i_tree" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35e6d558e6d4c7b82bc51d9c771e7a927862a161a7d87bf2b0541450e0e20915" +checksum = "4804bdc1dc124eb7e1aa9e144ecc04096bcf787a10a15fa44af682b51f0f6cce" [[package]] name = "iana-time-zone" @@ -4750,7 +4886,7 @@ dependencies = [ "console", "number_prefix", "portable-atomic", - "unicode-width", + "unicode-width 0.2.2", "web-time", ] @@ -4816,7 +4952,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5059,8 +5195,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arc-swap", "arrow", @@ -5110,6 +5246,7 @@ dependencies = [ "lance-tokenizer", "log", "moka", + "num-traits", "object_store 0.14.2", "permutation", "pin-project", @@ -5134,8 +5271,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5156,8 +5293,8 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" -version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "59.0.0" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5170,8 +5307,8 @@ dependencies = [ [[package]] name = "lance-arrow-stats" -version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "59.0.0" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-schema", @@ -5180,8 +5317,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrayref", "crunchy", @@ -5191,8 +5328,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5229,8 +5366,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "arrow-array", @@ -5246,10 +5383,11 @@ dependencies = [ "datafusion-functions", "datafusion-physical-expr", "futures", + "geodatafusion", "half", "lance-arrow", "lance-core", - "lance-geo", + "lance-datafusion-exec", "lance-jsonb", "log", "pin-project", @@ -5259,10 +5397,36 @@ dependencies = [ "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" +dependencies = [ + "arrow", + "arrow-array", + "arrow-schema", + "async-trait", + "datafusion-common", + "datafusion-execution", + "datafusion-expr", + "datafusion-functions", + "datafusion-physical-expr", + "datafusion-physical-plan", + "futures", + "half", + "lance-arrow", + "lance-core", + "lance-jsonb", + "log", + "pin-project", + "tokio", + "tracing", +] + [[package]] name = "lance-datagen" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "arrow-array", @@ -5279,8 +5443,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "proc-macro2", "quote", @@ -5289,8 +5453,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-arith", "arrow-array", @@ -5315,16 +5479,17 @@ dependencies = [ "num-traits", "prost", "prost-build", + "serde_json", "tokio", "tracing", "xxhash-rust", - "zstd", + "zstd 0.14.3", ] [[package]] name = "lance-file" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-arith", "arrow-array", @@ -5356,23 +5521,21 @@ dependencies = [ [[package]] name = "lance-geo" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ - "datafusion", "geo-traits", "geo-types", "geoarrow-array", "geoarrow-schema", - "geodatafusion", "lance-core", "serde", ] [[package]] name = "lance-index" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arc-swap", "arrow", @@ -5386,12 +5549,16 @@ dependencies = [ "async-recursion", "async-trait", "bitvec", + "blake3", "bytes", "crossbeam-queue", - "datafusion", "datafusion-common", + "datafusion-execution", "datafusion-expr", + "datafusion-functions", + "datafusion-functions-nested", "datafusion-physical-expr", + "datafusion-physical-plan", "dirs", "fst", "futures", @@ -5407,7 +5574,7 @@ dependencies = [ "lance-arrow-stats", "lance-bitpacking", "lance-core", - "lance-datafusion", + "lance-datafusion-exec", "lance-encoding", "lance-file", "lance-geo", @@ -5420,6 +5587,7 @@ dependencies = [ "lance-tokenizer", "libsais-rs", "log", + "nalgebra", "ndarray", "num-traits", "object_store 0.14.2", @@ -5443,16 +5611,16 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-schema", "arrow-select", "async-trait", "bytes", - "datafusion", "datafusion-common", + "datafusion-execution", "datafusion-expr", "futures", "lance-core", @@ -5467,8 +5635,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "arrow-array", @@ -5488,6 +5656,7 @@ dependencies = [ "log", "metrics", "moka", + "nix 0.31.3", "object_store 0.14.2", "object_store_opendal", "opendal", @@ -5507,12 +5676,13 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", ] [[package]] name = "lance-jsonb" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "byteorder", "ethnum", @@ -5529,9 +5699,10 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ + "argminmax 0.7.1", "arrow-array", "arrow-schema", "cc", @@ -5544,8 +5715,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "async-trait", @@ -5559,8 +5730,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arc-swap", "arrow", @@ -5586,7 +5757,7 @@ dependencies = [ "object_store 0.14.2", "quick-xml 0.40.1", "rand 0.9.5", - "reqwest 0.12.28", + "reqwest 0.13.5", "roaring", "serde", "serde_json", @@ -5614,8 +5785,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5629,8 +5800,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "arrow-array", @@ -5651,6 +5822,7 @@ dependencies = [ "lance-io", "lance-select", "log", + "num-traits", "object_store 0.14.2", "prost", "prost-build", @@ -5670,8 +5842,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-schema", @@ -5684,8 +5856,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "frostem", "icu_segmenter", @@ -5698,7 +5870,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.9" +version = "0.41.0-beta.17" dependencies = [ "ahash", "anyhow", @@ -5771,7 +5943,7 @@ dependencies = [ "rand 0.9.5", "random_word", "regex", - "reqwest 0.13.4", + "reqwest 0.13.5", "roaring", "rstest", "semver", @@ -5787,6 +5959,7 @@ dependencies = [ "tokenizers", "tokio", "tonic", + "tracing", "url", "urlencoding", "uuid", @@ -5794,9 +5967,64 @@ dependencies = [ "webbrowser", ] +[[package]] +name = "lancedb-blob-v2-docs" +version = "0.0.0" +dependencies = [ + "arrow-array", + "arrow-schema", + "futures-util", + "lancedb", + "tempfile", + "tokio", +] + +[[package]] +name = "lancedb-cli" +version = "0.1.0" +dependencies = [ + "anyhow", + "arrow-array", + "arrow-buffer", + "arrow-cast", + "arrow-flight", + "arrow-json", + "arrow-schema", + "async-trait", + "axum 0.8.9", + "base64 0.22.1", + "clap", + "csv", + "directories", + "futures", + "half", + "http 1.5.0", + "lancedb", + "prost", + "rcgen", + "reqwest 0.12.28", + "rustls", + "rustyline", + "serde", + "serde_ignored", + "serde_json", + "sha2 0.10.9", + "sqlparser 0.62.0", + "tempfile", + "termsize", + "tokio", + "tokio-stream", + "toml", + "tonic", + "tracing", + "unicode-width 0.2.2", + "url", + "which", +] + [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.9" +version = "0.41.0-beta.17" dependencies = [ "arrow-array", "arrow-buffer", @@ -5821,7 +6049,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.9" +version = "0.41.0-beta.17" dependencies = [ "arc-swap", "arrow", @@ -5831,6 +6059,7 @@ dependencies = [ "datafusion-common", "env_logger", "futures", + "lance-arrow", "lance-core", "lance-io", "lance-namespace", @@ -5923,9 +6152,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libloading" @@ -6027,6 +6256,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "348d0075b1fc163b26d72a7f75fc5141daf2fd1bdf128d873cbaf6785d495bdf" +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -6116,6 +6351,15 @@ dependencies = [ "twox-hash", ] +[[package]] +name = "lz4_flex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" +dependencies = [ + "twox-hash", +] + [[package]] name = "lzma-sys" version = "0.1.20" @@ -6199,9 +6443,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.8.0" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" @@ -6411,10 +6655,25 @@ dependencies = [ ] [[package]] -name = "napi" -version = "3.12.5" +name = "nalgebra" +version = "0.33.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0c007d4a8ead952a81887661d41fd56b7e7a70d3d4d921f445fb37a8f6efa1e" +checksum = "9d43ddcacf343185dfd6de2ee786d9e8b1c2301622afab66b6c73baf9882abfd" +dependencies = [ + "approx", + "matrixmultiply", + "num-complex", + "num-rational", + "num-traits", + "simba", + "typenum", +] + +[[package]] +name = "napi" +version = "3.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a746ad50efbfb632ade1de4025519a477decbbd798cea1a6ac41d7c44f80083" dependencies = [ "bitflags 2.11.1", "chrono", @@ -6432,46 +6691,63 @@ dependencies = [ [[package]] name = "napi-build" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0941983559cd62bfa7f04646a16428967a847365adeef27711e4e3927046bbed" +checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d" [[package]] name = "napi-derive" -version = "3.6.9" +version = "3.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1d232c24dc6754979b27efdf2047a5849efc7c92c1245de87e6bedbb9f5c3c" +checksum = "3ff48271a0f61abb83f3e2d1989fa71169143db95f6f948c3a8903961f2855dc" dependencies = [ "convert_case", "ctor", "napi-derive-backend", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] name = "napi-derive-backend" -version = "6.1.4" +version = "6.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd6856fe1686867da90ed0dc292d7c0c87a695eb7c578b913360f33619ee01e3" +checksum = "f2639052c5aff9956a21d7b6202fc61d5e89c5f19c72d289b7a0641ea94e8159" dependencies = [ "convert_case", "proc-macro2", "quote", "semver", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] name = "napi-sys" -version = "3.4.0" +version = "3.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e22a4f25c16a5c5411d987cd6fbd48313522ae1789ade2d6dd3efdc6d40a0fc8" +checksum = "d153beb7d5c973f4b9395be8a83054a28968b61188f1dd1a2cc2321af22daea2" dependencies = [ "libloading", ] +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + [[package]] name = "ndarray" version = "0.16.1" @@ -6513,6 +6789,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" +dependencies = [ + "bitflags 2.11.1", + "cfg-if 1.0.4", + "cfg_aliases 0.1.1", + "libc", +] + [[package]] name = "nix" version = "0.31.3" @@ -6521,7 +6809,7 @@ checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ "bitflags 2.11.1", "cfg-if 1.0.4", - "cfg_aliases", + "cfg_aliases 0.2.1", "libc", ] @@ -6574,7 +6862,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -6587,6 +6875,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-bigint-dig" version = "0.8.6" @@ -6649,6 +6947,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint 0.4.6", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -6703,7 +7012,7 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" dependencies = [ - "base64 0.21.7", + "base64 0.22.1", "chrono", "getrandom 0.2.17", "http 1.5.0", @@ -6845,7 +7154,7 @@ dependencies = [ "percent-encoding", "quick-xml 0.41.0", "rand 0.10.1", - "reqwest 0.13.4", + "reqwest 0.13.5", "rustls-pki-types", "serde", "serde_json", @@ -6983,7 +7292,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "opendal-core", - "reqwest 0.13.4", + "reqwest 0.13.5", ] [[package]] @@ -7189,12 +7498,49 @@ dependencies = [ "url", ] +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags 2.11.1", + "cfg-if 1.0.4", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "openssl-probe" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + [[package]] name = "option-ext" version = "0.2.0" @@ -7650,7 +7996,7 @@ dependencies = [ "streaming-iterator", "strength_reduce", "version_check", - "zstd", + "zstd 0.13.3", ] [[package]] @@ -7783,7 +8129,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "efdbdb4d9a92109bc2e0ce8e17af5ae8ab643bb5b7ee9d1d74f0aeffd1fbc95f" dependencies = [ "ahash", - "argminmax", + "argminmax 0.6.3", "base64 0.21.7", "bytemuck", "chrono", @@ -8048,7 +8394,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit", + "toml_edit 0.25.11+spec-1.1.0", ] [[package]] @@ -8076,8 +8422,8 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" dependencies = [ - "heck 0.4.1", - "itertools 0.12.1", + "heck 0.5.0", + "itertools 0.14.0", "log", "multimap", "petgraph", @@ -8096,7 +8442,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", - "itertools 0.12.1", + "itertools 0.14.0", "proc-macro2", "quote", "syn 2.0.117", @@ -8166,9 +8512,9 @@ checksum = "40e24eee682d89fb193496edf918a7f407d30175b2e785fe057e4392dfd182e0" [[package]] name = "pyo3" -version = "0.28.3" +version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91fd8e38a3b50ed1167fb981cd6fd60147e091784c427b8f7183a7ee32c31c12" +checksum = "700d18fa267b73b9b521fd7e13580e2f446916f176cacee1ab63fcc8191f1655" dependencies = [ "chrono", "libc", @@ -8182,9 +8528,9 @@ dependencies = [ [[package]] name = "pyo3-async-runtimes" -version = "0.28.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e7364a95bf00e8377bbf9b0f09d7ff9715a29d8fcf93b47d1a967363b973178" +checksum = "b3ef68daa7316a3fac65e5e18b2203f010346de1c1c53456811a2624673ab046" dependencies = [ "futures-channel", "futures-util", @@ -8197,9 +8543,9 @@ dependencies = [ [[package]] name = "pyo3-async-runtimes-macros" -version = "0.28.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c23399970eea9c31d0ac84cee4a9d8dd05f89b1da2f4dd5bb44b32a3f66db4f8" +checksum = "faf75ff3922e6830adcaa30f3a359ce861326f6161f16a13d97adb40ba6a744a" dependencies = [ "proc-macro2", "quote", @@ -8208,18 +8554,18 @@ dependencies = [ [[package]] name = "pyo3-build-config" -version = "0.28.3" +version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e368e7ddfdeb98c9bca7f8383be1648fd84ab466bf2bc015e94008db6d35611e" +checksum = "7b3fc0c4d08f6bb10e71fe39dfb9e2f59c6eb6854e22ec8092f50c69a4499adb" dependencies = [ "target-lexicon", ] [[package]] name = "pyo3-ffi" -version = "0.28.3" +version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f29e10af80b1f7ccaf7f69eace800a03ecd13e883acfacc1e5d0988605f651e" +checksum = "dfc0b8e19df29aad7086cf977bb0c2a2f143e30567eb113e9cf72b62ca698330" dependencies = [ "libc", "pyo3-build-config", @@ -8227,9 +8573,9 @@ dependencies = [ [[package]] name = "pyo3-macros" -version = "0.28.3" +version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df6e520eff47c45997d2fc7dd8214b25dd1310918bbb2642156ef66a67f29813" +checksum = "6100e8a4b5eba53afaa5ed078364851a0b2499c553a44c31026b929049b49dc6" dependencies = [ "proc-macro2", "pyo3-macros-backend", @@ -8239,13 +8585,12 @@ dependencies = [ [[package]] name = "pyo3-macros-backend" -version = "0.28.3" +version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4cdc218d835738f81c2338f822078af45b4afdf8b2e33cbb5916f108b813acb" +checksum = "6143877a16e82b5a727b7127ff4cd86858a24a28d745d72f43e6f227c7b1bdb3" dependencies = [ "heck 0.5.0", "proc-macro2", - "pyo3-build-config", "quote", "syn 2.0.117", ] @@ -8312,7 +8657,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" dependencies = [ "bytes", - "cfg_aliases", + "cfg_aliases 0.2.1", "pin-project-lite", "quinn-proto", "quinn-udp", @@ -8354,12 +8699,12 @@ version = "0.5.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" dependencies = [ - "cfg_aliases", + "cfg_aliases 0.2.1", "libc", "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -8597,6 +8942,18 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "rcgen" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48406db8ac1f3cbc7dcdb56ec355343817958a356ff430259bb07baf7607e1e1" +dependencies = [ + "pem", + "ring", + "time", + "yasna", +] + [[package]] name = "reborrow" version = "0.5.5" @@ -8641,6 +8998,17 @@ dependencies = [ "bitflags 2.11.1", ] +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + [[package]] name = "redox_users" version = "0.5.2" @@ -8883,11 +9251,13 @@ dependencies = [ "http-body-util", "hyper", "hyper-rustls", + "hyper-tls", "hyper-util", "js-sys", "log", "mime", "mime_guess", + "native-tls", "percent-encoding", "pin-project-lite", "quinn", @@ -8899,6 +9269,7 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", + "tokio-native-tls", "tokio-rustls", "tokio-util", "tower", @@ -8909,16 +9280,16 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams 0.4.2", "web-sys", - "webpki-roots 1.0.7", + "webpki-roots 1.0.10", ] [[package]] name = "reqwest" -version = "0.13.4" +version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "bytes", "encoding_rs", "futures-core", @@ -8981,7 +9352,7 @@ dependencies = [ "anyhow", "async-trait", "http 1.5.0", - "reqwest 0.13.4", + "reqwest 0.13.5", "thiserror 2.0.18", "tower-service", ] @@ -9159,6 +9530,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.11.1", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + [[package]] name = "rustix" version = "1.1.4" @@ -9168,8 +9552,8 @@ dependencies = [ "bitflags 2.11.1", "errno", "libc", - "linux-raw-sys", - "windows-sys 0.52.0", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", ] [[package]] @@ -9228,7 +9612,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -9239,9 +9623,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -9255,6 +9639,28 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +[[package]] +name = "rustyline" +version = "14.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7803e8936da37efd9b6d4478277f4b2b9bb5cdb37a113e8d63222e58da647e63" +dependencies = [ + "bitflags 2.11.1", + "cfg-if 1.0.4", + "clipboard-win", + "fd-lock", + "home", + "libc", + "log", + "memchr", + "nix 0.28.0", + "radix_trie", + "unicode-segmentation", + "unicode-width 0.1.14", + "utf8parse", + "windows-sys 0.52.0", +] + [[package]] name = "ryu" version = "1.0.23" @@ -9267,6 +9673,15 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3944826ff8fa8093089aba3acb4ef44b9446a99a16f3bf4e74af3f77d340ab7d" +[[package]] +name = "safe_arch" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323" +dependencies = [ + "bytemuck", +] + [[package]] name = "safetensors" version = "0.7.0" @@ -9442,11 +9857,22 @@ dependencies = [ ] [[package]] -name = "serde_json" -version = "1.0.151" +name = "serde_ignored" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798" dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash 0.2.0", "indexmap 2.14.0", "itoa", "memchr", @@ -9486,6 +9912,15 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -9645,6 +10080,12 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +[[package]] +name = "sif-itree" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7f45b8998ced5134fb1d75732c77842a3e888f19c1ff98481822e8fbfbf930b" + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -9675,6 +10116,19 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simba" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c99284beb21666094ba2b75bbceda012e610f5479dfcc2d6e2426f53197ffd95" +dependencies = [ + "approx", + "num-complex", + "num-traits", + "paste", + "wide", +] + [[package]] name = "simd-adler32" version = "0.3.9" @@ -9756,7 +10210,7 @@ version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.117", @@ -9768,7 +10222,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54254b8531cafa275c5e096f62d48c81435d1015405a91198ddb11e967301d40" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.117", @@ -10191,8 +10645,18 @@ dependencies = [ "fastrand", "getrandom 0.4.2", "once_cell", - "rustix", - "windows-sys 0.52.0", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "termsize" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f11ff5c25c172608d5b85e2fb43ee9a6d683a7f4ab7f96ae07b3d8b590368fd" +dependencies = [ + "libc", + "winapi", ] [[package]] @@ -10395,9 +10859,9 @@ dependencies = [ [[package]] name = "tokio" -version = "1.53.1" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -10421,6 +10885,16 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + [[package]] name = "tokio-retry" version = "0.3.1" @@ -10491,6 +10965,27 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + [[package]] name = "toml_datetime" version = "1.1.1+spec-1.1.0" @@ -10500,6 +10995,20 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap 2.14.0", + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + [[package]] name = "toml_edit" version = "0.25.11+spec-1.1.0" @@ -10507,9 +11016,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b" dependencies = [ "indexmap 2.14.0", - "toml_datetime", + "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", - "winnow", + "winnow 1.0.3", ] [[package]] @@ -10518,9 +11027,15 @@ version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" dependencies = [ - "winnow", + "winnow 1.0.3", ] +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "tonic" version = "0.14.6" @@ -10806,6 +11321,12 @@ version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + [[package]] name = "unicode-width" version = "0.2.2" @@ -10900,9 +11421,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.26.1" +version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ "getrandom 0.4.2", "js-sys", @@ -10917,6 +11438,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -11127,9 +11654,9 @@ dependencies = [ [[package]] name = "webbrowser" -version = "1.2.4" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94" +checksum = "d2c8ddfbbf66e501434657400268cefe51b95140a0266236415cda7627732df7" dependencies = [ "jni", "log", @@ -11143,9 +11670,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.7" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31141ce3fc3e300ae89b78c0dd67f9708061d1d2eda54b8209346fd6be9a92c" +checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" dependencies = [ "rustls-pki-types", ] @@ -11156,18 +11683,30 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.7", + "webpki-roots 1.0.10", ] [[package]] name = "webpki-roots" -version = "1.0.7" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] +[[package]] +name = "which" +version = "6.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" +dependencies = [ + "either", + "home", + "rustix 0.38.44", + "winsafe", +] + [[package]] name = "whoami" version = "2.1.2" @@ -11181,6 +11720,16 @@ dependencies = [ "web-sys", ] +[[package]] +name = "wide" +version = "0.7.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03" +dependencies = [ + "bytemuck", + "safe_arch", +] + [[package]] name = "winapi" version = "0.3.9" @@ -11203,7 +11752,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -11343,6 +11892,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows-sys" version = "0.52.0" @@ -11379,6 +11937,21 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + [[package]] name = "windows-targets" version = "0.52.6" @@ -11421,6 +11994,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -11433,6 +12012,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" @@ -11445,6 +12030,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -11469,6 +12060,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + [[package]] name = "windows_i686_msvc" version = "0.52.6" @@ -11481,6 +12078,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" @@ -11493,6 +12096,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" @@ -11505,6 +12114,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -11517,6 +12132,15 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "winnow" version = "1.0.3" @@ -11526,6 +12150,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + [[package]] name = "wit-bindgen" version = "0.51.0" @@ -11677,7 +12307,7 @@ dependencies = [ "more-asserts", "rand 0.10.1", "redb", - "reqwest 0.13.4", + "reqwest 0.13.5", "reqwest-middleware", "serde", "serde_json", @@ -11713,7 +12343,7 @@ dependencies = [ "getrandom 0.4.2", "heapify", "itertools 0.14.0", - "lz4_flex", + "lz4_flex 0.13.1", "more-asserts", "rand 0.10.1", "regex", @@ -11784,7 +12414,7 @@ dependencies = [ "oneshot", "pin-project", "rand 0.10.1", - "reqwest 0.13.4", + "reqwest 0.13.5", "serde", "serde_json", "shellexpand", @@ -11813,6 +12443,15 @@ version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" +[[package]] +name = "yasna" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" +dependencies = [ + "time", +] + [[package]] name = "yoke" version = "0.8.2" @@ -11942,7 +12581,16 @@ version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" dependencies = [ - "zstd-safe", + "zstd-safe 7.2.4", +] + +[[package]] +name = "zstd" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70" +dependencies = [ + "zstd-safe 8.2.0", ] [[package]] @@ -11955,10 +12603,19 @@ dependencies = [ ] [[package]] -name = "zstd-sys" -version = "2.0.16+zstd.1.5.7" +name = "zstd-safe" +version = "8.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" dependencies = [ "cc", "pkg-config", diff --git a/Cargo.toml b/Cargo.toml index e302d2891..ce5a5edae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,11 @@ [workspace] -members = ["rust/lancedb", "nodejs", "python"] +members = [ + "rust/lancedb/cli", + "rust/lancedb", + "nodejs", + "python", + "docs/web-tests/blob-v2/rs", +] resolver = "2" [workspace.package] @@ -10,60 +16,66 @@ repository = "https://github.com/lancedb/lancedb" description = "Serverless, low-latency vector database for AI applications" keywords = ["lancedb", "lance", "database", "vector", "search"] categories = ["database-implementations"] -rust-version = "1.94.0" +rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +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" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" +anyhow = "1" # Note that this one does not include pyarrow -arrow = { version = "58.0.0", optional = false } -arrow-array = "58.0.0" -arrow-buffer = "58.0.0" -arrow-data = "58.0.0" -arrow-ipc = "58.0.0" -arrow-ord = "58.0.0" -arrow-schema = "58.0.0" -arrow-select = "58.0.0" -arrow-cast = "58.0.0" -arrow-flight = { version = "58.0.0", features = ["flight-sql-experimental"] } +arrow = { version = "59.2.0", optional = false } +arrow-array = "59.2.0" +arrow-buffer = "59.2.0" +arrow-data = "59.2.0" +arrow-ipc = "59.2.0" +arrow-ord = "59.2.0" +arrow-schema = "59.2.0" +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" +base64 = "0.22" bytes = "1" -datafusion = { version = "54.0.0", default-features = false } -datafusion-catalog = "54.0.0" -datafusion-common = { version = "54.0.0", default-features = false } -datafusion-execution = "54.0.0" -datafusion-expr = "54.0.0" -datafusion-functions = "54.0.0" -datafusion-physical-plan = "54.0.0" -datafusion-physical-expr = "54.0.0" -datafusion-sql = "54.0.0" +datafusion = { version = "55.0.0", default-features = false } +datafusion-catalog = "55.0.0" +datafusion-common = { version = "55.0.0", default-features = false } +datafusion-execution = "55.0.0" +datafusion-expr = "55.0.0" +datafusion-functions = "55.0.0" +datafusion-physical-plan = "55.0.0" +datafusion-physical-expr = "55.0.0" +datafusion-sql = "55.0.0" env_logger = "0.11" half = { "version" = "2.7.1", default-features = false, features = [ "num-traits", ] } futures = "0.3" +hf-hub = { version = "0.4.1", default-features = false } +http = "1" log = "0.4" metrics = "0.24" metrics-util = "0.19" moka = { version = "0.12", features = ["future"] } object_store = "0.14.1" pin-project = "1.0.7" +prost = "0.14" rand = "0.9" snafu = "0.8" url = "2" @@ -73,9 +85,12 @@ regex = "1.10" semver = "1.0.25" serde = "1" serde_json = { version = "1", features = ["preserve_order"] } +serial_test = "3" +sha2 = "0.10" tempfile = "3.5.0" tokio = { version = "1.23", features = ["rt-multi-thread", "sync"] } tonic = { version = "0.14", features = ["tls-native-roots", "tls-aws-lc"] } +tracing = "0.1" uuid = { version = "1.7.0", features = ["v4", "v7"] } chrono = { version = "0.4", default-features = false, features = ["clock"] } diff --git a/README.md b/README.md index 7bf5d39fc..ea9431298 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,8 @@ LanceDB is a central location where developers can build, train and analyze thei - **Advanced Features**: Zero-copy, automatic versioning, manage versions of your data without needing extra infrastructure. GPU support in building vector index. ### **Products**: -- **Open Source & Local**: 100% open source, runs locally or in your cloud. No vendor lock-in. -- **Cloud and Enterprise**: Production-scale vector search with no servers to manage. Complete data sovereignty and security. +- **LanceDB Embedded (open source)**: 100% open source, runs in your application's process; your data can live on local disk or in object storage. No vendor lock-in. +- **LanceDB Enterprise**: Production-scale distributed search, indexing, and maintenance. Plus, complete data sovereignty and security. ### **Ecosystem**: - **Columnar Storage**: Built on the Lance columnar format for efficient storage and analytics. diff --git a/ci/check_cargo_lock.py b/ci/check_cargo_lock.py index 551b76794..94cb10aec 100644 --- a/ci/check_cargo_lock.py +++ b/ci/check_cargo_lock.py @@ -1,4 +1,7 @@ -"""Fail if pruning Cargo.lock did more than remove packages and the edges to them. +"""Fail if pruning Cargo.lock changes pins or adds dependency edges. + +Removing workspace members can disable optional dependency edges even when +their target packages remain in use elsewhere in the packaged workspace. Usage: python ci/check_cargo_lock.py """ @@ -45,7 +48,7 @@ def main() -> None: for package, deps in edges_after.items(): if package not in edges_before: errors.append(f"added or changed {package}") - elif deps != edges_before[package] - removed: + elif not deps <= edges_before[package]: errors.append(f"dependencies of {package[:2]} changed") if errors: sys.exit("error: the prune changed Cargo.lock:\n" + "\n".join(errors)) diff --git a/ci/set_lance_version.py b/ci/set_lance_version.py index c7bf41f55..bef97f8ad 100644 --- a/ci/set_lance_version.py +++ b/ci/set_lance_version.py @@ -2,6 +2,8 @@ import argparse import re import sys import json +import tomllib +from pathlib import Path LANCE_GIT_URL = "https://github.com/lance-format/lance.git" @@ -148,6 +150,18 @@ def update_cargo_toml(line_updater): with open("Cargo.toml", "w") as f: f.writelines(new_lines) + core_manifest = Path("rust/lancedb/Cargo.toml") + if core_manifest.exists(): + lines = core_manifest.read_text().splitlines(keepends=True) + for index, line in enumerate(lines): + if line.startswith("lance-arrow ="): + updated = tomllib.loads(line_updater(line))["lance-arrow"] + config = {"version": updated} if isinstance(updated, str) else updated + if "path" in config: + config["path"] = "../../" + config["path"] + lines[index] = dict_to_toml_line("lance-arrow", config) + core_manifest.write_text("".join(lines)) + def set_stable_version(version: str): """ diff --git a/ci/tests/test_check_cargo_lock.py b/ci/tests/test_check_cargo_lock.py index 82570d087..8ffcebd87 100644 --- a/ci/tests/test_check_cargo_lock.py +++ b/ci/tests/test_check_cargo_lock.py @@ -37,14 +37,15 @@ APP = package("app", "1.0.0", ["libc", "untrusted"], source=None) class CheckCargoLockTest(unittest.TestCase): - def run_check(self, after, header="version = 4\n\n"): + def run_check(self, after, header="version = 4\n\n", before=BEFORE): with tempfile.TemporaryDirectory() as tmp: before_path = Path(tmp, "before.lock") after_path = Path(tmp, "after.lock") - before_path.write_text(BEFORE) + before_path.write_text(before) after_path.write_text(header + after) return subprocess.run( [sys.executable, SCRIPT, before_path, after_path], + check=False, capture_output=True, text=True, ) @@ -81,9 +82,36 @@ class CheckCargoLockTest(unittest.TestCase): self.assertNotEqual(result.returncode, 0) self.assertIn("dependencies of ('libc'", result.stderr) - def test_removed_dependency_fails(self): + def test_removed_dependency_passes(self): app = package("app", "1.0.0", ["untrusted"], source=None) result = self.run_check(app + LIBC + UNTRUSTED) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_disabled_optional_dependency_still_used_elsewhere_passes(self): + # Removing the CLI disables axum's tracing feature, but other SDK + # dependencies still need tracing. Its package therefore stays pinned. + app = package("app", "1.0.0", ["axum", "tracing"], source=None) + tracing = package("tracing", "0.1.44") + before = ( + "version = 4\n\n" + app + package("axum", "0.8.9", ["tracing"]) + tracing + ) + after = app + package("axum", "0.8.9") + tracing + result = self.run_check(after, before=before) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_dependency_redirected_to_an_existing_version_fails(self): + before = ( + "version = 4\n\n" + + package("app", "1.0.0", ["untrusted 0.7.1"], source=None) + + package("untrusted", "0.7.1") + + UNTRUSTED + ) + after = ( + package("app", "1.0.0", ["untrusted 0.9.0"], source=None) + + package("untrusted", "0.7.1") + + UNTRUSTED + ) + result = self.run_check(after, before=before) self.assertNotEqual(result.returncode, 0) self.assertIn("dependencies of ('app'", result.stderr) diff --git a/ci/tests/test_python_dependencies.py b/ci/tests/test_python_dependencies.py new file mode 100644 index 000000000..97fb672c6 --- /dev/null +++ b/ci/tests/test_python_dependencies.py @@ -0,0 +1,47 @@ +import tomllib +import unittest +from pathlib import Path + +from packaging.requirements import Requirement +from packaging.version import Version + + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +class PythonDependenciesTest(unittest.TestCase): + def setUp(self): + with (REPO_ROOT / "python/pyproject.toml").open("rb") as f: + self.project = tomllib.load(f)["project"] + self.pylance = Requirement(self.project["optional-dependencies"]["pylance"][0]) + + def test_pylance_extra_excludes_older_lance_majors(self): + with (REPO_ROOT / "Cargo.toml").open("rb") as f: + lance = tomllib.load(f)["workspace"]["dependencies"]["lance"] + if "version" not in lance: + self.skipTest("Local Lance checkout has no version requirement") + major = Version(lance["version"].lstrip("=")).major + for older_major in range(major): + for suffix in (".0.0", ".0.0b6", ".999.999"): + version = f"{older_major}{suffix}" + with self.subTest(version=version): + self.assertFalse( + self.pylance.specifier.contains(version, prereleases=True), + f"The pylance extra must exclude Lance {version}; " + f"the bundled Lance is major {major}", + ) + + def test_pylance_extra_accepts_tested_version(self): + requirements = [ + Requirement(dep) for dep in self.project["optional-dependencies"]["tests"] + ] + tested = next(dep for dep in requirements if dep.name == "pylance") + pin = next(spec for spec in tested.specifier if spec.operator == "==") + self.assertTrue( + self.pylance.specifier.contains(pin.version, prereleases=True), + f"The tests and pylance extras must be installable together: {tested}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/ci/tests/test_set_lance_version.py b/ci/tests/test_set_lance_version.py index 1493fc59d..1173eab84 100644 --- a/ci/tests/test_set_lance_version.py +++ b/ci/tests/test_set_lance_version.py @@ -4,6 +4,7 @@ import subprocess import sys import tempfile import textwrap +import tomllib import unittest from pathlib import Path @@ -83,6 +84,13 @@ lance_datafusion = {{ "version" = "=8.2.0-beta.4", "features" = ["substrait"], " with self.subTest(version=version), tempfile.TemporaryDirectory() as tmp: workdir = Path(tmp) (workdir / "Cargo.toml").write_text(CARGO_TOML) + core_manifest = workdir / "rust/lancedb/Cargo.toml" + core_manifest.parent.mkdir(parents=True) + core_manifest.write_text( + "[dependencies]\nlance-arrow = { " + 'version = "=1.0.0", git = "https://github.com/lance-format/lance.git", ' + 'tag = "v1.0.0" }\narrow.workspace = true\n' + ) command_log = workdir / "commands.log" fake_bin = workdir / "bin" fake_bin.mkdir() @@ -111,6 +119,26 @@ lance_datafusion = {{ "version" = "=8.2.0-beta.4", "features" = ["substrait"], " + updated_dependencies + UNTOUCHED_DEPENDENCIES, ) + core = tomllib.loads(core_manifest.read_text())["dependencies"] + dependency = core["lance-arrow"] + if isinstance(dependency, str): + dependency = {"version": dependency} + if version == "local": + self.assertEqual( + dependency["path"], "../../../lance/rust/lance-arrow" + ) + else: + expected_version = { + "stable": "9.9.9", + "preview": "10.0.0-beta.3", + }.get(version, version.removeprefix("v")) + self.assertEqual(dependency["version"], f"={expected_version}") + if "beta" in expected_version: + self.assertEqual(dependency["git"], LANCE_GIT_URL) + self.assertEqual(dependency["tag"], f"v{expected_version}") + else: + self.assertNotIn("git", dependency) + self.assertEqual(core["arrow"], {"workspace": True}) commands = command_log.read_text().splitlines() for command in expected_commands: self.assertTrue( diff --git a/deny.toml b/deny.toml index 7d60ae63f..602cc2820 100644 --- a/deny.toml +++ b/deny.toml @@ -110,8 +110,30 @@ ignore = [ # compact_str/smol_str, so clearing this requires polars to migrate. # https://rustsec.org/advisories/RUSTSEC-2026-0249 { id = "RUSTSEC-2026-0249", reason = "smartstring unmaintained via polars; no fixed upstream release" }, + # crypto-bigint < 0.7.6: timing side-channels in constant-time ops, + # incl. subtraction, zero counting, division and Montgomery multiplication. + # Reached only through aws-sdk-s3 sigv4a -> aws-sigv4 (p256/ecdsa); signed + # requests carry the SigV4a credential-derived key. The patched 0.7.6 was + # published 2026-10-23, but no published aws-sigv4 release uses it yet + # (latest 1.6.3 pins crypto-bigint ^0.5), so clearing requires smithy-rs to + # ship an updated aws-sigv4. + # https://rustsec.org/advisories/RUSTSEC-2026-0387 + { id = "RUSTSEC-2026-0387", reason = "crypto-bigint via aws-sigv4 (sigv4a); no fixed upstream aws-sigv4 release yet" }, + + # zstd: arrow-ipc 58.x pins zstd ^0.13, while the patches require zstd + # >=0.14.3 and zstd-safe >=8.2.0. Arrow 59+ updates the dependency, but it + # cannot be used until DataFusion and Lance move to the matching Arrow line. + # LanceDB uses zstd::bulk through arrow-ipc and does not use the affected + # with_context, seekable, or decompress_stream APIs. + # https://rustsec.org/advisories/RUSTSEC-2026-0391 + # https://rustsec.org/advisories/RUSTSEC-2026-0398 + # https://rustsec.org/advisories/RUSTSEC-2026-0403 + { 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" }, ] + # --------------------------------------------------------------------------- # Licenses: only allow licenses we've reviewed as compatible with Apache-2.0. # --------------------------------------------------------------------------- @@ -167,7 +189,9 @@ wildcards = "deny" # `[workspace.dependencies]` table: any crate used by more than one member must # go through `workspace = true`, and entries nothing uses are an error. This # keeps versions from drifting between the core crate and the bindings. -workspace-dependencies = { duplicates = "deny", unused = "deny" } +# Python bundles a patched path crate while the Rust SDK uses the overridable +# upstream source. Check shared external declarations, not these path bindings. +workspace-dependencies = { duplicates = "deny", unused = "deny", include-path-dependencies = false } # Internal workspace crates reference each other via `path = "..."`, which # cargo-deny sees as a wildcard version. That's fine for private workspace # members (not published to crates.io), so allow it specifically for paths. diff --git a/docs/README.md b/docs/README.md index c5a99943d..5e434c520 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,10 +1,13 @@ # LanceDB Documentation -LanceDB docs are available at [docs.lancedb.com](https://docs.lancedb.com). +For website guides in `docs/web`, start with +[Documentation in CONTRIBUTING.md](../CONTRIBUTING.md#documentation). That +covers editing pages, generated examples, previews, availability and drafts. -The SDK docs are built and deployed automatically by [Github Actions](../.github/workflows/docs.yml) -whenever a commit is pushed to the `main` branch. So it is possible for the docs to show -unreleased features. +This page covers the SDK reference in `docs/src`, built with MkDocs. Its +[GitHub Actions workflow](../.github/workflows/docs.yml) builds and deploys on +pushes to `main`, so it can include unreleased APIs. That is separate from the +release editions of the Mintlify website. ## Building the docs diff --git a/docs/openapi.yml b/docs/openapi.yml index e619aa038..0eb5e02b8 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -1,9 +1,9 @@ openapi: 3.1.0 info: version: 1.0.0 - title: LanceDB Cloud API + title: LanceDB REST API description: | - LanceDB Cloud API is a RESTful API that allows users to access and modify data stored in LanceDB Cloud. + The LanceDB REST API is a RESTful API that allows users to access and modify data stored in LanceDB Enterprise or LanceDB Cloud (legacy). Table actions are considered temporary resource creations and all use POST method. contact: name: LanceDB support @@ -12,7 +12,7 @@ info: servers: - url: https://{db}.{region}.api.lancedb.com - description: LanceDB Cloud REST endpoint. + description: LanceDB Cloud (legacy) REST endpoint. For LanceDB Enterprise, use your deployment's endpoint. variables: db: default: "" diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 7a9a89641..4bac3f752 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -1,10 +1,10 @@ # Java SDK -The LanceDB Java SDK provides a convenient way to interact with LanceDB Cloud and Enterprise deployments using the Lance REST Namespace API. +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 for LanceDB remote database that connects to LanceDB Cloud and Enterprise. - Local database support is a work in progress. Check [LANCEDB-2848](https://github.com/lancedb/lancedb/issues/2848) for the latest progress. + The Java SDK currently only works with LanceDB Distributed, connecting 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,13 +14,13 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.41.0-beta.9 + 0.41.0-beta.17 ``` ## Quick Start -### Connecting to LanceDB Cloud +### Connecting to LanceDB Cloud (legacy) ```java import com.lancedb.LanceDbNamespaceClientBuilder; @@ -51,8 +51,8 @@ LanceNamespace namespaceClient = LanceDbNamespaceClientBuilder.newBuilder() |--------|-------------|----------| | `apiKey(String)` | LanceDB API key | Yes | | `database(String)` | Database name | Yes | -| `endpoint(String)` | Custom endpoint URL for Enterprise deployments | No | -| `region(String)` | AWS region (default: "us-east-1") | No | +| `endpoint(String)` | Custom endpoint URL for LanceDB Enterprise deployments | No | +| `region(String)` | LanceDB Cloud (legacy) region (default: "us-east-1") | No | | `config(String, String)` | Additional configuration parameters | No | ### Opening a Table with Vended Credentials diff --git a/docs/src/js/_media/CONTRIBUTING.md b/docs/src/js/_media/CONTRIBUTING.md index 2faa8cd37..2125cc8aa 100644 --- a/docs/src/js/_media/CONTRIBUTING.md +++ b/docs/src/js/_media/CONTRIBUTING.md @@ -50,6 +50,19 @@ pnpm install pnpm build ``` +Local SQL computed columns and materialized-view creation/refresh are experimental +and disabled in published packages. To opt in when building from this directory: + +```shell +pnpm build:debug --features experimental-functions +pnpm tsc +pnpm test --runInBand table.test.ts materialized_view.test.ts +``` + +Rebuild without `--features experimental-functions` to test the default package. +The tests detect the compiled feature; remote operations, metadata protections, +and ordinary eager `addColumns` transforms remain available in both builds. + Lint: ```shell diff --git a/docs/src/js/classes/AutoQuery.md b/docs/src/js/classes/AutoQuery.md index f12668b90..60f568e07 100644 --- a/docs/src/js/classes/AutoQuery.md +++ b/docs/src/js/classes/AutoQuery.md @@ -469,29 +469,34 @@ where(predicate): this A filter statement to be applied to this query. -The filter should be supplied as an SQL query string. For example: +The filter may be an SQL query string or an expression built with `col`, +which preserves case-sensitive column names. For example: #### Parameters -* **predicate**: `string` +* **predicate**: `string` \| [`Expr`](Expr.md) #### Returns `this` -#### Example +#### Examples ```ts x > 10 y > 0 AND y < 100 x > 5 OR y = 'test' +``` + +```ts +table.query().where(col("firstName").eq("Alice")); +``` Filtering performance can often be improved by creating a scalar index on the filter column(s). Calling this multiple times combines the filters with a logical AND rather than replacing the previous filter. -``` #### Inherited from diff --git a/docs/src/js/classes/Catalog.md b/docs/src/js/classes/Catalog.md index 8351380e2..31d3aabc6 100644 --- a/docs/src/js/classes/Catalog.md +++ b/docs/src/js/classes/Catalog.md @@ -70,7 +70,9 @@ Create a database, or open an existing database when existOk is true. dropDatabase(name, options): Promise ``` -Drop an empty database. The server rejects nonempty databases. +Drop a database. A nonempty database is an error unless `cascade` is set, +which drops everything in it first; the name stays taken until the server +finishes cleaning up their storage. #### Parameters @@ -78,6 +80,8 @@ Drop an empty database. The server rejects nonempty databases. * **options** = `{}` +* **options.cascade?**: `boolean` + * **options.ignoreMissing?**: `boolean` #### Returns diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index d5ab8c3d1..14f283cc9 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -180,6 +180,10 @@ abstract createMaterializedView( 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. + The view is populated before creation returns. Set `withNoData` to create only its definition and empty backing table. The view is a normal table: it can be queried, indexed and searched, and it appears in `tableNames`. @@ -432,8 +436,8 @@ abstract dropMaterializedView(name, namespacePath?): Promise Drop the materialized view named `name`. -The view may become unavailable before physical cleanup finishes. Use -[dropMaterializedViewAsync](Connection.md#dropmaterializedviewasync) to retain and wait for the cleanup job. +Remote drops wait for the SQL command to remove the catalog binding. +Physical cleanup continues in the background. Rejects a table that exists but is not a materialized view. @@ -455,8 +459,9 @@ Rejects a table that exists but is not a materialized view. abstract dropMaterializedViewAsync(name, namespacePath?): Promise ``` -Start dropping the materialized view named `name` and return its cleanup -job without waiting for completion. +Start dropping the materialized view named `name` and return its job. +Remote jobs have type `query` and use the SQL query ID as `id`. Waiting +confirms catalog removal; physical cleanup continues in the background. Rejects a table that exists but is not a materialized view. @@ -653,94 +658,48 @@ See [Listing](Listing.md) for pagination state and error behavior. ### listNamespaces() ```ts -abstract listNamespaces(namespacePath?, options?): Promise +abstract listNamespaces(namespacePath?, options?): Listing ``` -List the immediate child namespaces under the given parent. - -Results may be paginated. To retrieve subsequent pages, pass the -`pageToken` returned by a previous call. +Lazily list immediate child namespaces, 100 per page by default. #### Parameters * **namespacePath?**: `string`[] - The parent namespace path. Defaults - to the root namespace if omitted. -* **options?**: `Partial`<[`ListNamespacesOptions`](../interfaces/ListNamespacesOptions.md)> - Pagination options - (`pageToken`, `limit`). +* **options?**: [`ListingOptions`](../interfaces/ListingOptions.md) #### Returns -`Promise`<[`ListNamespacesResponse`](../interfaces/ListNamespacesResponse.md)> - -Child namespace names and - an optional token for fetching the next page. +[`Listing`](Listing.md)<`string`> *** ### listTables() -#### listTables(options) - ```ts -abstract listTables(options?): Promise +abstract listTables(namespacePath?, options?): Listing ``` -List a page of the tables in this database. +Lazily list tables in a namespace, requesting 100 per page by default. -To retrieve the tables after the page, pass the `pageToken` the response -carries back in. A page can be shorter than `limit` without being the last -one, so walk until a response carries no page token: - -```ts -const names = []; -let pageToken = undefined; -do { - const page = await conn.listTables({ pageToken, limit: 100 }); - names.push(...page.tables); - pageToken = page.pageToken; -} while (pageToken); -``` - -##### Parameters - -* **options?**: `Partial`<[`ListTablesOptions`](../interfaces/ListTablesOptions.md)> - Pagination options - (`pageToken`, `limit`). - -##### Returns - -`Promise`<[`ListTablesResponse`](../interfaces/ListTablesResponse.md)> - -A page of table names and an - optional token for the tables after it. - -#### listTables(namespacePath, options) - -```ts -abstract listTables(namespacePath?, options?): Promise -``` - -List a page of the tables in this database. - -##### Parameters +#### Parameters * **namespacePath?**: `string`[] - The namespace path to list tables from - (defaults to root namespace) -* **options?**: `Partial`<[`ListTablesOptions`](../interfaces/ListTablesOptions.md)> - Pagination options - (`pageToken`, `limit`). +* **options?**: [`ListingOptions`](../interfaces/ListingOptions.md) -##### Returns +#### Returns -`Promise`<[`ListTablesResponse`](../interfaces/ListTablesResponse.md)> +[`Listing`](Listing.md)<`string`> -A page of table names and an - optional token for the tables after it. +#### Example + +```ts +for await (const name of conn.listTables([], { pageLimit: 20 })) { + console.log(name); +} +``` *** @@ -868,7 +827,7 @@ abstract renameTable( Rename a table. -Currently only supported by LanceDB Cloud. Local OSS connections and +Currently only supported in LanceDB Distributed. LanceDB Embedded connections and namespace-backed connections (via [connectNamespace](../functions/connectNamespace.md)) reject with a "not supported" error. diff --git a/docs/src/js/classes/Expr.md b/docs/src/js/classes/Expr.md new file mode 100644 index 000000000..7342cf793 --- /dev/null +++ b/docs/src/js/classes/Expr.md @@ -0,0 +1,365 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / Expr + +# Class: Expr + +A SQL expression backed by the shared LanceDB expression builder. + +## Example + +```ts +table.query().where(col("firstName").eq("Alice")).toArray(); +``` + +## Constructors + +### new Expr() + +```ts +new Expr(inner): Expr +``` + +#### Parameters + +* **inner**: `Expr` + +#### Returns + +[`Expr`](Expr.md) + +## Properties + +### inner + +```ts +inner: Expr; +``` + +## Methods + +### add() + +```ts +add(other): Expr +``` + +Add a value. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### and() + +```ts +and(other): Expr +``` + +Combine two predicates with AND. + +#### Parameters + +* **other**: [`Expr`](Expr.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### cast() + +```ts +cast(dataType): Expr +``` + +Cast to an Arrow data type, such as "Int64". + +#### Parameters + +* **dataType**: `string` + +#### Returns + +[`Expr`](Expr.md) + +*** + +### contains() + +```ts +contains(substr): Expr +``` + +Test whether a string contains a substring. + +#### Parameters + +* **substr**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### div() + +```ts +div(other): Expr +``` + +Divide by a value. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### eq() + +```ts +eq(other): Expr +``` + +Compare for equality. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### gt() + +```ts +gt(other): Expr +``` + +Compare for greater than. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### gte() + +```ts +gte(other): Expr +``` + +Compare for greater than or equal to. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### isIn() + +```ts +isIn(values): Expr +``` + +Test membership in a list of values. + +#### Parameters + +* **values**: [`ExprLike`](../type-aliases/ExprLike.md)[] + +#### Returns + +[`Expr`](Expr.md) + +*** + +### lower() + +```ts +lower(): Expr +``` + +Convert a string to lowercase. + +#### Returns + +[`Expr`](Expr.md) + +*** + +### lt() + +```ts +lt(other): Expr +``` + +Compare for less than. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### lte() + +```ts +lte(other): Expr +``` + +Compare for less than or equal to. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### mul() + +```ts +mul(other): Expr +``` + +Multiply by a value. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### ne() + +```ts +ne(other): Expr +``` + +Compare for inequality. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### not() + +```ts +not(): Expr +``` + +Negate this predicate. + +#### Returns + +[`Expr`](Expr.md) + +*** + +### or() + +```ts +or(other): Expr +``` + +Combine two predicates with OR. + +#### Parameters + +* **other**: [`Expr`](Expr.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### sub() + +```ts +sub(other): Expr +``` + +Subtract a value. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### toSql() + +```ts +toSql(): string +``` + +Serialize with the LanceDB SQL dialect, preserving column case. + +#### Returns + +`string` + +*** + +### upper() + +```ts +upper(): Expr +``` + +Convert a string to uppercase. + +#### Returns + +[`Expr`](Expr.md) diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md index cfbe454ec..74e1c00e2 100644 --- a/docs/src/js/classes/Job.md +++ b/docs/src/js/classes/Job.md @@ -17,7 +17,8 @@ extra round trip on every call: - [Job.refresh](Job.md#refresh) and [Job.status](Job.md#status) fetch the whole record. - [Job.wait](Job.md#wait) records the terminal state it establishes, but not the rest of the record. -- Everything is null until one of those runs. +- Registry details are null until one of those runs. Query handles report + jobType "query" immediately. ## Accessors @@ -57,8 +58,10 @@ get id(): null | string Identifies the operation on the server that is running it. -Operations that run in this process have no server id. The value is -opaque: parsing it or storing it to resume the job later is not supported. +Registry handles expose a registry job ID; query handles expose a +connection-scoped SQL query UUID string. Local handles have no ID. +Query handles report jobType "query". Their IDs are not registry IDs or +durable resume tokens. #### Returns @@ -72,8 +75,8 @@ opaque: parsing it or storing it to resume the job later is not supported. get jobType(): null | string ``` -The job's type, as the server names it. Null for an in-process job, which -has no server-side record. +"query" immediately for SQL-backed handles; otherwise the cached +server-reported job type. Null for in-process handles. #### Returns diff --git a/docs/src/js/classes/MaterializedView.md b/docs/src/js/classes/MaterializedView.md index 0e2413328..3ba4d56b3 100644 --- a/docs/src/js/classes/MaterializedView.md +++ b/docs/src/js/classes/MaterializedView.md @@ -64,15 +64,20 @@ refresh(options?): Promise ``` Recompute the view from its source. +Local refresh requires a source build with `experimental-functions`. -Every refresh rebuilds the complete view. For local views, -`sourceVersion` refreshes to that source version instead of the latest; -remote SQL refreshes do not support source-version pinning. +`full: true` forces a remote rebuild; otherwise the server chooses the +refresh mode. Local views always rebuild, and `sourceVersion` selects a +source version instead of the latest. Remote SQL refreshes do not support +source-version pinning. Their results leave `mode`, `rowsWritten`, and +`sourceVersion` absent because the SQL job adapter does not expose these metrics. #### Parameters * **options?** +* **options.full?**: `boolean` + * **options.sourceVersion?**: `number` #### Returns diff --git a/docs/src/js/classes/Query.md b/docs/src/js/classes/Query.md index 8e216d1f4..7434e7b8e 100644 --- a/docs/src/js/classes/Query.md +++ b/docs/src/js/classes/Query.md @@ -543,29 +543,34 @@ where(predicate): this A filter statement to be applied to this query. -The filter should be supplied as an SQL query string. For example: +The filter may be an SQL query string or an expression built with `col`, +which preserves case-sensitive column names. For example: #### Parameters -* **predicate**: `string` +* **predicate**: `string` \| [`Expr`](Expr.md) #### Returns `this` -#### Example +#### Examples ```ts x > 10 y > 0 AND y < 100 x > 5 OR y = 'test' +``` + +```ts +table.query().where(col("firstName").eq("Alice")); +``` Filtering performance can often be improved by creating a scalar index on the filter column(s). Calling this multiple times combines the filters with a logical AND rather than replacing the previous filter. -``` #### Inherited from diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index b41ade302..4398ee3ad 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -69,6 +69,10 @@ abstract addColumns(newColumnTransforms): Promise 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. + The `{ computed }` form stores the expression rather than evaluating it now: the column is committed with no values, and rows get them from [Table#refreshColumn](Table.md#refreshcolumn). Declaring one therefore costs the same on a @@ -79,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. -On LanceDB Cloud and Enterprise the expression is planned by the +In LanceDB Distributed the expression is planned by the server, and the refresh runs as a server job -- see [Table#refreshColumnAsync](Table.md#refreshcolumnasync). @@ -381,6 +385,13 @@ await table.createIndex("vector", { }); ``` +```ts +// Or size the partitions by row count instead of choosing how many. +await table.createIndex("vector", { + config: lancedb.Index.ivfPq({ targetPartitionSize: 4096 }), +}); +``` + ```ts // Or create a Scalar index await table.createIndex("my_float_col"); @@ -675,7 +686,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 Cloud and Enterprise only; reading errors needs read +capped. LanceDB Distributed only; reading errors needs read access to the table, since a message carries the value that failed. #### Parameters @@ -928,7 +939,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 on remote tables. + This feature is currently only supported in LanceDB Distributed. #### Returns @@ -1035,11 +1046,12 @@ abstract refreshColumn(column): Promise ``` Fill the rows of a computed column that hold no value yet. +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. Local tables only: a remote refresh -runs as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync). +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). #### Parameters @@ -1063,12 +1075,15 @@ abstract refreshColumnAsync(column): 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 +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. On local tables the job runs in-process; on -LanceDB Cloud and Enterprise it is the server's backfill job. +than failing the job. In LanceDB Embedded the job runs in-process; in +LanceDB Distributed it is the server's backfill job. #### Parameters @@ -1297,8 +1312,12 @@ 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. For remote tables, this means the -same tokenizer model files must also exist locally. +the client process from index metadata. In LanceDB Distributed, 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 +server's index produces. If the model files are missing, an error naming +the tokenizer is raised. #### Parameters @@ -1423,8 +1442,6 @@ used when appropriate: - `lancedb:description`: for a human-readable description of a field. - `lancedb:tag:`: for a user-defined key-value tag, where the suffix names the tag category; e.g. `lancedb:tag:model: "clip"`. -- `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and - `feature_v2` might be in the same logical column. - `lancedb:status`: for status options (`production`, `candidate`, `deprecated`, `archived`) to designate the current life cycle state of this column. diff --git a/docs/src/js/classes/VectorQuery.md b/docs/src/js/classes/VectorQuery.md index 04ced2ef4..d98f05893 100644 --- a/docs/src/js/classes/VectorQuery.md +++ b/docs/src/js/classes/VectorQuery.md @@ -825,29 +825,34 @@ where(predicate): this A filter statement to be applied to this query. -The filter should be supplied as an SQL query string. For example: +The filter may be an SQL query string or an expression built with `col`, +which preserves case-sensitive column names. For example: #### Parameters -* **predicate**: `string` +* **predicate**: `string` \| [`Expr`](Expr.md) #### Returns `this` -#### Example +#### Examples ```ts x > 10 y > 0 AND y < 100 x > 5 OR y = 'test' +``` + +```ts +table.query().where(col("firstName").eq("Alice")); +``` Filtering performance can often be improved by creating a scalar index on the filter column(s). Calling this multiple times combines the filters with a logical AND rather than replacing the previous filter. -``` #### Inherited from diff --git a/docs/src/js/functions/col.md b/docs/src/js/functions/col.md new file mode 100644 index 000000000..6cff91cf7 --- /dev/null +++ b/docs/src/js/functions/col.md @@ -0,0 +1,21 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / col + +# Function: col() + +```ts +function col(name): Expr +``` + +Reference a column by its exact, case-sensitive name. + +## Parameters + +* **name**: `string` + +## Returns + +[`Expr`](../classes/Expr.md) diff --git a/docs/src/js/functions/connect.md b/docs/src/js/functions/connect.md index 009b7d785..5cfd11a71 100644 --- a/docs/src/js/functions/connect.md +++ b/docs/src/js/functions/connect.md @@ -20,15 +20,15 @@ Connect to a LanceDB instance at the given URI. Accepted formats: -- `/path/to/database` - local database +- `/path/to/database` - database on the local file system - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage -- `db://host:port` - remote database (LanceDB cloud) +- `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database ### Parameters * **uri**: `string` The uri of the database. If the database uri starts - with `db://` then it connects to a remote database. + with `db://` then it connects to LanceDB Enterprise or LanceDB Cloud (legacy). * **options?**: `Partial`<[`ConnectionOptions`](../interfaces/ConnectionOptions.md)> The options to use when connecting to the database @@ -80,9 +80,9 @@ Connect to a LanceDB instance at the given URI. Accepted formats: -- `/path/to/database` - local database +- `/path/to/database` - database on the local file system - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage -- `db://host:port` - remote database (LanceDB cloud) +- `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database ### Parameters diff --git a/docs/src/js/functions/connectNamespace.md b/docs/src/js/functions/connectNamespace.md index d49a8ced7..7f0ddb972 100644 --- a/docs/src/js/functions/connectNamespace.md +++ b/docs/src/js/functions/connectNamespace.md @@ -18,7 +18,7 @@ function connectNamespace( Connect to a LanceDB database through a namespace. Unlike [connect](connect.md), which routes by URI scheme (local path vs. -`db://` cloud), `connectNamespace` always returns a namespace-backed +`db://`), `connectNamespace` always returns a namespace-backed connection. The `implName` selects the namespace implementation: - `"dir"` — directory namespace, configured with [DirNamespaceConfig](../interfaces/DirNamespaceConfig.md). diff --git a/docs/src/js/functions/func.md b/docs/src/js/functions/func.md new file mode 100644 index 000000000..05f6901aa --- /dev/null +++ b/docs/src/js/functions/func.md @@ -0,0 +1,23 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / func + +# Function: func() + +```ts +function func(name, ...args): Expr +``` + +Call a registered SQL function, such as `func("lower", col("firstName"))`. + +## Parameters + +* **name**: `string` + +* ...**args**: [`ExprLike`](../type-aliases/ExprLike.md)[] + +## Returns + +[`Expr`](../classes/Expr.md) diff --git a/docs/src/js/functions/lit.md b/docs/src/js/functions/lit.md new file mode 100644 index 000000000..c9db2cf4d --- /dev/null +++ b/docs/src/js/functions/lit.md @@ -0,0 +1,21 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / lit + +# Function: lit() + +```ts +function lit(value): Expr +``` + +Create a string or numeric literal. Unsafe integers are represented as Float64. + +## Parameters + +* **value**: `string` \| `number` + +## Returns + +[`Expr`](../classes/Expr.md) diff --git a/docs/src/js/functions/litBool.md b/docs/src/js/functions/litBool.md new file mode 100644 index 000000000..d857d8b74 --- /dev/null +++ b/docs/src/js/functions/litBool.md @@ -0,0 +1,21 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / litBool + +# Function: litBool() + +```ts +function litBool(value): Expr +``` + +Create a boolean literal. + +## Parameters + +* **value**: `boolean` + +## Returns + +[`Expr`](../classes/Expr.md) diff --git a/docs/src/js/functions/litInt.md b/docs/src/js/functions/litInt.md new file mode 100644 index 000000000..6556f7572 --- /dev/null +++ b/docs/src/js/functions/litInt.md @@ -0,0 +1,21 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / litInt + +# Function: litInt() + +```ts +function litInt(value): Expr +``` + +Create an Int64 literal from a JavaScript safe integer. Other numbers throw RangeError. + +## Parameters + +* **value**: `number` + +## Returns + +[`Expr`](../classes/Expr.md) diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 646341190..25a32b29c 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -28,6 +28,7 @@ - [Catalog](classes/Catalog.md) - [Connection](classes/Connection.md) - [DatabaseNames](classes/DatabaseNames.md) +- [Expr](classes/Expr.md) - [HeaderProvider](classes/HeaderProvider.md) - [Index](classes/Index.md) - [Job](classes/Job.md) @@ -108,10 +109,6 @@ - [JobEventsOptions](interfaces/JobEventsOptions.md) - [JobFailureInfo](interfaces/JobFailureInfo.md) - [JobInfo](interfaces/JobInfo.md) -- [ListNamespacesOptions](interfaces/ListNamespacesOptions.md) -- [ListNamespacesResponse](interfaces/ListNamespacesResponse.md) -- [ListTablesOptions](interfaces/ListTablesOptions.md) -- [ListTablesResponse](interfaces/ListTablesResponse.md) - [ListingOptions](interfaces/ListingOptions.md) - [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md) - [MemtableStats](interfaces/MemtableStats.md) @@ -169,6 +166,7 @@ - [Data](type-aliases/Data.md) - [DataLike](type-aliases/DataLike.md) - [DataTypeLike](type-aliases/DataTypeLike.md) +- [ExprLike](type-aliases/ExprLike.md) - [FieldLike](type-aliases/FieldLike.md) - [IntoSql](type-aliases/IntoSql.md) - [IntoVector](type-aliases/IntoVector.md) @@ -183,11 +181,16 @@ - [RecordBatchIterator](functions/RecordBatchIterator.md) - [blob](functions/blob.md) +- [col](functions/col.md) - [connect](functions/connect.md) - [connectCatalog](functions/connectCatalog.md) - [connectNamespace](functions/connectNamespace.md) +- [func](functions/func.md) - [instrumentLanceDbMetrics](functions/instrumentLanceDbMetrics.md) - [isBlobField](functions/isBlobField.md) +- [lit](functions/lit.md) +- [litBool](functions/litBool.md) +- [litInt](functions/litInt.md) - [makeArrowTable](functions/makeArrowTable.md) - [makeJsonField](functions/makeJsonField.md) - [packBits](functions/packBits.md) diff --git a/docs/src/js/interfaces/AddDataOptions.md b/docs/src/js/interfaces/AddDataOptions.md index eb10fdb0f..26c5ccef8 100644 --- a/docs/src/js/interfaces/AddDataOptions.md +++ b/docs/src/js/interfaces/AddDataOptions.md @@ -18,8 +18,8 @@ optional allowExternalBlobOutsideBases: boolean; Whether blob URIs outside registered external bases may be written. -Defaults to `false`. This option is supported only for local/native -tables; remote tables return an error when it is enabled. An enabled write +Defaults to `false`. This option is supported only in LanceDB Embedded; +LanceDB Distributed 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/ClientConfig.md b/docs/src/js/interfaces/ClientConfig.md index d5ce32117..cc075ceed 100644 --- a/docs/src/js/interfaces/ClientConfig.md +++ b/docs/src/js/interfaces/ClientConfig.md @@ -80,7 +80,7 @@ optional userId: string; User identifier for tracking purposes. -This is sent as the `x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise. +This is sent as the `x-lancedb-user-id` header in requests to LanceDB Enterprise. It can be set directly, or via the `LANCEDB_USER_ID` environment variable. Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment variable that contains the user ID value. diff --git a/docs/src/js/interfaces/ConnectionOptions.md b/docs/src/js/interfaces/ConnectionOptions.md index 42f80f077..04cbff0ea 100644 --- a/docs/src/js/interfaces/ConnectionOptions.md +++ b/docs/src/js/interfaces/ConnectionOptions.md @@ -14,7 +14,7 @@ optional apiKey: string; ``` -(For LanceDB cloud only): the API key to use with LanceDB Cloud. +(For LanceDB Enterprise or LanceDB Cloud only): the API key to use. Can also be set via the environment variable `LANCEDB_API_KEY`. @@ -26,7 +26,7 @@ Can also be set via the environment variable `LANCEDB_API_KEY`. optional clientConfig: ClientConfig; ``` -(For LanceDB cloud only): configuration for the remote HTTP client. +(For LanceDB Enterprise or LanceDB Cloud only): configuration for the HTTP client. *** @@ -36,8 +36,8 @@ optional clientConfig: ClientConfig; optional hostOverride: string; ``` -(For LanceDB cloud only): the host to use for LanceDB cloud. Used -for testing purposes. +(For LanceDB Enterprise only): the host of the LanceDB Enterprise +deployment to connect to. *** @@ -47,7 +47,7 @@ for testing purposes. optional manifestEnabled: boolean; ``` -(For LanceDB OSS only): use directory namespace manifests as the source +(For LanceDB Embedded only): use directory namespace manifests as the source of truth for table metadata. Existing directory-listed root tables are migrated into the manifest on access. @@ -59,7 +59,7 @@ migrated into the manifest on access. optional namespaceClientProperties: Record; ``` -(For LanceDB OSS only): extra properties for the backing namespace +(For LanceDB Embedded only): extra properties for the backing namespace client used by manifest-enabled native connections. *** @@ -70,7 +70,7 @@ client used by manifest-enabled native connections. optional oauthConfig: NativeOAuthConfig; ``` -(For LanceDB cloud only): OAuth configuration for IdP-based +(For LanceDB Enterprise only): OAuth configuration for IdP-based authentication (e.g., Azure Entra ID). When set, token acquisition and refresh are handled entirely in Rust. TypeScript users should pass the public `OAuthConfig` type exported from `@lancedb/lancedb`. @@ -105,7 +105,7 @@ storage, raising per-read latency and cost. optional region: string; ``` -(For LanceDB cloud only): the region to use for LanceDB cloud. +(For LanceDB Cloud only): the region to use for LanceDB Cloud (legacy). Defaults to 'us-east-1'. *** @@ -116,7 +116,7 @@ Defaults to 'us-east-1'. optional session: Session; ``` -(For LanceDB OSS only): the session to use for this connection. Holds +(For LanceDB Embedded only): the session to use for this connection. Holds shared caches and other session-specific state. *** @@ -127,6 +127,6 @@ shared caches and other session-specific state. optional storageOptions: Record; ``` -(For LanceDB OSS only): configuration for object storage. +(For LanceDB Embedded only): configuration for object storage. The available options are described at https://docs.lancedb.com/storage/ diff --git a/docs/src/js/interfaces/CreateTableOptions.md b/docs/src/js/interfaces/CreateTableOptions.md index f46cf3722..e6119e74c 100644 --- a/docs/src/js/interfaces/CreateTableOptions.md +++ b/docs/src/js/interfaces/CreateTableOptions.md @@ -65,7 +65,7 @@ then no error will be raised. ### mode ```ts -mode: "overwrite" | "create"; +mode: "overwrite" | "create" | "exist_ok"; ``` The mode to use when creating the table. @@ -76,6 +76,9 @@ happen. Any provided data will be ignored. If this is set to "overwrite" then any existing table will be replaced. +If this is set to "exist_ok" then an existing table is opened and any +provided data is ignored. + *** ### schema? diff --git a/docs/src/js/interfaces/HnswPqOptions.md b/docs/src/js/interfaces/HnswPqOptions.md index 6d42ed28f..f044e0e11 100644 --- a/docs/src/js/interfaces/HnswPqOptions.md +++ b/docs/src/js/interfaces/HnswPqOptions.md @@ -100,6 +100,8 @@ optional numPartitions: number; The number of IVF partitions to create. +When set, this takes precedence over `targetPartitionSize`. + For HNSW, we recommend a small number of partitions. Setting this to 1 works well for most tables. For very large tables, training just one HNSW graph will require too much memory. Each partition becomes its own HNSW graph, so @@ -147,3 +149,23 @@ number of vectors used to train the index is `sample_rate * num_partitions`. Increasing this value might improve the quality of the index but in most cases the default should be sufficient. + +*** + +### targetPartitionSize? + +```ts +optional targetPartitionSize: number; +``` + +The target number of rows in each IVF partition. + +This is an alternative to `numPartitions`. When it is set and +`numPartitions` is not, the number of partitions is derived by dividing +the number of rows by this value. When both are set, `numPartitions` is +used and this value is ignored. When neither is set, the target is +1,048,576 rows. + +Larger partitions mean fewer of them, which makes the first part of the +search (picking the right partitions) faster and the second part +(searching within a partition) slower. diff --git a/docs/src/js/interfaces/HnswSqOptions.md b/docs/src/js/interfaces/HnswSqOptions.md index 585737a5a..332854490 100644 --- a/docs/src/js/interfaces/HnswSqOptions.md +++ b/docs/src/js/interfaces/HnswSqOptions.md @@ -100,6 +100,8 @@ optional numPartitions: number; The number of IVF partitions to create. +When set, this takes precedence over `targetPartitionSize`. + For HNSW, we recommend a small number of partitions. Setting this to 1 works well for most tables. For very large tables, training just one HNSW graph will require too much memory. Each partition becomes its own HNSW graph, so @@ -126,3 +128,23 @@ number of vectors used to train the index is `sample_rate * num_partitions`. Increasing this value might improve the quality of the index but in most cases the default should be sufficient. + +*** + +### targetPartitionSize? + +```ts +optional targetPartitionSize: number; +``` + +The target number of rows in each IVF partition. + +This is an alternative to `numPartitions`. When it is set and +`numPartitions` is not, the number of partitions is derived by dividing +the number of rows by this value. When both are set, `numPartitions` is +used and this value is ignored. When neither is set, the target is +1,048,576 rows. + +Larger partitions mean fewer of them, which makes the first part of the +search (picking the right partitions) faster and the second part +(searching within a partition) slower. diff --git a/docs/src/js/interfaces/IndexConfig.md b/docs/src/js/interfaces/IndexConfig.md index 6622c0189..df3b81c52 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` for remote tables or indices created before timestamps were tracked. +`undefined` in LanceDB Distributed or indices created before timestamps were tracked. *** @@ -43,8 +43,8 @@ optional indexDetails: any; Index-type-specific details parsed as a JavaScript object. -Falls back to a raw string if JSON parsing fails. `undefined` for -remote tables or when details are unavailable. +Falls back to a raw string if JSON parsing fails. `undefined` in +LanceDB Distributed or when details are unavailable. *** @@ -66,7 +66,7 @@ optional indexUuid: string; The UUID of the first segment of the index. -`undefined` for remote tables, which do not yet surface this. +`undefined` in LanceDB Distributed, which does not yet surface this. *** @@ -78,7 +78,7 @@ optional indexVersion: number; The on-disk index format version. -`undefined` for remote tables. +`undefined` in LanceDB Distributed. *** @@ -100,7 +100,7 @@ optional numIndexedRows: number; The number of rows indexed, across all segments. -`undefined` for remote tables. +May be `undefined` in LanceDB Distributed if the server does not report it. *** @@ -112,7 +112,7 @@ optional numSegments: number; The number of segments that make up the index. -`undefined` for remote tables. +`undefined` in LanceDB Distributed. *** @@ -124,7 +124,7 @@ optional numUnindexedRows: number; The number of rows not yet covered by this index. -`undefined` for remote tables. +May be `undefined` in LanceDB Distributed 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` for remote tables or indices without size tracking. +`undefined` in LanceDB Distributed or indices without size tracking. *** @@ -148,4 +148,4 @@ optional typeUrl: string; The protobuf type URL, a precise type identifier for the index. -`undefined` for remote tables. +`undefined` in LanceDB Distributed. diff --git a/docs/src/js/interfaces/IvfFlatOptions.md b/docs/src/js/interfaces/IvfFlatOptions.md index 36da98907..5b8024bc3 100644 --- a/docs/src/js/interfaces/IvfFlatOptions.md +++ b/docs/src/js/interfaces/IvfFlatOptions.md @@ -82,8 +82,9 @@ optional numPartitions: number; The number of IVF partitions to create. This value should generally scale with the number of rows in the dataset. -By default the number of partitions is the square root of the number of -rows. +When set, this takes precedence over `targetPartitionSize`. When omitted, +the partition count is derived from `targetPartitionSize`, which defaults +to 4096 rows for this index type. If this value is too large then the first part of the search (picking the right partition) will be slow. If this value is too small then the second @@ -110,3 +111,23 @@ Increasing this value might improve the quality of the index but in most cases t default should be sufficient. The default value is 256. + +*** + +### targetPartitionSize? + +```ts +optional targetPartitionSize: number; +``` + +The target number of rows in each IVF partition. + +This is an alternative to `numPartitions`. When it is set and +`numPartitions` is not, the number of partitions is derived by dividing +the number of rows by this value. When both are set, `numPartitions` is +used and this value is ignored. When neither is set, the target is +4096 rows. + +Larger partitions mean fewer of them, which makes the first part of the +search (picking the right partitions) faster and the second part +(searching within a partition) slower. diff --git a/docs/src/js/interfaces/IvfPqOptions.md b/docs/src/js/interfaces/IvfPqOptions.md index 7109e448c..f1dd47621 100644 --- a/docs/src/js/interfaces/IvfPqOptions.md +++ b/docs/src/js/interfaces/IvfPqOptions.md @@ -92,8 +92,9 @@ optional numPartitions: number; The number of IVF partitions to create. This value should generally scale with the number of rows in the dataset. -By default the number of partitions is the square root of the number of -rows. +When set, this takes precedence over `targetPartitionSize`. When omitted, +the partition count is derived from `targetPartitionSize`, which defaults +to 8192 rows for this index type. If this value is too large then the first part of the search (picking the right partition) will be slow. If this value is too small then the second @@ -141,3 +142,23 @@ Increasing this value might improve the quality of the index but in most cases t default should be sufficient. The default value is 256. + +*** + +### targetPartitionSize? + +```ts +optional targetPartitionSize: number; +``` + +The target number of rows in each IVF partition. + +This is an alternative to `numPartitions`. When it is set and +`numPartitions` is not, the number of partitions is derived by dividing +the number of rows by this value. When both are set, `numPartitions` is +used and this value is ignored. When neither is set, the target is +8192 rows. + +Larger partitions mean fewer of them, which makes the first part of the +search (picking the right partitions) faster and the second part +(searching within a partition) slower. diff --git a/docs/src/js/interfaces/IvfRqOptions.md b/docs/src/js/interfaces/IvfRqOptions.md index 6b48cf653..eb2cfe0ac 100644 --- a/docs/src/js/interfaces/IvfRqOptions.md +++ b/docs/src/js/interfaces/IvfRqOptions.md @@ -58,7 +58,8 @@ Number of bits per dimension for residual quantization. This value controls how much each residual component is compressed. The more bits, the more accurate the index will be but the slower search. Typical values -are small integers; the default is 1 bit per dimension. +are small integers. If unset, uses Lance's default (currently 5 bits per +dimension). Set to 1 for maximum compression. *** @@ -71,8 +72,9 @@ optional numPartitions: number; The number of IVF partitions to create. This value should generally scale with the number of rows in the dataset. -By default the number of partitions is the square root of the number of -rows. +When set, this takes precedence over `targetPartitionSize`. When omitted, +the partition count is derived from `targetPartitionSize`, which defaults +to 4096 rows for this index type. If this value is too large then the first part of the search (picking the right partition) will be slow. If this value is too small then the second @@ -99,3 +101,23 @@ Increasing this value might improve the quality of the index but in most cases t default should be sufficient. The default value is 256. + +*** + +### targetPartitionSize? + +```ts +optional targetPartitionSize: number; +``` + +The target number of rows in each IVF partition. + +This is an alternative to `numPartitions`. When it is set and +`numPartitions` is not, the number of partitions is derived by dividing +the number of rows by this value. When both are set, `numPartitions` is +used and this value is ignored. When neither is set, the target is +4096 rows. + +Larger partitions mean fewer of them, which makes the first part of the +search (picking the right partitions) faster and the second part +(searching within a partition) slower. diff --git a/docs/src/js/interfaces/ListNamespacesOptions.md b/docs/src/js/interfaces/ListNamespacesOptions.md deleted file mode 100644 index 79680417f..000000000 --- a/docs/src/js/interfaces/ListNamespacesOptions.md +++ /dev/null @@ -1,27 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / ListNamespacesOptions - -# Interface: ListNamespacesOptions - -## Properties - -### limit? - -```ts -optional limit: number; -``` - -An optional limit to the number of results to return. - -*** - -### pageToken? - -```ts -optional pageToken: string; -``` - -Token from a previous response for pagination. diff --git a/docs/src/js/interfaces/ListNamespacesResponse.md b/docs/src/js/interfaces/ListNamespacesResponse.md deleted file mode 100644 index a99ab480f..000000000 --- a/docs/src/js/interfaces/ListNamespacesResponse.md +++ /dev/null @@ -1,23 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / ListNamespacesResponse - -# Interface: ListNamespacesResponse - -## Properties - -### namespaces - -```ts -namespaces: string[]; -``` - -*** - -### pageToken? - -```ts -optional pageToken: string; -``` diff --git a/docs/src/js/interfaces/ListTablesOptions.md b/docs/src/js/interfaces/ListTablesOptions.md deleted file mode 100644 index b8dd8b5ef..000000000 --- a/docs/src/js/interfaces/ListTablesOptions.md +++ /dev/null @@ -1,35 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / ListTablesOptions - -# Interface: ListTablesOptions - -## Properties - -### limit? - -```ts -optional limit: number; -``` - -An upper bound on how many tables to return. -Defaults to 100. Zero returns an empty page without a continuation token. - -A page may hold fewer than this and still not be the last one, so keep -going while the response carries a page token rather than while pages are -full. - -*** - -### pageToken? - -```ts -optional pageToken: string; -``` - -Token from a previous response, to resume listing where it left off. - -The token is opaque: it carries whatever the database needs to resume, and -callers should not construct or interpret one. diff --git a/docs/src/js/interfaces/ListTablesResponse.md b/docs/src/js/interfaces/ListTablesResponse.md deleted file mode 100644 index 76cac2b23..000000000 --- a/docs/src/js/interfaces/ListTablesResponse.md +++ /dev/null @@ -1,23 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / ListTablesResponse - -# Interface: ListTablesResponse - -## Properties - -### pageToken? - -```ts -optional pageToken: string; -``` - -*** - -### tables - -```ts -tables: string[]; -``` diff --git a/docs/src/js/interfaces/QueryExecutionOptions.md b/docs/src/js/interfaces/QueryExecutionOptions.md index 8d3749f38..f18ada7aa 100644 --- a/docs/src/js/interfaces/QueryExecutionOptions.md +++ b/docs/src/js/interfaces/QueryExecutionOptions.md @@ -20,12 +20,14 @@ How to return blob v2 columns. Applies to `toArrow()` and `toArray()`. - `"descriptions"` (default): each blob is a descriptor. Read the bytes with [Table.fetchBlobs](../classes/Table.md#fetchblobs) or [Table.fetchBlobFiles](../classes/Table.md#fetchblobfiles). -- `"bytes"`: each top-level blob column holds the blob bytes as - `LargeBinary`. The query also reads `_rowid` to fetch the bytes, and +- `"bytes"`: each blob column, including blobs nested in structs, holds + the bytes as `LargeBinary`. The query also reads `_rowid` to fetch them, and leaves it out of the result unless [QueryBase.withRowId](../classes/QueryBase.md#withrowid) was called. All the bytes are held in memory. -Blobs nested in a struct or a list keep their descriptors. +Selecting a parent struct or directly aliasing a blob or struct also returns +bytes. Blobs inside lists keep their descriptors. Arbitrary projection +expressions are not materialized as bytes. The rows and the bytes come from the same table version. If the table changes while the query runs, the query runs again, up to three times. diff --git a/docs/src/js/interfaces/RefreshMaterializedViewResult.md b/docs/src/js/interfaces/RefreshMaterializedViewResult.md index 1c8b8bc21..e1ec3eb65 100644 --- a/docs/src/js/interfaces/RefreshMaterializedViewResult.md +++ b/docs/src/js/interfaces/RefreshMaterializedViewResult.md @@ -8,30 +8,34 @@ ## Properties -### mode +### mode? ```ts -mode: string; +optional mode: string; ``` -How the view was brought up to date: "rebuild". +How the view was brought up to date: "rebuild", or absent for LanceDB Distributed SQL refreshes. *** -### rowsWritten +### rowsWritten? ```ts -rowsWritten: number; +optional rowsWritten: number; ``` +Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes. + *** -### sourceVersion +### sourceVersion? ```ts -sourceVersion: number; +optional sourceVersion: number; ``` +Source version refreshed to, or absent for LanceDB Distributed SQL refreshes. + *** ### version diff --git a/docs/src/js/interfaces/RetryConfig.md b/docs/src/js/interfaces/RetryConfig.md index a9e4e6046..4f9336b66 100644 --- a/docs/src/js/interfaces/RetryConfig.md +++ b/docs/src/js/interfaces/RetryConfig.md @@ -84,7 +84,7 @@ optional statuses: number[]; ``` The HTTP status codes for which to retry the request. Default is -[429, 500, 502, 503]. +[409, 429, 500, 502, 503, 504]. You can also set this via the environment variable `LANCE_CLIENT_RETRY_STATUSES`. Use a comma-separated list of integers. diff --git a/docs/src/js/interfaces/TableNamesOptions.md b/docs/src/js/interfaces/TableNamesOptions.md index 123aa6c9f..e1fd8c382 100644 --- a/docs/src/js/interfaces/TableNamesOptions.md +++ b/docs/src/js/interfaces/TableNamesOptions.md @@ -8,7 +8,7 @@ ## Deprecated -Use [ListTablesOptions](ListTablesOptions.md) with [Connection.listTables](../classes/Connection.md#listtables) +Use [ListingOptions](ListingOptions.md) with [Connection.listTables](../classes/Connection.md#listtables) instead. ## Properties diff --git a/docs/src/js/interfaces/TimeoutConfig.md b/docs/src/js/interfaces/TimeoutConfig.md index c821afc4d..74e174522 100644 --- a/docs/src/js/interfaces/TimeoutConfig.md +++ b/docs/src/js/interfaces/TimeoutConfig.md @@ -45,6 +45,10 @@ The timeout for reading data from the server in seconds. Default is 300 seconds (5 minutes). This can also be set via the environment variable `LANCE_CLIENT_READ_TIMEOUT`, as an integer number of seconds. +This also applies while waiting for response headers during an upload. +A large or slowly produced request body (for example, when creating a +table) may need a longer timeout even if data is still being uploaded. + *** ### timeout? diff --git a/docs/src/js/type-aliases/BlobReadOptions.md b/docs/src/js/type-aliases/BlobReadOptions.md index 17264b0e4..53184aa48 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 remote table. +read stops, including in-flight requests to a LanceDB Distributed table. diff --git a/docs/src/js/type-aliases/ExprLike.md b/docs/src/js/type-aliases/ExprLike.md new file mode 100644 index 000000000..d0628c982 --- /dev/null +++ b/docs/src/js/type-aliases/ExprLike.md @@ -0,0 +1,13 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / ExprLike + +# Type Alias: ExprLike + +```ts +type ExprLike: Expr | string | number | boolean; +``` + +Values accepted by expression operators. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index c8a82851f..b3c0c4672 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -20,20 +20,34 @@ pip install lancedb The following methods describe the synchronous API client. There is also an [asynchronous API client](#connections-asynchronous). +Connections to `db://` databases reject local-only options with +`NotImplementedError`. These include `session` and `manifest_enabled=True` on +connect, per-table storage and write options on create, and `index_cache_size`, +`storage_options`, or `location` on open (where the method accepts them). +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 +LanceDB Embedded API: `name, data, schema, mode, exist_ok, on_bad_vectors, fill_value, +embedding_functions`. Prefer keyword arguments for optional parameters. + ## Connections (Synchronous) ::: lancedb.connect ::: lancedb.db.DBConnection -Resource listings (`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. +Resource listings return iterators. Use `list(db.list_tables())` to collect all +table names. `db.list_tables().tables` is a list of the first page; `limit` +controls its page size and `page_token` resumes at a saved token. The same +patterns apply to `list_namespaces()`. Other resource listings use `page_limit`. ::: lancedb.listing.Listing +::: lancedb.listing.TableListing + +::: lancedb.listing.NamespaceListing + ::: lancedb.Session ## Catalogs (Synchronous) @@ -213,15 +227,24 @@ async for entry in catalog.authz.list_acls(subject=Subject.role("reader")): ## Remote SQL -Submit SQL against a remote LanceDB database through the connection. +Submit SQL against a LanceDB Distributed 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 reader as soon as its initial result stream is available. `execute_query_async` -returns a query handle immediately; use it to inspect progress, open a reader, +returns a query handle once submission is accepted; use it to inspect progress, open a reader, or cancel the query. The SQL client is initialized by the first query and -retained for the lifetime of the remote connection. Query ids are random, -connection-scoped references rather than encoded SQL or durable resume tokens: +retained for the lifetime of the connection. Query ids are random, +connection-scoped references rather than encoded SQL or durable resume tokens. + +Both APIs start with one Flight call. The server can stream results on that +call or return a polling continuation that the SDK follows automatically. +This behavior is the same with and without parameters. Open the reader directly; +a directly streamed query needs its reader to make progress. Dropping an unread +handle or its reader stops direct streaming. Deferred execution continues until +explicitly cancelled. + +For example: ```python import lancedb @@ -285,8 +308,29 @@ listing a storage directory. ## Tables (Synchronous) +LanceDB Embedded and LanceDB Distributed 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. + +The old LanceDB Distributed 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. + ::: lancedb.table.Table +::: lancedb.table.CompactionOptions + ::: lancedb.table.FragmentStatistics ::: lancedb.table.FragmentSummaryStats @@ -301,6 +345,14 @@ listing a storage directory. ## Functions and Jobs +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`. + +::: lancedb.BlobReader + ::: lancedb.functions.FunctionArtifact ::: lancedb.functions.FunctionParameter @@ -377,6 +429,30 @@ listing a storage directory. ## Materialized Views (Synchronous) +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 +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 +`auto_refresh_interval_seconds`: + +```python +view = db.create_materialized_view( + "recent_orders", + "orders", + auto_refresh_enabled=True, + auto_refresh_interval_seconds=300, +) +``` + +Omit `auto_refresh_interval_seconds` to let the server determine when to refresh. +These options also apply to asynchronous creation and creation jobs. Embedded +connections built with `experimental-functions` support manual refresh and reject +automatic scheduling requests. + ::: lancedb.materialized_view.MaterializedView ::: lancedb.materialized_view.MaterializedViewDefinition @@ -432,6 +508,8 @@ and combined with [BooleanQuery][lancedb.query.BooleanQuery]. ::: lancedb.query.MultiMatchQuery +::: lancedb.query.CombinedFieldsQuery + ::: lancedb.query.BooleanQuery ::: lancedb.query.FullTextOperator @@ -502,18 +580,103 @@ instead of being materialized with the rest of the row. `lancedb.BlobType` is `lance.blob.BlobType` when pylance is installed. Without pylance, LanceDB uses a matching `lance.blob.v2` extension type so blob columns -still work. Queries return descriptors. Call +still work. Native table queries return descriptors. Call [`fetch_blob_files`][lancedb.table.Table.fetch_blob_files] for lazy reads or [`fetch_blobs`][lancedb.table.Table.fetch_blobs] for eager bytes. +LanceDB Embedded supports these fetch APIs for both legacy blob v1 columns +(`lance-encoding:blob`) and blob v2 columns. For legacy columns, obtain row IDs +with `search().with_row_id(True).to_arrow()` and pass the result to the fetch API. One missing or deleted row ID rejects the entire blob-read batch; the APIs do not return partial results. +To construct inline Blob V2 arrays for ingestion in record batches, use +[blob_array][lancedb.schema.blob_array]. It accepts bytes and `None`, preserving +the distinction between an empty blob (`b""`) and a null blob: + +```python +import pyarrow as pa +from lancedb.schema import blob, blob_array + +schema = pa.schema([pa.field("video_id", pa.string()), blob("video")]) +batch = pa.RecordBatch.from_arrays( + [pa.array(["a", "b", "c"]), blob_array([b"abc", None, b""])], + schema=schema, +) +table = db.create_table("videos", data=iter([batch]), schema=schema) +table.add(iter([batch])) +``` + +`create_table(..., schema=...)` also casts plain binary values into blob columns +declared in the schema. `table.add(...)` casts them using the table's schema. +These conversions apply to Python rows and plain binary Arrow columns. +PyArrow's `RecordBatch.from_pylist(..., schema=...)` cannot convert raw bytes +into the blob extension type; use `blob_array` and `RecordBatch.from_arrays` +when constructing batches explicitly. + +For external blob references, construct the descriptor struct described by +[blob][lancedb.schema.blob], then wrap it with `pa.ExtensionArray.from_storage`. +Inline `data` and external `uri` representations are mutually exclusive. + +LanceDB Distributed 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]: + +```python +rows = db.execute_query(""" + SELECT f.timestamp, blob_descriptor(v.video) AS video + FROM videos v JOIN frames f ON v.id = f.video_id +""").read_all() +videos = db.open_table("videos") +for row in rows.to_pylist(): + if row["video"] is not None: + with videos.open_blob_file(row["video"]) as video: + frame = extract_frame(video, row["timestamp"]) +``` + +This example uses a LanceDB Distributed 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 +the source table and commit and reads the captured version without changing +the table handle's checkout. Raw native storage descriptors omit `source`; +use `fetch_blob_files(column, row_ids)` for those query results. + +The singular API accepts a dictionary or Arrow struct scalar. The iterable +accepts Arrow arrays/chunked arrays or another iterable, opens handles as +iteration advances, and preserves order, duplicates, and nulls as `None`. +Close each non-null handle after use. Async tables provide +`await table.open_blob_file(...)` and +`async for file in table.open_blob_files(...)`. + +```python +for row, video in zip(rows.to_pylist(), videos.open_blob_files(rows["video"])): + if video is not None: + with video: + frame = extract_frame(video, row["timestamp"]) +``` + +For an async table, the iterable is consumed with `async for`: + +```python +async for video in async_videos.open_blob_files(rows["video"]): + if video is not None: + with video: + payload = await video.aread() +``` + +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 +requests that validate the captured URI and commit timestamp. + Blobs inside lists can be written and queried as descriptors. They are omitted from `blob_columns()` because row ids do not identify individual list elements, so the fetch APIs cannot read their bytes yet. ::: lancedb.blob +::: lancedb.schema.blob_array + ::: lancedb._blob.BlobFile options: show_root_full_path: false @@ -615,6 +778,16 @@ can be used to create, list, or open tables. ::: lancedb.listing.AsyncListing +`async for name in db.list_tables()` loads pages as needed. To inspect the +first page, use `page = await db.list_tables()` and then `page.tables`. Reading +the page list does not consume the iterator. `page.page_token` is the token for +the next request; drain cached results before using it to resume in a new +listing. The same behavior applies to namespaces. + +::: lancedb.listing.AsyncTableListing + +::: lancedb.listing.AsyncNamespaceListing + ## Namespaces (Asynchronous) ::: lancedb.connect_namespace_async diff --git a/docs/web-tests/blob-v2/README.md b/docs/web-tests/blob-v2/README.md new file mode 100644 index 000000000..c0f75cdc6 --- /dev/null +++ b/docs/web-tests/blob-v2/README.md @@ -0,0 +1,55 @@ +# Blob v2 documentation tests + +`docs/web-tests/ts` pins `@lancedb/lancedb` 0.31.0 and `docs/web-tests/rs` pins `lancedb` 0.31.0. Those releases do not include `blob()`. Run the Blob v2 examples here. + +## Python + +`lancedb==0.41.0b10` from the LanceDB package index, without pylance. PyPI `lancedb` 0.40.0 does not provide `lancedb.blob()`. + +```shell +python3.13 -m venv .venv +.venv/bin/pip install -r docs/web-tests/blob-v2/py/requirements.txt +.venv/bin/python -m pytest docs/web-tests/blob-v2/py/test_multimodal.py +``` + +`test_blob_pylance.py` checks custom thresholds and `to_pandas()` in `lazy` and `bytes` mode. Those calls import pylance. Use a second virtualenv. `test_multimodal.py` fails if `lance` can be imported. Snippets from this file are written to `docs/web/snippets/blob_pylance.mdx`. + +This install is for the optional tests only. The public guide does not tell users to bypass the dependency resolver. PyPI `pylance` 13.0.0 requires `lance-namespace<0.12`, and `lancedb==0.41.0b10` requires `lance-namespace>=0.13`, so `lancedb[pylance]` does not resolve. The three tests passed with pylance installed after the base requirements, without its own dependency pin. + +```shell +python3.13 -m venv .venv-pylance +.venv-pylance/bin/pip install -r docs/web-tests/blob-v2/py/requirements.txt +.venv-pylance/bin/pip install --no-deps pylance==13.0.0 +.venv-pylance/bin/python -m pytest docs/web-tests/blob-v2/py/test_blob_pylance.py +``` + +## TypeScript + +`@lancedb/lancedb@0.41.0-beta.8`. Node.js 22.6 or newer. `npm test` passes `--experimental-strip-types`, which Node added in 22.6.0. + +```shell +cd docs/web-tests/blob-v2/ts +npm ci +npm test +``` + +## Rust + +crates.io `lancedb` 0.40.0 does not include `blob()`. This example builds the workspace crate, `lancedb` 0.41.0-beta.10. Pass `--features remote` so this checkout compiles. The example uses a local database. The Rust workflow runs this example. It is not a default feature, so a workspace build without `remote` does not turn that feature on for the rest of the workspace. + +```shell +cargo run -p lancedb-blob-v2-docs --features remote --example multimodal +``` + +## CI + +Python and TypeScript above install preview packages. Pre-release builds are not guaranteed to stay available for more than 6 months, so those runs are not required PR checks. Run them when the guide's pins change. The Rust example is the in-repo check. + +Regenerate snippets from the repository root: + +```shell +python3 docs/web-tests/mdx_snippets_gen.py \ + -s docs/web-tests/py -s docs/web-tests/ts -s docs/web-tests/rs \ + -s docs/web-tests/blob-v2/py -s docs/web-tests/blob-v2/ts -s docs/web-tests/blob-v2/rs \ + -o docs/web/snippets +``` diff --git a/docs/web-tests/blob-v2/py/pytest.ini b/docs/web-tests/blob-v2/py/pytest.ini new file mode 100644 index 000000000..17c9e9cb4 --- /dev/null +++ b/docs/web-tests/blob-v2/py/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +asyncio_mode = auto +testpaths = test_multimodal.py diff --git a/docs/web-tests/blob-v2/py/requirements.txt b/docs/web-tests/blob-v2/py/requirements.txt new file mode 100644 index 000000000..c90c8d622 --- /dev/null +++ b/docs/web-tests/blob-v2/py/requirements.txt @@ -0,0 +1,8 @@ +--extra-index-url https://pypi.fury.io/lancedb/ + +lancedb==0.41.0b10 +numpy==2.2.6 +pandas==2.3.3 +pillow==12.1.1 +pytest==8.4.2 +pytest-asyncio==1.2.0 diff --git a/docs/web-tests/blob-v2/py/test_blob_pylance.py b/docs/web-tests/blob-v2/py/test_blob_pylance.py new file mode 100644 index 000000000..8f66088a7 --- /dev/null +++ b/docs/web-tests/blob-v2/py/test_blob_pylance.py @@ -0,0 +1,154 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Blob reads that import pylance. + +Install pylance==13.0.0 with --no-deps after lancedb==0.41.0b10. +See docs/web-tests/blob-v2/README.md. +""" + +import lance +import lancedb +import numpy as np +import pyarrow as pa +import pytest + + +def test_blob_api_to_pandas(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema( + [ + pa.field("id", pa.int64()), + lancedb.blob("video"), + ] + ) + tbl = db.create_table( + "videos", + data=[ + {"id": 1, "video": b"fake_video_bytes_1"}, + {"id": 2, "video": b"fake_video_bytes_2"}, + ], + schema=schema, + mode="overwrite", + ) + + # --8<-- [start:blob_api_to_pandas] + df_lazy = tbl.to_pandas() + + df_bytes = tbl.to_pandas(blob_mode="bytes") + + df_desc = tbl.to_pandas(blob_mode="descriptions") + + arrow_bytes = tbl.to_arrow(blob_mode="bytes") + + df_typed = tbl.to_pandas(split_blocks=True, self_destruct=True) + # --8<-- [end:blob_api_to_pandas] + + assert len(df_lazy) == 2 + assert all(isinstance(value, lance.BlobFile) for value in df_lazy["video"]) + assert isinstance(df_bytes["video"].iloc[0], bytes) + assert df_bytes["video"].tolist() == [ + b"fake_video_bytes_1", + b"fake_video_bytes_2", + ] + assert arrow_bytes["video"].to_pylist() == [ + b"fake_video_bytes_1", + b"fake_video_bytes_2", + ] + assert "_rowid" not in df_bytes.columns + assert len(df_desc) == 2 + assert set(df_desc["video"].iloc[0]) == { + "kind", + "position", + "size", + "blob_id", + "blob_uri", + } + assert len(df_typed) == 2 + + +@pytest.mark.asyncio +async def test_query_to_pandas_kwargs(tmp_path): + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("vector", pa.list_(pa.float32(), 128)), + lancedb.blob("video"), + ] + ) + data = [ + { + "id": i, + "vector": np.random.rand(128).astype(np.float32), + "video": f"fake_video_bytes_{i}".encode(), + } + for i in range(10) + ] + + db = lancedb.connect(tmp_path / "sync") + tbl = db.create_table("search_demo", data=data, schema=schema, mode="overwrite") + + async_db = await lancedb.connect_async(str(tmp_path / "async")) + tbl_async = await async_db.create_table( + "search_demo", data=data, schema=schema, mode="overwrite" + ) + + query_vector = np.random.rand(128).astype(np.float32) + + # --8<-- [start:query_to_pandas_kwargs] + df_lazy = ( + tbl.search().where("id = 1").select(["id", "video"]).to_pandas(blob_mode="lazy") + ) + + df_bytes = await ( + tbl_async.query() + .where("id = 1") + .select(["id", "video"]) + .to_pandas(blob_mode="bytes") + ) + + df_vec = ( + tbl.search(query_vector) + .limit(2) + .select(["id", "video"]) + .to_pandas(blob_mode="bytes", split_blocks=True, self_destruct=True) + ) + # --8<-- [end:query_to_pandas_kwargs] + + assert len(df_lazy) == 1 + assert "_rowid" not in df_bytes.columns + assert len(df_bytes) == 1 + assert df_bytes["video"].iloc[0] == b"fake_video_bytes_1" + assert len(df_vec) == 2 + assert isinstance(df_vec["video"].iloc[0], bytes) + + +def test_append_keeps_table_blob_thresholds(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema( + [ + pa.field("id", pa.int64()), + lancedb.blob("video", inline_size_threshold=64 * 1024), + ] + ) + tbl = db.create_table("videos", schema=schema) + other = pa.schema( + [ + pa.field("id", pa.int64()), + lancedb.blob("video", inline_size_threshold=8 * 1024), + ] + ) + payload = b"x" * (20 * 1024) + tbl.add( + pa.table( + [pa.array([1], type=pa.int64()), lance.blob_array([payload])], + schema=other, + ) + ) + + stored = tbl.schema.field("video").metadata[ + b"lance-encoding:blob-inline-size-threshold" + ] + assert stored == b"65536" + descriptor = tbl.search().select(["video"]).to_arrow(blob_mode="descriptions") + assert descriptor.column("video")[0].as_py()["kind"] == 0 diff --git a/docs/web-tests/blob-v2/py/test_multimodal.py b/docs/web-tests/blob-v2/py/test_multimodal.py new file mode 100644 index 000000000..bf14ba57b --- /dev/null +++ b/docs/web-tests/blob-v2/py/test_multimodal.py @@ -0,0 +1,204 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import importlib.util + +import lancedb +import pyarrow as pa + +if importlib.util.find_spec("lance") is not None: + raise RuntimeError( + "Blob v2 documentation tests must run without pylance. " + "Install docs/web-tests/blob-v2/py/requirements.txt into a fresh virtualenv." + ) + +INLINE_MAX = 64 * 1024 +DEDICATED_MIN = 4 * 1024 * 1024 + + +def test_blob_api_definition(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + # --8<-- [start:blob_api_setup] + import lancedb + + db = lancedb.connect("./blob_db") + # --8<-- [end:blob_api_setup] + assert db.list_tables().tables == [] + + # --8<-- [start:blob_api_schema] + import lancedb + import pyarrow as pa + + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("label", pa.string()), + lancedb.blob("image"), + ] + ) + # --8<-- [end:blob_api_schema] + image = schema.field("image").type + assert image.extension_name == "lance.blob.v2" + assert type(image).__module__ == "lancedb.schema" + + # --8<-- [start:blob_api_ingest] + import io + from PIL import Image + + def jpeg_with_make(color, make): + image = Image.new("RGB", (8, 8), color=color) + exif = Image.Exif() + exif[0x010F] = make + buf = io.BytesIO() + image.save(buf, format="JPEG", exif=exif) + return buf.getvalue() + + tbl = db.create_table( + "photos", + data=[ + {"id": 1, "label": "red", "image": jpeg_with_make("red", "TestCam")}, + {"id": 2, "label": "blue", "image": jpeg_with_make("blue", "OtherCam")}, + ], + schema=schema, + mode="overwrite", + ) + # --8<-- [end:blob_api_ingest] + assert len(tbl) == 2 + + # --8<-- [start:blob_api_bytes] + rows = ( + tbl.search().where("id = 1").select(["id", "image"]).to_list(blob_mode="bytes") + ) + # --8<-- [end:blob_api_bytes] + assert len(rows) == 1 + assert rows[0]["id"] == 1 + assert "_rowid" not in rows[0] + assert rows[0]["image"].startswith(b"\xff\xd8") + + # --8<-- [start:blob_api_files] + from PIL import ExifTags + + rows = tbl.search().where("id = 1").select(["label"]).with_row_id(True).to_list() + with tbl.fetch_blob_files("image", [rows[0]["_rowid"]])[0] as image_file: + make = Image.open(image_file).getexif().get(ExifTags.Base.Make) + print(rows[0]["label"], make) + # --8<-- [end:blob_api_files] + assert rows[0]["label"] == "red" + assert make == "TestCam" + + # --8<-- [start:blob_api_fetch] + rows = tbl.search().select(["id"]).with_row_id(True).to_list() + row_ids = [row["_rowid"] for row in rows] + payloads = tbl.fetch_blobs("image", row_ids) + # --8<-- [end:blob_api_fetch] + assert all(payload.startswith(b"\xff\xd8") for payload in payloads.to_pylist()) + + # --8<-- [start:blob_api_ranges] + slices = tbl.fetch_blob_ranges("image", [(row_ids[0], 0, 2)]) + + with tbl.fetch_blob_files("image", [row_ids[0]])[0] as image_file: + parts = image_file.read_ranges([(0, 2)]) + # --8<-- [end:blob_api_ranges] + assert slices.to_pylist() == [b"\xff\xd8"] + assert parts == [b"\xff\xd8"] + + +def test_eager_query_returns_blob_bytes_without_row_id(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + payload = b"inline-bytes" + tbl = db.create_table( + "photos", + data=[{"id": 1, "image": payload}], + schema=schema, + ) + + rows = ( + tbl.search().where("id = 1").select(["id", "image"]).to_list(blob_mode="bytes") + ) + arrow_bytes = ( + tbl.search().where("id = 1").select(["id", "image"]).to_arrow(blob_mode="bytes") + ) + described = tbl.to_pandas(blob_mode="descriptions") + + assert rows == [{"id": 1, "image": payload}] + assert "_rowid" not in rows[0] + assert arrow_bytes.column("image").to_pylist() == [payload] + assert "_rowid" not in arrow_bytes.column_names + assert described["image"].iloc[0]["kind"] == 0 + + +def test_deferred_fetch_reads_blob_by_row_id(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + payload = b"deferred-bytes" + tbl = db.create_table( + "photos", + data=[{"id": 1, "image": payload}], + schema=schema, + ) + + described = ( + tbl.search() + .where("id = 1") + .select(["id", "image"]) + .to_list(blob_mode="descriptions") + ) + assert described[0]["image"]["kind"] == 0 + assert "_rowid" not in described[0] + + found = tbl.search().where("id = 1").select(["id"]).with_row_id(True).to_list() + row_id = found[0]["_rowid"] + fetched = tbl.fetch_blobs("image", [row_id]).to_pylist() + with tbl.fetch_blob_files("image", [row_id])[0] as handle: + streamed = handle.read() + + assert fetched == [payload] + assert streamed == payload + + +def _marked(size, marker): + payload = bytearray(size) + payload[0] = marker + payload[-1] = marker + return bytes(payload) + + +def test_storage_tiers_round_trip(tmp_path): + cases = [ + (1, _marked(INLINE_MAX, 11), 0), + (2, _marked(INLINE_MAX + 1, 22), 1), + (3, _marked(DEDICATED_MIN, 33), 1), + (4, _marked(DEDICATED_MIN + 1, 44), 2), + ] + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + tbl = db.create_table( + "tiers", + data=[{"id": row_id, "image": payload} for row_id, payload, _kind in cases], + schema=schema, + ) + + described = { + row["id"]: row["image"] + for row in tbl.search() + .select(["id", "image"]) + .to_list(blob_mode="descriptions") + } + located = { + row["id"]: row["_rowid"] + for row in tbl.search().select(["id"]).with_row_id(True).to_list() + } + fetched = { + row_id: tbl.fetch_blobs("image", [located[row_id]]).to_pylist()[0] + for row_id, _payload, _kind in cases + } + + for row_id, payload, kind in cases: + descriptor = described[row_id] + assert descriptor["kind"] == kind + assert descriptor["size"] == len(payload) + assert fetched[row_id] == payload + with tbl.fetch_blob_files("image", [located[row_id]])[0] as handle: + assert handle.read_range(0, 1) == payload[:1] + assert handle.read_range(len(payload) - 1, 1) == payload[-1:] diff --git a/docs/web-tests/blob-v2/rs/Cargo.toml b/docs/web-tests/blob-v2/rs/Cargo.toml new file mode 100644 index 000000000..f96fde230 --- /dev/null +++ b/docs/web-tests/blob-v2/rs/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "lancedb-blob-v2-docs" +version = "0.0.0" +edition.workspace = true +publish = false +license.workspace = true + +[features] +remote = ["lancedb/remote"] + +[dependencies] +arrow-array = { workspace = true } +arrow-schema = { workspace = true } +futures-util = "0.3" +lancedb = { workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } + +[[example]] +name = "multimodal" +path = "multimodal.rs" diff --git a/docs/web-tests/blob-v2/rs/multimodal.rs b/docs/web-tests/blob-v2/rs/multimodal.rs new file mode 100644 index 000000000..257bc01c1 --- /dev/null +++ b/docs/web-tests/blob-v2/rs/multimodal.rs @@ -0,0 +1,344 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +// --8<-- [start:blob_api_imports] +use std::sync::Arc; + +use arrow_array::{ + Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, UInt64Array, +}; +use arrow_schema::{DataType, Field, Schema}; +use futures_util::TryStreamExt; +use lancedb::blob::{BlobRangeRequest, blob}; +use lancedb::connect; +use lancedb::database::CreateTableMode; +use lancedb::query::{ExecutableQuery, QueryBase}; +// --8<-- [end:blob_api_imports] + +use arrow_array::{StructArray, UInt8Array}; + +const INLINE_MAX: usize = 64 * 1024; +const DEDICATED_MIN: usize = 4 * 1024 * 1024; + +#[tokio::main] +async fn main() { + tutorial().await; + deferred_fetch().await; + storage_tiers().await; +} + +async fn tutorial() { + let temp_dir = tempfile::tempdir().unwrap(); + let original_dir = std::env::current_dir().unwrap(); + std::env::set_current_dir(temp_dir.path()).unwrap(); + + // --8<-- [start:blob_api_setup] + let db = connect("./blob_db").execute().await.unwrap(); + // --8<-- [end:blob_api_setup] + + // --8<-- [start:blob_api_schema] + let blob_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("label", DataType::Utf8, true), + blob("image", true), + ])); + // --8<-- [end:blob_api_schema] + + // --8<-- [start:blob_api_ingest] + let blob_table = db + .create_empty_table("photos", blob_schema) + .mode(CreateTableMode::Overwrite) + .execute() + .await + .unwrap(); + + let input_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("label", DataType::Utf8, true), + Field::new("image", DataType::LargeBinary, true), + ])); + let input_batch = RecordBatch::try_new( + input_schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1_i64, 2_i64])), + Arc::new(StringArray::from(vec![Some("door"), Some("window")])), + Arc::new(LargeBinaryArray::from_iter_values([ + b"inline_image_bytes".as_slice(), + b"second_image_bytes".as_slice(), + ])), + ], + ) + .unwrap(); + let input_reader: Box = Box::new( + RecordBatchIterator::new(vec![Ok(input_batch)].into_iter(), input_schema), + ); + blob_table.add(input_reader).execute().await.unwrap(); + // --8<-- [end:blob_api_ingest] + assert_eq!(blob_table.count_rows(None).await.unwrap(), 2); + + // --8<-- [start:blob_api_files] + let batches = blob_table + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let row_ids = batches[0] + .column_by_name("_rowid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec(); + + let handles = blob_table + .fetch_blob_files("image", &row_ids[..1]) + .await + .unwrap(); + let header = handles[0].as_ref().unwrap().read_range(0..6).await.unwrap(); + handles[0].as_ref().unwrap().close().await.unwrap(); + // --8<-- [end:blob_api_files] + assert_eq!(header.as_ref(), b"inline"); + + // --8<-- [start:blob_api_fetch] + let payloads = blob_table.fetch_blobs("image", &row_ids).await.unwrap(); + // --8<-- [end:blob_api_fetch] + assert_eq!(payloads.len(), 2); + + // --8<-- [start:blob_api_ranges] + let slices = blob_table + .fetch_blob_ranges( + "image", + [ + BlobRangeRequest::new(row_ids[0], 0, 6), + BlobRangeRequest::new(row_ids[1], 0, 6), + BlobRangeRequest::new(row_ids[1], 7, 5), + ], + ) + .await + .unwrap(); + + let second_handles = blob_table + .fetch_blob_files("image", &row_ids[1..2]) + .await + .unwrap(); + let second_image = second_handles[0].as_ref().unwrap(); + let parts = second_image.read_ranges(&[0..6, 7..12]).await.unwrap(); + second_image.close().await.unwrap(); + // --8<-- [end:blob_api_ranges] + assert_eq!(slices.value(0), b"inline"); + assert_eq!(slices.value(1), b"second"); + assert_eq!(slices.value(2), b"image"); + assert_eq!(parts[0].as_ref(), b"second"); + assert_eq!(parts[1].as_ref(), b"image"); + + std::env::set_current_dir(original_dir).unwrap(); +} + +async fn deferred_fetch() { + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob("image", true), + ])); + let table = db + .create_empty_table("photos", schema) + .execute() + .await + .unwrap(); + let input_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("image", DataType::LargeBinary, true), + ])); + let batch = RecordBatch::try_new( + input_schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1_i64])), + Arc::new(LargeBinaryArray::from_iter_values([ + b"deferred-bytes".as_slice() + ])), + ], + ) + .unwrap(); + let reader: Box = Box::new( + RecordBatchIterator::new(vec![Ok(batch)].into_iter(), input_schema), + ); + table.add(reader).execute().await.unwrap(); + + let described = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(descriptor_kind(&described[0], 0), 0); + assert!(described[0].column_by_name("_rowid").is_none()); + + let located = table + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let row_id = located[0] + .column_by_name("_rowid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + let payloads = table.fetch_blobs("image", &[row_id]).await.unwrap(); + let handles = table.fetch_blob_files("image", &[row_id]).await.unwrap(); + let streamed = handles[0] + .as_ref() + .unwrap() + .read_range(0..payloads.value(0).len() as u64) + .await + .unwrap(); + handles[0].as_ref().unwrap().close().await.unwrap(); + + assert_eq!(payloads.value(0), b"deferred-bytes"); + assert_eq!(streamed.as_ref(), b"deferred-bytes"); +} + +async fn storage_tiers() { + let cases = [ + (1_i64, marked(INLINE_MAX, 11), 0_u8), + (2_i64, marked(INLINE_MAX + 1, 22), 1_u8), + (3_i64, marked(DEDICATED_MIN, 33), 1_u8), + (4_i64, marked(DEDICATED_MIN + 1, 44), 2_u8), + ]; + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob("image", true), + ])); + let table = db + .create_empty_table("tiers", schema) + .execute() + .await + .unwrap(); + let input_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("image", DataType::LargeBinary, true), + ])); + let batch = RecordBatch::try_new( + input_schema.clone(), + vec![ + Arc::new(Int64Array::from_iter_values(cases.iter().map(|row| row.0))), + Arc::new(LargeBinaryArray::from_iter_values( + cases.iter().map(|row| row.1.as_slice()), + )), + ], + ) + .unwrap(); + let reader: Box = Box::new( + RecordBatchIterator::new(vec![Ok(batch)].into_iter(), input_schema), + ); + table.add(reader).execute().await.unwrap(); + + let described = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let located = table + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut kind_by_id = std::collections::HashMap::new(); + for batch in &described { + let ids = batch + .column_by_name("id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + kind_by_id.insert(ids.value(row), descriptor_kind(batch, row)); + } + } + let mut row_id_by_id = std::collections::HashMap::new(); + for batch in &located { + let ids = batch + .column_by_name("id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let row_ids = batch + .column_by_name("_rowid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + row_id_by_id.insert(ids.value(row), row_ids.value(row)); + } + } + + for (id, payload, kind) in &cases { + assert_eq!(kind_by_id[id], *kind); + let row_id = row_id_by_id[id]; + let fetched = table.fetch_blobs("image", &[row_id]).await.unwrap(); + assert_eq!(fetched.value(0), payload.as_slice()); + let handles = table.fetch_blob_files("image", &[row_id]).await.unwrap(); + let handle = handles[0].as_ref().unwrap(); + let head = handle.read_range(0..1).await.unwrap(); + let tail = handle + .read_range((payload.len() - 1) as u64..payload.len() as u64) + .await + .unwrap(); + handle.close().await.unwrap(); + assert_eq!(head.as_ref(), &payload[..1]); + assert_eq!(tail.as_ref(), &payload[payload.len() - 1..]); + } +} + +fn marked(size: usize, marker: u8) -> Vec { + let mut payload = vec![0_u8; size]; + payload[0] = marker; + payload[size - 1] = marker; + payload +} + +fn descriptor_kind(batch: &RecordBatch, row: usize) -> u8 { + let image = batch + .column_by_name("image") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap_or_else(|| panic!("image column was {}", batch.schema())); + image + .column_by_name("kind") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(row) +} diff --git a/docs/web-tests/blob-v2/ts/multimodal.test.ts b/docs/web-tests/blob-v2/ts/multimodal.test.ts new file mode 100644 index 000000000..b253ee9b2 --- /dev/null +++ b/docs/web-tests/blob-v2/ts/multimodal.test.ts @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { chdir, cwd } from "node:process"; +import { test } from "node:test"; +import * as arrow from "apache-arrow"; +import { Buffer } from "node:buffer"; +import * as lancedb from "@lancedb/lancedb"; + +const INLINE_MAX = 64 * 1024; +const DEDICATED_MIN = 4 * 1024 * 1024; + +function marked(size: number, marker: number): Buffer { + const payload = Buffer.alloc(size); + payload[0] = marker; + payload[payload.length - 1] = marker; + return payload; +} + +function kindOf(value: unknown): number { + assert.equal(typeof value, "object"); + assert.ok(value !== null); + const kind = (value as { kind?: unknown }).kind; + assert.equal(typeof kind, "number"); + return kind; +} + +test("blob column tutorial", async () => { + const directory = mkdtempSync(join(tmpdir(), "blob-v2-")); + const previous = cwd(); + chdir(directory); + try { + // --8<-- [start:blob_api_setup] + const db = await lancedb.connect("./blob_db"); + // --8<-- [end:blob_api_setup] + + // --8<-- [start:blob_api_schema] + const blobSchema = new arrow.Schema([ + new arrow.Field("id", new arrow.Int64()), + new arrow.Field("label", new arrow.Utf8()), + lancedb.blob("image"), + ]); + // --8<-- [end:blob_api_schema] + + // --8<-- [start:blob_api_ingest] + const blobTable = await db.createEmptyTable("photos", blobSchema, { + mode: "overwrite", + }); + + await blobTable.add([ + { id: 1n, label: "door", image: Buffer.from("inline_image_bytes") }, + { id: 2n, label: "window", image: Buffer.from("second_image_bytes") }, + ]); + // --8<-- [end:blob_api_ingest] + assert.equal(await blobTable.countRows(), 2); + + // --8<-- [start:blob_api_files] + const rows = await blobTable + .query() + .select(["id", "label"]) + .withRowId() + .toArray(); + const rowIds = rows.map((row) => row._rowid as bigint); + + const [image] = await blobTable.fetchBlobFiles("image", [rowIds[0]!]); + const header = await image!.readRange(0n, 6n); + await image!.close(); + // --8<-- [end:blob_api_files] + assert.equal(header.toString("utf8"), "inline"); + + // --8<-- [start:blob_api_fetch] + const payloads = await blobTable.fetchBlobs("image", rowIds); + // --8<-- [end:blob_api_fetch] + assert.equal(payloads.length, 2); + + // --8<-- [start:blob_api_ranges] + const [secondImage] = await blobTable.fetchBlobFiles("image", [rowIds[1]!]); + const parts = await secondImage!.readRanges([ + { start: 0n, end: 6n }, + { start: 7n, end: 12n }, + ]); + await secondImage!.close(); + // --8<-- [end:blob_api_ranges] + assert.deepEqual( + parts.map((part) => part.toString("utf8")), + ["second", "image"], + ); + + // --8<-- [start:blob_api_bytes_mode] + const withBytes = await blobTable + .query() + .select(["id", "image"]) + .toArray({ blobMode: "bytes" }); + const firstImage: Uint8Array | null = withBytes[0].image; + // --8<-- [end:blob_api_bytes_mode] + assert.equal(Buffer.from(firstImage!).toString("utf8"), "inline_image_bytes"); + assert.equal(Object.hasOwn(withBytes[0], "_rowid"), false); + } finally { + chdir(previous); + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("eager query returns blob bytes without a row id", async () => { + const directory = mkdtempSync(join(tmpdir(), "blob-v2-eager-")); + try { + const db = await lancedb.connect(directory); + const schema = new arrow.Schema([ + new arrow.Field("id", new arrow.Int64()), + lancedb.blob("image"), + ]); + const table = await db.createEmptyTable("photos", schema); + const payload = Buffer.from("inline-bytes"); + await table.add([{ id: 1n, image: payload }]); + + const rows = await table + .query() + .where("id = 1") + .select(["id", "image"]) + .toArray({ blobMode: "bytes" }); + + assert.equal(rows.length, 1); + assert.equal(Object.hasOwn(rows[0], "_rowid"), false); + assert.equal(Buffer.from(rows[0].image).toString("utf8"), "inline-bytes"); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("deferred fetch reads a blob by row id", async () => { + const directory = mkdtempSync(join(tmpdir(), "blob-v2-deferred-")); + try { + const db = await lancedb.connect(directory); + const schema = new arrow.Schema([ + new arrow.Field("id", new arrow.Int64()), + lancedb.blob("image"), + ]); + const table = await db.createEmptyTable("photos", schema); + await table.add([{ id: 1n, image: Buffer.from("deferred-bytes") }]); + + const described = await table + .query() + .where("id = 1") + .select(["id", "image"]) + .toArray(); + assert.equal(kindOf(described[0].image), 0); + assert.equal(Object.hasOwn(described[0], "_rowid"), false); + + const found = await table.query().where("id = 1").select(["id"]).withRowId().toArray(); + const rowId = found[0]._rowid as bigint; + const payloads = await table.fetchBlobs("image", [rowId]); + const [handle] = await table.fetchBlobFiles("image", [rowId]); + const streamed = await handle!.readRange(0n, handle!.size()); + await handle!.close(); + + assert.equal(Buffer.from(payloads[0]).toString("utf8"), "deferred-bytes"); + assert.equal(Buffer.from(streamed).toString("utf8"), "deferred-bytes"); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("storage tiers round-trip", async () => { + const cases = [ + { id: 1n, image: marked(INLINE_MAX, 11), kind: 0 }, + { id: 2n, image: marked(INLINE_MAX + 1, 22), kind: 1 }, + { id: 3n, image: marked(DEDICATED_MIN, 33), kind: 1 }, + { id: 4n, image: marked(DEDICATED_MIN + 1, 44), kind: 2 }, + ]; + const directory = mkdtempSync(join(tmpdir(), "blob-v2-tiers-")); + try { + const db = await lancedb.connect(directory); + const schema = new arrow.Schema([ + new arrow.Field("id", new arrow.Int64()), + lancedb.blob("image"), + ]); + const table = await db.createEmptyTable("tiers", schema); + await table.add(cases.map(({ id, image }) => ({ id, image }))); + + const described = await table.query().select(["id", "image"]).toArray(); + const located = await table.query().select(["id"]).withRowId().toArray(); + const rowIdByValue = new Map(located.map((row) => [row.id as bigint, row._rowid as bigint])); + + for (const item of cases) { + const descriptor = described.find((row) => row.id === item.id); + assert.ok(descriptor); + assert.equal(kindOf(descriptor.image), item.kind); + const rowId = rowIdByValue.get(item.id); + assert.ok(rowId !== undefined); + const [payload] = await table.fetchBlobs("image", [rowId]); + assert.deepEqual(Buffer.from(payload), item.image); + const [handle] = await table.fetchBlobFiles("image", [rowId]); + const streamed = await handle!.read(); + await handle!.close(); + assert.deepEqual(streamed, item.image); + } + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); diff --git a/docs/web-tests/blob-v2/ts/package-lock.json b/docs/web-tests/blob-v2/ts/package-lock.json new file mode 100644 index 000000000..9426f2b18 --- /dev/null +++ b/docs/web-tests/blob-v2/ts/package-lock.json @@ -0,0 +1,1565 @@ +{ + "name": "lancedb-blob-v2-docs", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "lancedb-blob-v2-docs", + "version": "0.0.0", + "dependencies": { + "@lancedb/lancedb": "0.41.0-beta.8", + "apache-arrow": "21.2.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@huggingface/jinja": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.3.4.tgz", + "integrity": "sha512-kFFQWJiWwvxezKQnvH1X7GjsECcMljFx+UZK9hx6P26aVHwwidJVTB0ptLfRVZQvVkOGHoMmTGvo4nT0X9hHOA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@huggingface/transformers": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-3.0.2.tgz", + "integrity": "sha512-lTyS81eQazMea5UCehDGFMfdcNRZyei7XQLH5X6j4AhA/18Ka0+5qPgMxUxuZLU4xkv60aY2KNz9Yzthv6WVJg==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@huggingface/jinja": "^0.3.0", + "onnxruntime-node": "1.19.2", + "onnxruntime-web": "1.21.0-dev.20241024-d9ca84ef96", + "sharp": "^0.33.5" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", + "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", + "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", + "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", + "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", + "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", + "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz", + "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz", + "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz", + "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", + "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.0.5" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", + "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz", + "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz", + "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz", + "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz", + "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.2.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz", + "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", + "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@lancedb/lancedb": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb/-/lancedb-0.41.0-beta.8.tgz", + "integrity": "sha512-W6Sw1rJgJJAT75jXom2fkNvE976iH8EO74ShytymS6sEzCj63gQXQqCYg+jPvQva/dnvYQiOeOGsdkGDFwKmlA==", + "cpu": [ + "x64", + "arm64" + ], + "license": "Apache-2.0", + "os": [ + "darwin", + "linux", + "win32" + ], + "dependencies": { + "@opentelemetry/api": "^1.9.0", + "reflect-metadata": "^0.2.2" + }, + "engines": { + "node": ">= 22" + }, + "optionalDependencies": { + "@huggingface/transformers": "3.0.2", + "@lancedb/lancedb-darwin-arm64": "0.41.0-beta.8", + "@lancedb/lancedb-linux-arm64-gnu": "0.41.0-beta.8", + "@lancedb/lancedb-linux-arm64-musl": "0.41.0-beta.8", + "@lancedb/lancedb-linux-x64-gnu": "0.41.0-beta.8", + "@lancedb/lancedb-linux-x64-musl": "0.41.0-beta.8", + "@lancedb/lancedb-win32-arm64-msvc": "0.41.0-beta.8", + "@lancedb/lancedb-win32-x64-msvc": "0.41.0-beta.8", + "openai": "4.29.2" + }, + "peerDependencies": { + "@types/node": ">=22", + "apache-arrow": ">=15.0.0 <22.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@lancedb/lancedb-darwin-arm64": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-darwin-arm64/-/lancedb-darwin-arm64-0.41.0-beta.8.tgz", + "integrity": "sha512-M1o7VQmB1th9L8YnOqXlxruB1jW6Gns9rTS5H5rCzjv25CTEq/mw9uwl6jrDlLiuVSLWJ89Jj2EDUMH8ZKkEbw==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-linux-arm64-gnu": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-gnu/-/lancedb-linux-arm64-gnu-0.41.0-beta.8.tgz", + "integrity": "sha512-X5lJ2JWMHIrvq/IkkHPjQ3v6myv2jZKK/eayiLe/8Wasxt6LIm9Z7KJYLtXpp5y+kqncAmMRP+BaAJAY02FgvQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-linux-arm64-musl": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-musl/-/lancedb-linux-arm64-musl-0.41.0-beta.8.tgz", + "integrity": "sha512-9reTx4gKOIZlx1hNp3s+O2tMv56aF0bp+kt22+XniwL6xLhVyMlyp+cRnhReVqbvu3Ykqe1lZEQO8U3EXuxSFg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-linux-x64-gnu": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-gnu/-/lancedb-linux-x64-gnu-0.41.0-beta.8.tgz", + "integrity": "sha512-tu9RvxpNNVeUOIWrjmsZgufP+ebBvNES0x4D4qHpPsUJXwdR/LJ4QjON57NvuyQ9CZTUL7Rdk8xbzg+nvlmAaQ==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-linux-x64-musl": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-musl/-/lancedb-linux-x64-musl-0.41.0-beta.8.tgz", + "integrity": "sha512-EFMuG0GaFO0BPNfY/XRo66nDKKq3ndyiq/t+P4P500cagDtFgCpZphhF8Q+BkQpQ1b+ZgVS2Uaxu5tOyo0SPhg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-win32-arm64-msvc": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-arm64-msvc/-/lancedb-win32-arm64-msvc-0.41.0-beta.8.tgz", + "integrity": "sha512-+vKZHO0CzZgoqqu9izXP2Ea0fBQ/PtolNz3B9JZItR5nc2w12bknA57K1sS06H74BBU9Yie2hDHNt3qzdPBEdw==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-win32-x64-msvc": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-x64-msvc/-/lancedb-win32-x64-msvc-0.41.0-beta.8.tgz", + "integrity": "sha512-qSgWdgh9TzUiurd658ynzD4BxI/6E9yih7HFuFxvi8S+Zcp/NNiDpgrMWLQn/KfvorVJg9XBO8nhZMtg34UTGw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz", + "integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@types/node": { + "version": "25.9.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.9.tgz", + "integrity": "sha512-b4e2xxj/yMeT2hNlD6x7zNFiQK2Dlmkb9CQ6v3/1G2RezKN4YS2lcEv8lzGm1mhs4f2lM4yNAMI/zUDBZBBt7w==", + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.4" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "optional": true, + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/agentkeepalive": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", + "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/apache-arrow": { + "version": "21.2.0", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-21.2.0.tgz", + "integrity": "sha512-Hxe6Agq26gQOM954qpzYSllJBPJl+e16U5CkfuMUhLrNba+5nKkttIVlflaovN6oaTratqMGAO8H5u/aNhmHWQ==", + "license": "Apache-2.0", + "dependencies": { + "@types/node": "^25.2.0", + "flatbuffers": "^25.1.24", + "json-with-bigint": "^3.5.3", + "tslib": "^2.6.2" + }, + "bin": { + "arrow2csv": "bin/arrow2csv.js" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT", + "optional": true + }, + "node_modules/base-64": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-0.1.0.tgz", + "integrity": "sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==", + "optional": true + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/charenc": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", + "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==", + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": "*" + } + }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "license": "BlueOak-1.0.0", + "optional": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "license": "MIT", + "optional": true, + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT", + "optional": true + }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "license": "MIT", + "optional": true, + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "optional": true, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/crypt": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", + "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": "*" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/digest-fetch": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/digest-fetch/-/digest-fetch-1.3.0.tgz", + "integrity": "sha512-CGJuv6iKNM7QyZlM2T3sPAdZWd/p9zQiRNS9G+9COUCwzWFTs0Xp8NF5iePx7wtvhDykReiRRrSeNb4oMmB8lA==", + "license": "ISC", + "optional": true, + "dependencies": { + "base-64": "^0.1.0", + "md5": "^2.3.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", + "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==", + "license": "MIT", + "optional": true + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", + "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, + "node_modules/formdata-node/node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", + "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 14" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "optional": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", + "license": "ISC", + "optional": true + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "optional": true, + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "optional": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/is-arrayish": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz", + "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==", + "license": "MIT", + "optional": true + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "license": "MIT", + "optional": true + }, + "node_modules/json-with-bigint": { + "version": "3.5.12", + "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.12.tgz", + "integrity": "sha512-uwbF/wSSuOgC7qqlq27Xp5B6a2MHVug3t0idZdTqu0JnlFvgJuH7ju+KAk/J06C7GfhoYy2gnb9wz2INqcne7w==", + "license": "MIT" + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0", + "optional": true + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/md5": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz", + "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==", + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "charenc": "0.0.2", + "crypt": "0.0.2", + "is-buffer": "~1.1.6" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "optional": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", + "optional": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "license": "MIT", + "optional": true, + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT", + "optional": true + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "optional": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/onnxruntime-common": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.19.2.tgz", + "integrity": "sha512-a4R7wYEVFbZBlp0BfhpbFWqe4opCor3KM+5Wm22Az3NGDcQMiU2hfG/0MfnBs+1ZrlSGmlgWeMcXQkDk1UFb8Q==", + "license": "MIT", + "optional": true + }, + "node_modules/onnxruntime-node": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.19.2.tgz", + "integrity": "sha512-9eHMP/HKbbeUcqte1JYzaaRC8JPn7ojWeCeoyShO86TOR97OCyIyAIOGX3V95ErjslVhJRXY8Em/caIUc0hm1Q==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "onnxruntime-common": "1.19.2", + "tar": "^7.0.1" + } + }, + "node_modules/onnxruntime-web": { + "version": "1.21.0-dev.20241024-d9ca84ef96", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.21.0-dev.20241024-d9ca84ef96.tgz", + "integrity": "sha512-ANSQfMALvCviN3Y4tvTViKofKToV1WUb2r2VjZVCi3uUBPaK15oNJyIxhsNyEckBr/Num3JmSXlkHOD8HfVzSQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "flatbuffers": "^1.12.0", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.20.0-dev.20241016-2b8fc5529b", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, + "node_modules/onnxruntime-web/node_modules/flatbuffers": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-1.12.0.tgz", + "integrity": "sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==", + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true + }, + "node_modules/onnxruntime-web/node_modules/onnxruntime-common": { + "version": "1.20.0-dev.20241016-2b8fc5529b", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.20.0-dev.20241016-2b8fc5529b.tgz", + "integrity": "sha512-KZK8b6zCYGZFjd4ANze0pqBnqnFTS3GIVeclQpa2qseDpXrCQJfkWBixRcrZShNhm3LpFOZ8qJYFC5/qsJK9WQ==", + "license": "MIT", + "optional": true + }, + "node_modules/openai": { + "version": "4.29.2", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.29.2.tgz", + "integrity": "sha512-cPkT6zjEcE4qU5OW/SoDDuXEsdOLrXlAORhzmaguj5xZSPlgKvLhi27sFWhLKj07Y6WKNWxcwIbzm512FzTBNQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "digest-fetch": "^1.3.0", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7", + "web-streams-polyfill": "^3.2.1" + }, + "bin": { + "openai": "bin/cli" + } + }, + "node_modules/openai/node_modules/@types/node": { + "version": "18.19.130", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", + "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", + "license": "MIT", + "optional": true, + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/openai/node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "license": "MIT", + "optional": true + }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", + "license": "MIT", + "optional": true + }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", + "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", + "hasInstallScript": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.6.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "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" + } + }, + "node_modules/simple-swizzle": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", + "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==", + "license": "MIT", + "optional": true, + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/tar": { + "version": "7.5.22", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", + "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", + "license": "BlueOak-1.0.0", + "optional": true, + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT", + "optional": true + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "license": "MIT" + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause", + "optional": true + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "license": "BlueOak-1.0.0", + "optional": true, + "engines": { + "node": ">=18" + } + } + } +} diff --git a/docs/web-tests/blob-v2/ts/package.json b/docs/web-tests/blob-v2/ts/package.json new file mode 100644 index 000000000..f39495edd --- /dev/null +++ b/docs/web-tests/blob-v2/ts/package.json @@ -0,0 +1,16 @@ +{ + "name": "lancedb-blob-v2-docs", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "test": "node --experimental-strip-types --test multimodal.test.ts" + }, + "engines": { + "node": ">=22.6.0" + }, + "dependencies": { + "@lancedb/lancedb": "0.41.0-beta.8", + "apache-arrow": "21.2.0" + } +} diff --git a/docs/web-tests/py/test_doc_storage_examples.py b/docs/web-tests/py/test_doc_storage_examples.py index 13bedb731..99ab4a514 100644 --- a/docs/web-tests/py/test_doc_storage_examples.py +++ b/docs/web-tests/py/test_doc_storage_examples.py @@ -7,6 +7,36 @@ import pyarrow as pa import pytest +def test_compaction_tuning(mem_db): + payload = b"x" * 1016 + table = mem_db.create_table( + "compaction_tuning", [{"id": i, "payload": payload} for i in range(32)] + ) + table.add([{"id": i, "payload": payload} for i in range(32, 64)]) + assert table.stats()["fragment_stats"]["num_fragments"] == 2 + + # --8<-- [start:storage_compaction_tuning] + from lancedb import CompactionOptions + + desired_fragment_bytes = 64 * 1024 + average_row_bytes = 1024 # Estimate from representative rows. + options: CompactionOptions = { + "target_rows_per_fragment": max(1, desired_fragment_bytes // average_row_bytes), + "batch_size": 16, + "num_threads": 1, + } + table.optimize(compaction_options=options) + # --8<-- [end:storage_compaction_tuning] + + assert table.stats()["fragment_stats"]["num_fragments"] == 1 + assert table.count_rows() == 64 + + table.add([{"id": 64, "payload": payload}]) + table.optimize(compaction_options=options) + assert table.stats()["fragment_stats"]["num_fragments"] == 2 + assert sorted(table.to_arrow()["id"].to_pylist()) == list(range(65)) + + def test_rebuild_vector_index(tmp_db): rng = np.random.default_rng(7) table = tmp_db.create_table( diff --git a/docs/web-tests/py/test_function.py b/docs/web-tests/py/test_function.py index f66a50aec..a89424316 100644 --- a/docs/web-tests/py/test_function.py +++ b/docs/web-tests/py/test_function.py @@ -50,6 +50,25 @@ def describe(value: float): return {"half": value / 2, "note": None} +# --8<-- [start:function_class_define] +@udf(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. + from sentence_transformers import SentenceTransformer + + self.model = SentenceTransformer(model) + + def __call__(self, text: str) -> list[float]: + return self.model.encode(text).tolist() + + def close(self): + del self.model + + +# --8<-- [end:function_class_define] + + # 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. SERVICE_REPLY = ( @@ -166,6 +185,31 @@ def test_function_version_binds_a_column(tmp_path): table.add_columns({"doubled": application}) +def test_class_function_is_constructed_only_where_it_runs(): + # Registration reads __init__'s signature; it never constructs the class, + # so the model's package need not be installed here. + assert "sentence_transformers" not in sys.modules + signature = embed.registration_request.signature + assert [ + (field.name, field.arrow_type, field.nullable) + for field in signature.initialization + ] == [("model", "utf8", True)] + assert [(p.name, p.arrow_type) for p in signature.inputs] == [("text", "utf8")] + assert "sentence_transformers" not in sys.modules + + embedder = registered_version(embed) + # --8<-- [start:function_class_apply] + from lancedb import col + + application = embedder(text=col("text"), model="all-mpnet-base-v2") + # --8<-- [end:function_class_apply] + assert application.initialization == {"model": "all-mpnet-base-v2"} + # The default applies to an omitted field. + assert embedder(text=col("text")).initialization == {} + with pytest.raises(TypeError, match="unknown arguments"): + embedder(text=col("text"), device="cuda") + + def test_function_enterprise(monkeypatch): require_deployment() diff --git a/docs/web-tests/py/test_integrations.py b/docs/web-tests/py/test_integrations.py index 577847504..84c4560ae 100644 --- a/docs/web-tests/py/test_integrations.py +++ b/docs/web-tests/py/test_integrations.py @@ -93,7 +93,7 @@ def test_embedding_cohere_usage() -> None: cohere = ( EmbeddingFunctionRegistry.get_instance() .get("cohere") - .create(name="embed-multilingual-v2.0") + .create(name="embed-multilingual-v3.0") ) class TextModel(LanceModel): diff --git a/docs/web-tests/py/test_multimodal.py b/docs/web-tests/py/test_multimodal.py index cb4a647c3..dbce74ca8 100644 --- a/docs/web-tests/py/test_multimodal.py +++ b/docs/web-tests/py/test_multimodal.py @@ -1,137 +1,134 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +import io import pytest +import lancedb +import numpy as np +import pyarrow as pa + try: + # --8<-- [start:multimodal_imports] + import io import lancedb import numpy as np import pyarrow as pa - import io from PIL import Image + # --8<-- [end:multimodal_imports] except ImportError: pass -# --8<-- [start:multimodal_imports] -import lancedb -import pyarrow as pa -import pandas as pd -import numpy as np -import io -from PIL import Image -# --8<-- [end:multimodal_imports] def test_multimodal_ingestion(db_path_factory): - # Ensure dependencies are available pytest.importorskip("PIL") - pytest.importorskip("lancedb") - pytest.importorskip("numpy") # --8<-- [start:create_dummy_data] - # Create some dummy images def create_dummy_image(color): - img = Image.new('RGB', (100, 100), color=color) + img = Image.new("RGB", (100, 100), color=color) buf = io.BytesIO() - img.save(buf, format='PNG') + img.save(buf, format="PNG") return buf.getvalue() - # Create dataset with metadata, vectors, and image blobs data = [ { "id": 1, "filename": "red_square.png", "vector": np.random.rand(128).astype(np.float32), - "image_blob": create_dummy_image('red'), - "label": "red" + "image_blob": create_dummy_image("red"), + "label": "red", }, { "id": 2, "filename": "blue_square.png", "vector": np.random.rand(128).astype(np.float32), - "image_blob": create_dummy_image('blue'), - "label": "blue" - } + "image_blob": create_dummy_image("blue"), + "label": "blue", + }, ] # --8<-- [end:create_dummy_data] # --8<-- [start:define_schema] - # Define schema explicitly to ensure image_blob is treated as binary - schema = pa.schema([ - pa.field("id", pa.int32()), - pa.field("filename", pa.string()), - pa.field("vector", pa.list_(pa.float32(), 128)), - pa.field("image_blob", pa.binary()), # Important: Use pa.binary() for blobs - pa.field("label", pa.string()) - ]) + schema = pa.schema( + [ + pa.field("id", pa.int32()), + pa.field("filename", pa.string()), + pa.field("vector", pa.list_(pa.float32(), 128)), + pa.field("image_blob", pa.binary()), + pa.field("label", pa.string()), + ] + ) # --8<-- [end:define_schema] - db_uri = db_path_factory("multimodal_db") - db = lancedb.connect(db_uri) + db = lancedb.connect(db_path_factory("multimodal_db")) # --8<-- [start:ingest_data] tbl = db.create_table("images", data=data, schema=schema, mode="overwrite") # --8<-- [end:ingest_data] - + assert len(tbl) == 2 # --8<-- [start:search_data] - # Search for similar images query_vector = np.random.rand(128).astype(np.float32) results = tbl.search(query_vector).limit(1).to_pandas() # --8<-- [end:search_data] # --8<-- [start:process_results] - # Convert back to PIL Image for _, row in results.iterrows(): - image_bytes = row['image_blob'] + image_bytes = row["image_blob"] image = Image.open(io.BytesIO(image_bytes)) print(f"Retrieved image: {row['filename']}, Size: {image.size}") - # You can now use 'image' with other libraries or display it # --8<-- [end:process_results] - + assert len(results) == 1 -def test_blob_api_definition(db_path_factory): - # --8<-- [start:blob_api_schema] + +def test_legacy_blob_api_definition(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + # --8<-- [start:legacy_blob_api_schema] import pyarrow as pa # Define schema with Blob API metadata for lazy loading - schema = pa.schema([ - pa.field("id", pa.int64()), - pa.field( - "video", - pa.large_binary(), - metadata={"lance-encoding:blob": "true"} # Enable Blob API - ), - ]) - # --8<-- [end:blob_api_schema] + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field( + "video", + pa.large_binary(), + metadata={"lance-encoding:blob": "true"}, # Enable Blob API + ), + ] + ) + # --8<-- [end:legacy_blob_api_schema] - # --8<-- [start:blob_api_ingest] + # --8<-- [start:legacy_blob_api_ingest] import lancedb - db = lancedb.connect(db_path_factory("blob_db")) - + db = lancedb.connect("./blob_db") + # Create sample data data = [ {"id": 1, "video": b"fake_video_bytes_1"}, - {"id": 2, "video": b"fake_video_bytes_2"} + {"id": 2, "video": b"fake_video_bytes_2"}, ] - + # Create the table tbl = db.create_table("videos", data=data, schema=schema) - # --8<-- [end:blob_api_ingest] + # --8<-- [end:legacy_blob_api_ingest] assert len(tbl) == 2 -def test_blob_api_to_pandas(db_path_factory): - db = lancedb.connect(db_path_factory("blob_to_pandas_db")) - schema = pa.schema([ - pa.field("id", pa.int64()), - pa.field( - "video", - pa.large_binary(), - metadata={"lance-encoding:blob": "true"}, - ), - ]) +def test_legacy_blob_api_to_pandas(db_path_factory): + db = lancedb.connect(db_path_factory("legacy_blob_to_pandas_db")) + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field( + "video", + pa.large_binary(), + metadata={"lance-encoding:blob": "true"}, + ), + ] + ) tbl = db.create_table( "videos", data=[ @@ -142,7 +139,7 @@ def test_blob_api_to_pandas(db_path_factory): mode="overwrite", ) - # --8<-- [start:blob_api_to_pandas] + # --8<-- [start:legacy_blob_api_to_pandas] # Default: blob columns come back lazily df_lazy = tbl.to_pandas() @@ -154,7 +151,7 @@ def test_blob_api_to_pandas(db_path_factory): # Forward extra kwargs to PyArrow's to_pandas df_typed = tbl.to_pandas(split_blocks=True, self_destruct=True) - # --8<-- [end:blob_api_to_pandas] + # --8<-- [end:legacy_blob_api_to_pandas] assert len(df_lazy) == 2 assert isinstance(df_bytes["video"].iloc[0], bytes) @@ -167,16 +164,18 @@ def test_blob_api_to_pandas(db_path_factory): @pytest.mark.asyncio -async def test_query_to_pandas_kwargs(db_path_factory): - schema = pa.schema([ - pa.field("id", pa.int64()), - pa.field("vector", pa.list_(pa.float32(), 128)), - pa.field( - "video", - pa.large_binary(), - metadata={"lance-encoding:blob": "true"}, - ), - ]) +async def test_legacy_query_to_pandas_kwargs(db_path_factory): + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("vector", pa.list_(pa.float32(), 128)), + pa.field( + "video", + pa.large_binary(), + metadata={"lance-encoding:blob": "true"}, + ), + ] + ) data = [ { "id": i, @@ -186,11 +185,11 @@ async def test_query_to_pandas_kwargs(db_path_factory): for i in range(10) ] - db = lancedb.connect(db_path_factory("query_to_pandas_db")) + db = lancedb.connect(db_path_factory("legacy_query_to_pandas_db")) tbl = db.create_table("search_demo", data=data, schema=schema, mode="overwrite") async_db = await lancedb.connect_async( - str(db_path_factory("query_to_pandas_async_db")) + str(db_path_factory("legacy_query_to_pandas_async_db")) ) tbl_async = await async_db.create_table( "search_demo", data=data, schema=schema, mode="overwrite" @@ -198,7 +197,8 @@ async def test_query_to_pandas_kwargs(db_path_factory): query_vector = np.random.rand(128).astype(np.float32) - # --8<-- [start:query_to_pandas_kwargs] + # fmt: off + # --8<-- [start:legacy_query_to_pandas_kwargs] # Plain scan query: blob_mode is supported end to end df_lazy = ( tbl.search() @@ -223,7 +223,8 @@ async def test_query_to_pandas_kwargs(db_path_factory): .select(["id", "vector"]) .to_pandas(split_blocks=True, self_destruct=True) ) - # --8<-- [end:query_to_pandas_kwargs] + # --8<-- [end:legacy_query_to_pandas_kwargs] + # fmt: on assert len(df_lazy) == 1 assert len(df_bytes) == 1 diff --git a/docs/web-tests/py/test_quickstart.py b/docs/web-tests/py/test_quickstart.py index 779a268d4..bdcb8abff 100644 --- a/docs/web-tests/py/test_quickstart.py +++ b/docs/web-tests/py/test_quickstart.py @@ -119,38 +119,35 @@ async def async_db(request, db_path_factory): await owned.drop_claimed() -def create_characters(db): +def create_frames(db): # --8<-- [start:quickstart_data] data = [ { - "id": "1", - "name": "King Arthur", - "role": "King", - "description": "Leader of Camelot and wielder of Excalibur.", - "stats": {"strength": 4, "magic": 1, "leadership": 5, "wisdom": 4}, - "vector": [0.7, 0.1, 0.9, 0.7], + "frame_id": "1", + "video_id": "clip-1", + "caption": "a robot arm reaching toward a cup", + "stats": {"motion": 3, "sharpness": 4, "exposure": 4, "framing": 3}, + "embedding": [0.7, 0.1, 0.9, 0.7], }, { - "id": "2", - "name": "Merlin", - "role": "Wizard", - "description": "Advisor and prophet with deep magical knowledge.", - "stats": {"strength": 2, "magic": 5, "leadership": 4, "wisdom": 5}, - "vector": [0.2, 0.9, 0.4, 0.9], + "frame_id": "2", + "video_id": "clip-1", + "caption": "a two-finger gripper closing on a cup", + "stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2}, + "embedding": [0.2, 0.9, 0.4, 0.9], }, { - "id": "3", - "name": "Sir Lancelot", - "role": "Knight", - "description": "Legendary knight known for courage and combat skill.", - "stats": {"strength": 5, "magic": 1, "leadership": 3, "wisdom": 3}, - "vector": [0.9, 0.1, 0.5, 0.4], + "frame_id": "3", + "video_id": "clip-2", + "caption": "a robot arm holding a cup steady", + "stats": {"motion": 2, "sharpness": 3, "exposure": 3, "framing": 4}, + "embedding": [0.9, 0.1, 0.5, 0.4], }, ] # --8<-- [end:quickstart_data] # --8<-- [start:quickstart_create_table] - table = db.create_table("characters", data=data, mode="overwrite") + table = db.create_table("frames", data=data, mode="overwrite") # --8<-- [end:quickstart_create_table] assert table.count_rows() == 3 @@ -158,12 +155,11 @@ def create_characters(db): table.add( [ { - "id": "4", - "name": "Morgana", - "role": "Sorceress", - "description": "Powerful sorceress of Avalon.", - "stats": {"strength": 2, "magic": 5, "leadership": 4, "wisdom": 4}, - "vector": [0.3, 0.9, 0.6, 0.8], + "frame_id": "4", + "video_id": "clip-2", + "caption": "a gripper lowering a cup onto the table", + "stats": {"motion": 5, "sharpness": 4, "exposure": 4, "framing": 2}, + "embedding": [0.3, 0.9, 0.6, 0.8], } ] ) @@ -173,153 +169,152 @@ def create_characters(db): def test_quickstart(db): - table = create_characters(db) + table = create_frames(db) # --8<-- [start:quickstart_vector_search_1] - # Search for examples similar to a "wise magical advisor" + # Search for frames similar to "a gripper closing on an object" query_vector = [0.2, 0.8, 0.4, 0.9] # Ensure you run `pip install polars` beforehand result = ( table.search(query_vector) - .select(["name", "role", "description", "_distance"]) + .select(["frame_id", "video_id", "caption", "_distance"]) .limit(2) .to_polars() ) print(result) # --8<-- [end:quickstart_vector_search_1] - assert result["name"].to_list() == ["Merlin", "Morgana"] + assert result["frame_id"].to_list() == ["2", "4"] # --8<-- [start:quickstart_output_pandas] # Ensure you run `pip install pandas` beforehand result = table.search(query_vector).limit(2).to_pandas() print(result) # --8<-- [end:quickstart_output_pandas] - assert result["name"].to_list() == ["Merlin", "Morgana"] + assert result["frame_id"].to_list() == ["2", "4"] # --8<-- [start:quickstart_curate_with_metadata] curated = ( table.search(query_vector) - .where("stats.magic >= 4") - .select(["name", "role", "description", "_distance"]) + .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["name"].to_list() == ["Merlin", "Morgana"] + assert curated["frame_id"].to_list() == ["2", "4"] - curated = table.search(query_vector).where("stats.magic < 4").limit(2).to_list() - assert [row["name"] for row in curated] == ["King Arthur", "Sir Lancelot"] + 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): data = [ { - "id": "2", - "name": "Merlin", - "role": "Wizard", - "description": "Advisor and prophet with deep magical knowledge.", - "stats": {"strength": 2, "magic": 5, "leadership": 4, "wisdom": 5}, - "vector": [0.2, 0.9, 0.4, 0.9], + "frame_id": "2", + "video_id": "clip-1", + "caption": "a two-finger gripper closing on a cup", + "stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2}, + "embedding": [0.2, 0.9, 0.4, 0.9], } ] # --8<-- [start:quickstart_create_table_async] async_table = await async_db.create_table( - "characters", + "frames", data=data, mode="overwrite", ) # --8<-- [end:quickstart_create_table_async] # --8<-- [start:quickstart_vector_search_1_async] - # Search for examples similar to a "wise magical advisor" + # Search for frames similar to "a gripper closing on an object" 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(["name", "role", "description", "_distance"]).limit(2).to_polars() + ).select(["frame_id", "video_id", "caption", "_distance"]).limit(2).to_polars() print(async_result) # --8<-- [end:quickstart_vector_search_1_async] - assert async_result["name"].to_list() == ["Merlin"] + assert async_result["frame_id"].to_list() == ["2"] def test_quickstart_derived_feature(db): - table = create_characters(db) + table = create_frames(db) # --8<-- [start:quickstart_add_feature] table.add_columns( { - "power_score": "cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)" + "quality_score": "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)" } ) # --8<-- [end:quickstart_add_feature] # --8<-- [start:quickstart_query_feature] - features = table.search().select(["name", "role", "power_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["name"], features["power_score"])) == [ - ("King Arthur", 3.5), - ("Merlin", 4.0), - ("Morgana", 3.75), - ("Sir Lancelot", 3.0), + assert sorted(zip(features["frame_id"], features["quality_score"])) == [ + ("1", 3.5), + ("2", 4.0), + ("3", 3.0), + ("4", 3.75), ] -def description_lengths(table): - rows = table.search().select(["description", "description_length"]).to_list() - return {row["description"]: row["description_length"] for row in rows} +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_characters(lancedb.connect(db_path_factory("computed"))) + table = create_frames(lancedb.connect(db_path_factory("computed"))) # --8<-- [start:quickstart_computed_feature] - table.add_columns(computed={"description_length": "length(description)"}) - table.refresh_column("description_length") + table.add_columns(computed={"caption_length": "length(caption)"}) + table.refresh_column("caption_length") # --8<-- [end:quickstart_computed_feature] - lengths = description_lengths(table) + lengths = caption_lengths(table) assert lengths == {text: len(text) for text in lengths} def test_quickstart_computed_column_on_a_deployment(deployment): - table = create_characters(deployment) + table = create_frames(deployment) # --8<-- [start:quickstart_computed_feature_enterprise] - table.add_columns(computed={"description_length": "length(description)"}) - job = table.refresh_column_async("description_length") + table.add_columns(computed={"caption_length": "length(caption)"}) + job = table.refresh_column_async("caption_length") job.wait() # --8<-- [end:quickstart_computed_feature_enterprise] - lengths = description_lengths(table) + lengths = caption_lengths(table) assert len(lengths) == 4 assert lengths == {text: len(text) for text in lengths} with pytest.raises(Exception): - table.refresh_column("description_length") + table.refresh_column("caption_length") def test_quickstart_multimodal(db, tmp_path, monkeypatch): app = tmp_path / "app" (app / "data").mkdir(parents=True) - shutil.copy(IMAGE, app / "data/sir-lancelot.jpg") + shutil.copy(IMAGE, app / "data/sample-frame.jpg") monkeypatch.chdir(app) # --8<-- [start:quickstart_multimodal_bytes] from pathlib import Path - image_bytes = Path("data/sir-lancelot.jpg").read_bytes() + image_bytes = Path("data/sample-frame.jpg").read_bytes() multimodal_table = db.create_table( - "character_images", + "frame_images", data=[ { - "id": "lancelot", - "description": "Portrait of Sir Lancelot", + "frame_id": "thumb-1", + "caption": "Sample frame thumbnail", "image": image_bytes, - "vector": [0.9, 0.1, 0.5, 0.4], + "embedding": [0.9, 0.1, 0.5, 0.4], } ], mode="overwrite", @@ -331,7 +326,7 @@ def test_quickstart_multimodal(db, tmp_path, monkeypatch): def test_quickstart_training(db): - table = create_characters(db) + table = create_frames(db) # --8<-- [start:quickstart_training] import torch @@ -339,15 +334,15 @@ def test_quickstart_training(db): table.add_columns( { - "magic": "cast(stats.magic as float)", - "strength": "cast(stats.strength as float)", + "motion": "cast(stats.motion as float)", + "sharpness": "cast(stats.sharpness as float)", } ) - dataset = Permutation.identity(table).select_columns(["magic", "strength"]) + dataset = Permutation.identity(table).select_columns(["motion", "sharpness"]) dataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, shuffle=True) # --8<-- [end:quickstart_training] batches = list(dataloader) assert len(batches) == 1 - assert set(batches[0]) == {"magic", "strength"} + assert set(batches[0]) == {"motion", "sharpness"} assert all(isinstance(value, torch.Tensor) for value in batches[0].values()) - assert sorted(batches[0]["magic"].tolist()) == [1.0, 1.0, 5.0, 5.0] + assert sorted(batches[0]["motion"].tolist()) == [2.0, 3.0, 5.0, 5.0] diff --git a/docs/web-tests/rs/Cargo.lock b/docs/web-tests/rs/Cargo.lock index 447bae7f6..6e288950e 100644 --- a/docs/web-tests/rs/Cargo.lock +++ b/docs/web-tests/rs/Cargo.lock @@ -5561,9 +5561,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", diff --git a/docs/web-tests/rs/multimodal.rs b/docs/web-tests/rs/multimodal.rs index 8cae02eee..f9531d2d5 100644 --- a/docs/web-tests/rs/multimodal.rs +++ b/docs/web-tests/rs/multimodal.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use arrow_array::types::Float32Type; use arrow_array::{ - BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch, + Array, BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, }; use arrow_schema::{DataType, Field, Schema}; @@ -83,8 +83,9 @@ async fn main() { ], ) .unwrap(); - let image_reader: Box = - Box::new(RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone())); + let image_reader: Box = Box::new( + RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone()), + ); let table = db .create_table("images", image_reader) .mode(CreateTableMode::Overwrite) @@ -137,42 +138,45 @@ async fn main() { let search_rows: usize = results.iter().map(|batch| batch.num_rows()).sum(); assert_eq!(search_rows, 1); - // --8<-- [start:blob_api_schema] - let blob_metadata = HashMap::from([( + // --8<-- [start:legacy_blob_api_schema] + let legacy_blob_metadata = HashMap::from([( "lance-encoding:blob".to_string(), "true".to_string(), )]); - let blob_schema = Schema::new(vec![ + let legacy_blob_schema = Schema::new(vec![ Field::new("id", DataType::Int64, false), - Field::new("video", DataType::LargeBinary, true).with_metadata(blob_metadata), + Field::new("video", DataType::LargeBinary, true).with_metadata(legacy_blob_metadata), ]); - // --8<-- [end:blob_api_schema] + // --8<-- [end:legacy_blob_api_schema] - // --8<-- [start:blob_api_ingest] - let blob_rows = vec![ + // --8<-- [start:legacy_blob_api_ingest] + let legacy_blob_rows = vec![ (1_i64, b"fake_video_bytes_1".to_vec()), (2_i64, b"fake_video_bytes_2".to_vec()), ]; - let blob_schema = Arc::new(blob_schema); - let blob_batch = RecordBatch::try_new( - blob_schema.clone(), + let legacy_blob_schema = Arc::new(legacy_blob_schema); + let legacy_blob_batch = RecordBatch::try_new( + legacy_blob_schema.clone(), vec![ - Arc::new(Int64Array::from_iter_values(blob_rows.iter().map(|row| row.0))), + Arc::new(Int64Array::from_iter_values( + legacy_blob_rows.iter().map(|row| row.0), + )), Arc::new(LargeBinaryArray::from_iter_values( - blob_rows.iter().map(|row| row.1.as_slice()), + legacy_blob_rows.iter().map(|row| row.1.as_slice()), )), ], ) .unwrap(); - let blob_reader: Box = - Box::new(RecordBatchIterator::new(vec![Ok(blob_batch)].into_iter(), blob_schema)); - let blob_table = db - .create_table("videos", blob_reader) + let legacy_blob_reader: Box = Box::new( + RecordBatchIterator::new(vec![Ok(legacy_blob_batch)].into_iter(), legacy_blob_schema), + ); + let legacy_blob_table = db + .create_table("legacy_videos", legacy_blob_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); - // --8<-- [end:blob_api_ingest] - assert_eq!(blob_table.count_rows(None).await.unwrap(), 2); + // --8<-- [end:legacy_blob_api_ingest] + assert_eq!(legacy_blob_table.count_rows(None).await.unwrap(), 2); } diff --git a/docs/web-tests/rs/quickstart.rs b/docs/web-tests/rs/quickstart.rs index f6ea7e0f9..b0df4daba 100644 --- a/docs/web-tests/rs/quickstart.rs +++ b/docs/web-tests/rs/quickstart.rs @@ -16,92 +16,88 @@ use lancedb::arrow::arrow_schema::{DataType, Field, FieldRef, Fields, Schema}; // Define structs representing the data schema #[derive(Debug, Clone)] struct Stats { - strength: i8, - magic: i8, - leadership: i8, - wisdom: i8, + motion: i8, + sharpness: i8, + exposure: i8, + framing: i8, } #[derive(Debug, Clone)] -struct Character { - id: String, - name: String, - role: String, - description: String, +struct Frame { + frame_id: String, + video_id: String, + caption: String, stats: Stats, - vector: [f32; 4], + embedding: [f32; 4], } -fn characters_schema() -> Arc { +fn frames_schema() -> Arc { Arc::new(Schema::new(vec![ - Field::new("id", DataType::LargeUtf8, false), - Field::new("name", DataType::LargeUtf8, false), - Field::new("role", DataType::LargeUtf8, false), - Field::new("description", DataType::LargeUtf8, false), + Field::new("frame_id", DataType::LargeUtf8, false), + Field::new("video_id", DataType::LargeUtf8, false), + Field::new("caption", DataType::LargeUtf8, false), Field::new( "stats", DataType::Struct(Fields::from(vec![ - Arc::new(Field::new("strength", DataType::Int8, false)), - Arc::new(Field::new("magic", DataType::Int8, false)), - Arc::new(Field::new("leadership", DataType::Int8, false)), - Arc::new(Field::new("wisdom", DataType::Int8, false)), + Arc::new(Field::new("motion", DataType::Int8, false)), + Arc::new(Field::new("sharpness", DataType::Int8, false)), + Arc::new(Field::new("exposure", DataType::Int8, false)), + Arc::new(Field::new("framing", DataType::Int8, false)), ])), false, ), Field::new( - "vector", + "embedding", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), false, ), ])) } -fn characters_to_reader( +fn frames_to_reader( schema: Arc, - rows: &[Character], + rows: &[Frame], ) -> Box { - let ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.id.as_str())); - let names = LargeStringArray::from_iter_values(rows.iter().map(|row| row.name.as_str())); - let roles = LargeStringArray::from_iter_values(rows.iter().map(|row| row.role.as_str())); - let descriptions = - LargeStringArray::from_iter_values(rows.iter().map(|row| row.description.as_str())); + 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 strength = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.strength)); - let magic = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.magic)); - let leadership = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.leadership)); - let wisdom = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.wisdom)); + 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)); + let exposure = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.exposure)); + let framing = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.framing)); let stats_fields: Vec = vec![ - Arc::new(Field::new("strength", DataType::Int8, false)), - Arc::new(Field::new("magic", DataType::Int8, false)), - Arc::new(Field::new("leadership", DataType::Int8, false)), - Arc::new(Field::new("wisdom", DataType::Int8, false)), + Arc::new(Field::new("motion", DataType::Int8, false)), + Arc::new(Field::new("sharpness", DataType::Int8, false)), + Arc::new(Field::new("exposure", DataType::Int8, false)), + Arc::new(Field::new("framing", DataType::Int8, false)), ]; let stats = StructArray::new( stats_fields.into(), vec![ - Arc::new(strength), - Arc::new(magic), - Arc::new(leadership), - Arc::new(wisdom), + Arc::new(motion), + Arc::new(sharpness), + Arc::new(exposure), + Arc::new(framing), ], None, ); - let vectors = FixedSizeListArray::from_iter_primitive::( + let embeddings = FixedSizeListArray::from_iter_primitive::( rows.iter() - .map(|row| Some(row.vector.iter().copied().map(Some).collect::>())), + .map(|row| Some(row.embedding.iter().copied().map(Some).collect::>())), 4, ); let batch = RecordBatch::try_new( schema.clone(), vec![ - Arc::new(ids), - Arc::new(names), - Arc::new(roles), - Arc::new(descriptions), + Arc::new(frame_ids), + Arc::new(video_ids), + Arc::new(captions), Arc::new(stats), - Arc::new(vectors), + Arc::new(embeddings), ], ) .unwrap(); @@ -121,44 +117,41 @@ async fn main() { // --8<-- [start:quickstart_data] let data = vec![ - Character { - id: "1".to_string(), - name: "King Arthur".to_string(), - role: "King".to_string(), - description: "Leader of Camelot and wielder of Excalibur.".to_string(), + Frame { + frame_id: "1".to_string(), + video_id: "clip-1".to_string(), + caption: "a robot arm reaching toward a cup".to_string(), stats: Stats { - strength: 4, - magic: 1, - leadership: 5, - wisdom: 4, + motion: 3, + sharpness: 4, + exposure: 4, + framing: 3, }, - vector: [0.7, 0.1, 0.9, 0.7], + embedding: [0.7, 0.1, 0.9, 0.7], }, - Character { - id: "2".to_string(), - name: "Merlin".to_string(), - role: "Wizard".to_string(), - description: "Advisor and prophet with deep magical knowledge.".to_string(), + Frame { + frame_id: "2".to_string(), + video_id: "clip-1".to_string(), + caption: "a two-finger gripper closing on a cup".to_string(), stats: Stats { - strength: 2, - magic: 5, - leadership: 4, - wisdom: 5, + motion: 5, + sharpness: 4, + exposure: 5, + framing: 2, }, - vector: [0.2, 0.9, 0.4, 0.9], + embedding: [0.2, 0.9, 0.4, 0.9], }, - Character { - id: "3".to_string(), - name: "Sir Lancelot".to_string(), - role: "Knight".to_string(), - description: "Legendary knight known for courage and combat skill.".to_string(), + Frame { + frame_id: "3".to_string(), + video_id: "clip-2".to_string(), + caption: "a robot arm holding a cup steady".to_string(), stats: Stats { - strength: 5, - magic: 1, - leadership: 3, - wisdom: 3, + motion: 2, + sharpness: 3, + exposure: 3, + framing: 4, }, - vector: [0.9, 0.1, 0.5, 0.4], + embedding: [0.9, 0.1, 0.5, 0.4], }, ]; // --8<-- [end:quickstart_data] @@ -166,9 +159,9 @@ async fn main() { // --8<-- [start:quickstart_create_table] use lancedb::database::CreateTableMode; - let schema = characters_schema(); + let schema = frames_schema(); let table = db - .create_table("characters", characters_to_reader(schema.clone(), &data)) + .create_table("frames", frames_to_reader(schema.clone(), &data)) .mode(CreateTableMode::Overwrite) .execute() .await @@ -177,21 +170,20 @@ async fn main() { assert_eq!(table.count_rows(None).await.unwrap(), 3); // --8<-- [start:quickstart_add_data] - let more_data = vec![Character { - id: "4".to_string(), - name: "Morgana".to_string(), - role: "Sorceress".to_string(), - description: "Powerful sorceress of Avalon.".to_string(), + let more_data = vec![Frame { + frame_id: "4".to_string(), + video_id: "clip-2".to_string(), + caption: "a gripper lowering a cup onto the table".to_string(), stats: Stats { - strength: 2, - magic: 5, - leadership: 4, - wisdom: 4, + motion: 5, + sharpness: 4, + exposure: 4, + framing: 2, }, - vector: [0.3, 0.9, 0.6, 0.8], + embedding: [0.3, 0.9, 0.6, 0.8], }]; table - .add(characters_to_reader(schema.clone(), &more_data)) + .add(frames_to_reader(schema.clone(), &more_data)) .execute() .await .unwrap(); @@ -202,7 +194,7 @@ async fn main() { use lancedb::arrow::IntoPolars; use lancedb::query::{ExecutableQuery, QueryBase, Select}; - // Search for examples similar to a "wise magical advisor" + // Search for frames similar to "a gripper closing on an object" let query_vector = [0.2, 0.8, 0.4, 0.9]; let result = table @@ -210,9 +202,9 @@ async fn main() { .nearest_to(&query_vector) .unwrap() .select(Select::Columns(vec![ - "name".to_string(), - "role".to_string(), - "description".to_string(), + "frame_id".to_string(), + "video_id".to_string(), + "caption".to_string(), "_distance".to_string(), ])) .limit(2) @@ -224,20 +216,20 @@ async fn main() { .unwrap(); println!("{result:?}"); // --8<-- [end:quickstart_vector_search_1] - let name_col = result.column("name").unwrap().str().unwrap(); - assert_eq!(name_col.get(0).unwrap(), "Merlin"); - assert_eq!(name_col.get(1).unwrap(), "Morgana"); + let frame_id_col = result.column("frame_id").unwrap().str().unwrap(); + 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.magic >= 4") + .only_if("stats.motion >= 4") .select(Select::Columns(vec![ - "name".to_string(), - "role".to_string(), - "description".to_string(), + "frame_id".to_string(), + "video_id".to_string(), + "caption".to_string(), "_distance".to_string(), ])) .limit(2) @@ -249,9 +241,9 @@ async fn main() { .unwrap(); println!("{curated:?}"); // --8<-- [end:quickstart_curate_with_metadata] - let curated_name_col = curated.column("name").unwrap().str().unwrap(); - assert_eq!(curated_name_col.get(0).unwrap(), "Merlin"); - assert_eq!(curated_name_col.get(1).unwrap(), "Morgana"); + 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 @@ -259,9 +251,9 @@ async fn main() { .nearest_to(&query_vector) .unwrap() .select(Select::Columns(vec![ - "name".to_string(), - "role".to_string(), - "description".to_string(), + "frame_id".to_string(), + "video_id".to_string(), + "caption".to_string(), "_distance".to_string(), ])) .limit(2) @@ -273,15 +265,15 @@ async fn main() { .unwrap(); println!("{result:?}"); // --8<-- [end:quickstart_output_array] - let name_col = result.column("name").unwrap().str().unwrap(); - assert_eq!(name_col.get(0).unwrap(), "Merlin"); + 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![( - "power_score".to_string(), - "cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)" + "quality_score".to_string(), + "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)" .to_string(), )]), None, @@ -294,9 +286,9 @@ async fn main() { let features = table .query() .select(Select::Columns(vec![ - "name".to_string(), - "role".to_string(), - "power_score".to_string(), + "frame_id".to_string(), + "video_id".to_string(), + "quality_score".to_string(), ])) .execute() .await @@ -306,7 +298,7 @@ async fn main() { .unwrap(); println!("{features:?}"); // --8<-- [end:quickstart_query_feature] - assert_eq!(features.column("power_score").unwrap().len(), 4); + 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(); @@ -314,7 +306,7 @@ async fn main() { std::fs::copy( std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../web/static/assets/images/quickstart/sir-lancelot.jpg"), - app.path().join("data/sir-lancelot.jpg"), + app.path().join("data/sample-frame.jpg"), ) .unwrap(); std::env::set_current_dir(app.path()).unwrap(); @@ -322,30 +314,30 @@ async fn main() { // --8<-- [start:quickstart_multimodal_bytes] use lancedb::arrow::arrow_array::BinaryArray; - let image_bytes = std::fs::read("data/sir-lancelot.jpg").unwrap(); + let image_bytes = std::fs::read("data/sample-frame.jpg").unwrap(); let image_schema = Arc::new(Schema::new(vec![ - Field::new("id", DataType::LargeUtf8, false), - Field::new("description", DataType::LargeUtf8, false), + Field::new("frame_id", DataType::LargeUtf8, false), + Field::new("caption", DataType::LargeUtf8, false), Field::new("image", DataType::Binary, false), Field::new( - "vector", + "embedding", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), false, ), ])); - let image_vectors = [[0.9_f32, 0.1, 0.5, 0.4]]; + let image_embeddings = [[0.9_f32, 0.1, 0.5, 0.4]]; let image_batch = RecordBatch::try_new( image_schema.clone(), vec![ - Arc::new(LargeStringArray::from_iter_values(["lancelot"])), + Arc::new(LargeStringArray::from_iter_values(["thumb-1"])), Arc::new(LargeStringArray::from_iter_values([ - "Portrait of Sir Lancelot", + "Sample frame thumbnail", ])), Arc::new(BinaryArray::from_iter_values([image_bytes.as_slice()])), Arc::new( FixedSizeListArray::from_iter_primitive::( - image_vectors + image_embeddings .iter() .map(|vector| Some(vector.iter().copied().map(Some).collect::>())), 4, @@ -359,7 +351,7 @@ async fn main() { image_schema, )); let multimodal_table = db - .create_table("character_images", image_reader) + .create_table("frame_images", image_reader) .mode(CreateTableMode::Overwrite) .execute() .await diff --git a/docs/web-tests/ts/connection.test.ts b/docs/web-tests/ts/connection.test.ts index 891501d4c..651be7d36 100644 --- a/docs/web-tests/ts/connection.test.ts +++ b/docs/web-tests/ts/connection.test.ts @@ -4,6 +4,12 @@ import { afterEach, describe, expect, jest, test } from "@jest/globals"; import * as lancedb from "@lancedb/lancedb"; import { withTempDirectory } from "./util.ts"; +async function collectNames(items: AsyncIterable): Promise { + const names: string[] = []; + for await (const name of items) names.push(name); + return names; +} + test("connect to a local database", async () => { await withTempDirectory(async (tempDir) => { const cwd = process.cwd(); @@ -13,12 +19,12 @@ test("connect to a local database", async () => { const db = await lancedb.connect("ex_lancedb"); // --8<-- [end:connect] await db.createTable("probe", [{ id: 1 }]); - expect((await db.listTables()).tables).toEqual(["probe"]); + expect(await collectNames(db.listTables())).toEqual(["probe"]); } finally { process.chdir(cwd); } const reopened = await lancedb.connect(`${tempDir}/ex_lancedb`); - expect((await reopened.listTables()).tables).toEqual(["probe"]); + expect(await collectNames(reopened.listTables())).toEqual(["probe"]); }); }); @@ -109,8 +115,8 @@ async function namespaceTableOpsExample() { ); // Verify - console.log((await db.listNamespaces()).namespaces); // ["prod"] - console.log((await db.listNamespaces(["prod"])).namespaces); // ["recommendations", "search"] + console.log(await collectNames(db.listNamespaces())); // ["prod"] + console.log(await collectNames(db.listNamespaces(["prod"]))); // ["recommendations", "search"] console.log(await db.tableNames(["prod", "search"])); // ["user"] console.log(await db.tableNames(["prod", "recommendations"])); // ["user"] // --8<-- [end:namespace_table_ops] @@ -124,7 +130,7 @@ async function namespaceAdminOpsExample() { await db.createNamespace(["prod"]); await db.createNamespace(["prod", "search"]); - const childNamespaces = (await db.listNamespaces(["prod"])).namespaces; + const childNamespaces = await collectNames(db.listNamespaces(["prod"])); console.log(`Child namespaces under ${JSON.stringify(namespace)}:`, childNamespaces); // Child namespaces under ["prod","search"]: [ 'search' ] diff --git a/docs/web-tests/ts/multimodal.test.ts b/docs/web-tests/ts/multimodal.test.ts index ac9a8201e..32672a6a3 100644 --- a/docs/web-tests/ts/multimodal.test.ts +++ b/docs/web-tests/ts/multimodal.test.ts @@ -75,8 +75,8 @@ test("multimodal snippets (async)", async () => { // --8<-- [end:process_results] expect(results).toHaveLength(1); - // --8<-- [start:blob_api_schema] - const blobSchema = new arrow.Schema([ + // --8<-- [start:legacy_blob_api_schema] + const legacyBlobSchema = new arrow.Schema([ new arrow.Field("id", new arrow.Int64()), new arrow.Field( "video", @@ -85,20 +85,24 @@ test("multimodal snippets (async)", async () => { new Map([["lance-encoding:blob", "true"]]), ), ]); - // --8<-- [end:blob_api_schema] + // --8<-- [end:legacy_blob_api_schema] - // --8<-- [start:blob_api_ingest] - const blobData = lancedb.makeArrowTable( + // --8<-- [start:legacy_blob_api_ingest] + const legacyBlobData = lancedb.makeArrowTable( [ { id: 1, video: Buffer.from("fake_video_bytes_1") }, { id: 2, video: Buffer.from("fake_video_bytes_2") }, ], - { schema: blobSchema }, + { schema: legacyBlobSchema }, ); - const blobTable = await db.createTable("videos", blobData, { - mode: "overwrite", - }); - // --8<-- [end:blob_api_ingest] - expect(await blobTable.countRows()).toBe(2); + const legacyBlobTable = await db.createTable( + "legacy_videos", + legacyBlobData, + { + mode: "overwrite", + }, + ); + // --8<-- [end:legacy_blob_api_ingest] + expect(await legacyBlobTable.countRows()).toBe(2); }); }); diff --git a/docs/web-tests/ts/quickstart.test.ts b/docs/web-tests/ts/quickstart.test.ts index e32a14f86..6796e0613 100644 --- a/docs/web-tests/ts/quickstart.test.ts +++ b/docs/web-tests/ts/quickstart.test.ts @@ -20,12 +20,7 @@ const connections = async function tableNames(db: lancedb.Connection) { const names: string[] = []; - let pageToken: string | undefined; - do { - const page = await db.listTables({ pageToken }); - names.push(...page.tables); - pageToken = page.pageToken; - } while (pageToken); + for await (const name of db.listTables()) names.push(name); return names; } @@ -95,50 +90,46 @@ async function withDatabase( }); } -async function createCharacters(db: lancedb.Connection) { +async function createFrames(db: lancedb.Connection) { // --8<-- [start:quickstart_data] const data = [ { - id: "1", - name: "King Arthur", - role: "King", - description: "Leader of Camelot and wielder of Excalibur.", - stats: { strength: 4, magic: 1, leadership: 5, wisdom: 4 }, - vector: [0.7, 0.1, 0.9, 0.7], + frame_id: "1", + video_id: "clip-1", + caption: "a robot arm reaching toward a cup", + stats: { motion: 3, sharpness: 4, exposure: 4, framing: 3 }, + embedding: [0.7, 0.1, 0.9, 0.7], }, { - id: "2", - name: "Merlin", - role: "Wizard", - description: "Advisor and prophet with deep magical knowledge.", - stats: { strength: 2, magic: 5, leadership: 4, wisdom: 5 }, - vector: [0.2, 0.9, 0.4, 0.9], + frame_id: "2", + video_id: "clip-1", + caption: "a two-finger gripper closing on a cup", + stats: { motion: 5, sharpness: 4, exposure: 5, framing: 2 }, + embedding: [0.2, 0.9, 0.4, 0.9], }, { - id: "3", - name: "Sir Lancelot", - role: "Knight", - description: "Legendary knight known for courage and combat skill.", - stats: { strength: 5, magic: 1, leadership: 3, wisdom: 3 }, - vector: [0.9, 0.1, 0.5, 0.4], + frame_id: "3", + video_id: "clip-2", + caption: "a robot arm holding a cup steady", + stats: { motion: 2, sharpness: 3, exposure: 3, framing: 4 }, + embedding: [0.9, 0.1, 0.5, 0.4], }, ]; // --8<-- [end:quickstart_data] // --8<-- [start:quickstart_create_table] - const table = await db.createTable("characters", data, { mode: "overwrite" }); + const table = await db.createTable("frames", data, { mode: "overwrite" }); // --8<-- [end:quickstart_create_table] expect(await table.countRows()).toBe(3); // --8<-- [start:quickstart_add_data] await table.add([ { - id: "4", - name: "Morgana", - role: "Sorceress", - description: "Powerful sorceress of Avalon.", - stats: { strength: 2, magic: 5, leadership: 4, wisdom: 4 }, - vector: [0.3, 0.9, 0.6, 0.8], + frame_id: "4", + video_id: "clip-2", + caption: "a gripper lowering a cup onto the table", + stats: { motion: 5, sharpness: 4, exposure: 4, framing: 2 }, + embedding: [0.3, 0.9, 0.6, 0.8], }, ]); // --8<-- [end:quickstart_add_data] @@ -149,44 +140,44 @@ async function createCharacters(db: lancedb.Connection) { describe.each(connections)("quickstart (%s)", (connection) => { test("create, add and search", async () => { await withDatabase(connection, async (db) => { - const table = await createCharacters(db); + const table = await createFrames(db); // --8<-- [start:quickstart_vector_search_1] - // Search for examples similar to a "wise magical advisor" + // Search for frames similar to "a gripper closing on an object" const queryVector = [0.2, 0.8, 0.4, 0.9]; const result = await table .search(queryVector) - .select(["name", "role", "description", "_distance"]) + .select(["frame_id", "video_id", "caption", "_distance"]) .limit(2) .toArray(); console.table(result); // --8<-- [end:quickstart_vector_search_1] - expect(result.map((row) => row.name)).toEqual(["Merlin", "Morgana"]); + expect(result.map((row) => row.frame_id)).toEqual(["2", "4"]); // --8<-- [start:quickstart_curate_with_metadata] const curated = await table .search(queryVector) - .where("stats.magic >= 4") - .select(["name", "role", "description", "_distance"]) + .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.name)).toEqual(["Merlin", "Morgana"]); + expect(curated.map((row) => row.frame_id)).toEqual(["2", "4"]); }); }); test("a derived feature", async () => { await withDatabase(connection, async (db) => { - const table = await createCharacters(db); + const table = await createFrames(db); // --8<-- [start:quickstart_add_feature] await table.addColumns([ { - name: "power_score", + name: "quality_score", valueSql: - "cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)", + "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)", }, ]); // --8<-- [end:quickstart_add_feature] @@ -194,17 +185,17 @@ describe.each(connections)("quickstart (%s)", (connection) => { // --8<-- [start:quickstart_query_feature] const features = await table .query() - .select(["name", "role", "power_score"]) + .select(["frame_id", "video_id", "quality_score"]) .toArray(); console.table(features); // --8<-- [end:quickstart_query_feature] expect( - features.map((row) => [row.name, row.power_score]).sort(), + features.map((row) => [row.frame_id, row.quality_score]).sort(), ).toEqual([ - ["King Arthur", 3.5], - ["Merlin", 4], - ["Morgana", 3.75], - ["Sir Lancelot", 3], + ["1", 3.5], + ["2", 4], + ["3", 3], + ["4", 3.75], ]); }); }); @@ -213,7 +204,7 @@ describe.each(connections)("quickstart (%s)", (connection) => { await withDatabase(connection, async (db) => { await withTempDirectory(async (app) => { fs.mkdirSync(path.join(app, "data")); - fs.copyFileSync(IMAGE, path.join(app, "data/sir-lancelot.jpg")); + fs.copyFileSync(IMAGE, path.join(app, "data/sample-frame.jpg")); const cwd = process.cwd(); process.chdir(app); try { @@ -221,13 +212,13 @@ describe.each(connections)("quickstart (%s)", (connection) => { const arrow = await import("apache-arrow"); const { readFile } = await import("node:fs/promises"); - const imageBytes = await readFile("data/sir-lancelot.jpg"); + const imageBytes = await readFile("data/sample-frame.jpg"); const imageSchema = new arrow.Schema([ - new arrow.Field("id", new arrow.Utf8()), - new arrow.Field("description", new arrow.Utf8()), + new arrow.Field("frame_id", new arrow.Utf8()), + new arrow.Field("caption", new arrow.Utf8()), new arrow.Field("image", new arrow.Binary()), new arrow.Field( - "vector", + "embedding", new arrow.FixedSizeList( 4, new arrow.Field("item", new arrow.Float32(), true), @@ -237,16 +228,16 @@ describe.each(connections)("quickstart (%s)", (connection) => { const imageData = lancedb.makeArrowTable( [ { - id: "lancelot", - description: "Portrait of Sir Lancelot", + frame_id: "thumb-1", + caption: "Sample frame thumbnail", image: imageBytes, - vector: [0.9, 0.1, 0.5, 0.4], + embedding: [0.9, 0.1, 0.5, 0.4], }, ], { schema: imageSchema }, ); const multimodalTable = await db.createTable( - "character_images", + "frame_images", imageData, { mode: "overwrite" }, ); diff --git a/docs/web-tests/ts/vscode_extension.ts b/docs/web-tests/ts/vscode_extension.ts new file mode 100644 index 000000000..abd5c98ad --- /dev/null +++ b/docs/web-tests/ts/vscode_extension.ts @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +// The `src/extension.ts` of the sample extension in the VS Code integration guide. +// It needs the VS Code extension host, so jest doesn't run it: the LanceDB code it +// calls is tested in vscode_search.test.ts, and the extension itself was tested +// with @vscode/test-cli. + +// --8<-- [start:vscode_extension] +import * as vscode from "vscode"; +import { + type Chunk, + chunkMarkdown, + indexChunks, + openDatabase, + searchChunks, +} from "./search"; + +export async function activate(context: vscode.ExtensionContext) { + // One index per workspace. `storageUri` is undefined when no folder is open. + const storage = context.storageUri ?? context.globalStorageUri; + + // Transformers.js downloads the embedding model on first use. Keep it in + // global storage so every workspace shares one copy and it survives + // extension updates. Use `import()`: LanceDB loads the ES module build, and + // `require()` would return a separate copy whose settings LanceDB never sees. + const { env } = await import("@huggingface/transformers"); + env.cacheDir = vscode.Uri.joinPath(context.globalStorageUri, "models").fsPath; + + context.subscriptions.push( + vscode.commands.registerCommand("lancedbSearch.index", async () => { + const files = await vscode.workspace.findFiles( + "**/*.md", + "**/node_modules/**", + ); + const chunks: Chunk[] = []; + for (const file of files) { + const bytes = await vscode.workspace.fs.readFile(file); + // Store the file's URI, not a path relative to its folder: in a + // multi-root workspace `findFiles` searches every folder, and only the + // URI says which one a result came from. + chunks.push( + ...chunkMarkdown(file.toString(), new TextDecoder().decode(bytes)), + ); + } + if (chunks.length === 0) { + vscode.window.showWarningMessage("No Markdown files to index."); + return 0; + } + + await vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Indexing ${files.length} Markdown files`, + }, + async () => { + await vscode.workspace.fs.createDirectory(storage); + await indexChunks(await openDatabase(storage.fsPath), chunks); + }, + ); + vscode.window.showInformationMessage( + `Indexed ${chunks.length} paragraphs from ${files.length} files.`, + ); + return chunks.length; + }), + + // Called with a query (for example from a test or another extension), the + // command returns the matching rows instead of showing a picker. + vscode.commands.registerCommand( + "lancedbSearch.search", + async (query?: string) => { + const text = + query ?? + (await vscode.window.showInputBox({ + prompt: "Search Markdown by meaning", + })); + if (!text) { + return []; + } + const results = await searchChunks( + await openDatabase(storage.fsPath), + text, + ); + if (query !== undefined) { + return results; + } + + const picked = await vscode.window.showQuickPick( + results.map((row) => { + const uri = vscode.Uri.parse(row.path); + return { + label: `${vscode.workspace.asRelativePath(uri)}:${row.line + 1}`, + description: `distance ${row._distance.toFixed(3)}`, + detail: row.text, + uri, + line: row.line, + }; + }), + { placeHolder: text, matchOnDetail: true }, + ); + if (picked) { + const editor = await vscode.window.showTextDocument(picked.uri); + const start = new vscode.Position(picked.line, 0); + editor.selection = new vscode.Selection(start, start); + editor.revealRange( + new vscode.Range(start, start), + vscode.TextEditorRevealType.InCenter, + ); + } + return results; + }, + ), + ); +} + +export function deactivate() {} +// --8<-- [end:vscode_extension] diff --git a/docs/web-tests/ts/vscode_search.test.ts b/docs/web-tests/ts/vscode_search.test.ts new file mode 100644 index 000000000..21dd4d816 --- /dev/null +++ b/docs/web-tests/ts/vscode_search.test.ts @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +import { expect, test } from "@jest/globals"; +import { withTempDirectory } from "./util.ts"; +import { + chunkMarkdown, + indexChunks, + openDatabase, + searchChunks, +} from "./vscode_search.ts"; + +// The same files make up the sample workspace used in the docs page. +const workspace: Record = { + "README.md": + "# Acme CLI\n\nAcme CLI syncs your local notes to the Acme cloud.\n\nInstall it with `npm install -g acme-cli`, then run `acme login`.\n", + "docs/auth.md": + "# Authentication\n\nAcme uses personal access tokens. Create one under Settings > Tokens.\n\nIf a token leaks, revoke it on the Tokens page and generate a replacement.\nRevoked tokens stop working immediately.\n", + "docs/sync.md": + "# Syncing\n\nRun `acme sync` to upload changed notes. Only files modified since the last sync are sent.\n\nConflicts are resolved by keeping both copies and adding `.conflict` to the older one.\n", + "docs/config.md": + "# Configuration\n\nSettings live in `~/.acme/config.toml`.\n\nSet `sync.interval` to control how often background sync runs, in minutes.\n", + "docs/troubleshooting.md": + "# Troubleshooting\n\nIf `acme sync` hangs, check that your proxy allows connections to api.acme.dev on port 443.\n\nRun `acme doctor` to print diagnostics you can attach to a bug report.\n", + "CONTRIBUTING.md": + "# Contributing\n\nRun `npm test` before opening a pull request. New commands need a page in docs/.\n", +}; + +test("chunkMarkdown splits paragraphs and records their start line", () => { + expect(chunkMarkdown("docs/auth.md", workspace["docs/auth.md"])).toEqual([ + { path: "docs/auth.md", line: 0, text: "# Authentication" }, + { + path: "docs/auth.md", + line: 2, + text: "Acme uses personal access tokens. Create one under Settings > Tokens.", + }, + { + path: "docs/auth.md", + line: 4, + text: "If a token leaks, revoke it on the Tokens page and generate a replacement.\nRevoked tokens stop working immediately.", + }, + ]); +}); + +test("index workspace Markdown and search it by meaning", async () => { + await withTempDirectory(async (storageDir) => { + const chunks = Object.entries(workspace).flatMap(([filePath, content]) => + chunkMarkdown(filePath, content), + ); + await indexChunks(await openDatabase(storageDir), chunks); + + // Each command in the extension opens its own connection, so search + // through a fresh one to check the table is usable after a reload. + const db = await openDatabase(storageDir); + const leaked = await searchChunks( + db, + "my credentials were exposed, what should I do?", + ); + expect(leaked[0].path).toBe("docs/auth.md"); + expect(leaked[0].line).toBe(4); + + const firewall = await searchChunks( + db, + "uploads are stuck behind the company firewall", + ); + expect(firewall[0].path).toBe("docs/troubleshooting.md"); + }); +}, 100_000); diff --git a/docs/web-tests/ts/vscode_search.ts b/docs/web-tests/ts/vscode_search.ts new file mode 100644 index 000000000..d090084a1 --- /dev/null +++ b/docs/web-tests/ts/vscode_search.ts @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +// --8<-- [start:vscode_imports] +import * as path from "node:path"; +import * as lancedb from "@lancedb/lancedb"; +import "@lancedb/lancedb/embedding/transformers"; +import { Int32, Utf8 } from "apache-arrow"; +// --8<-- [end:vscode_imports] + +// --8<-- [start:vscode_chunk] +export type Chunk = { path: string; line: number; text: string }; + +// Split a Markdown file into paragraphs, keeping the line each one starts on +// so a search result can jump straight to it. +export function chunkMarkdown(filePath: string, content: string): Chunk[] { + const lines = content.split(/\r?\n/); + const chunks: Chunk[] = []; + let start = 0; + for (let i = 0; i <= lines.length; i++) { + if (i === lines.length || lines[i].trim() === "") { + const text = lines.slice(start, i).join("\n").trim(); + if (text) { + chunks.push({ path: filePath, line: start, text }); + } + start = i + 1; + } + } + return chunks; +} +// --8<-- [end:vscode_chunk] + +// --8<-- [start:vscode_connect] +// Pass an absolute directory, such as `context.storageUri.fsPath`. A relative +// path resolves against the extension host's working directory, which is not +// your workspace and may be read-only (on macOS it is usually `/`). +export async function openDatabase(storageDir: string) { + return lancedb.connect(path.join(storageDir, "lancedb")); +} +// --8<-- [end:vscode_connect] + +// --8<-- [start:vscode_index] +export async function indexChunks(db: lancedb.Connection, chunks: Chunk[]) { + // Runs all-MiniLM-L6-v2 locally through Transformers.js: no API key needed. + const embedder = (await lancedb.embedding + .getRegistry() + .get("huggingface") + ?.create()) as lancedb.embedding.EmbeddingFunction; + + const schema = lancedb.embedding.LanceSchema({ + path: new Utf8(), + line: new Int32(), + text: embedder.sourceField(new Utf8()), + vector: embedder.vectorField(), + }); + + // LanceDB fills in the `vector` column from `text` as the rows are written. + return db.createTable("chunks", chunks, { schema, mode: "overwrite" }); +} +// --8<-- [end:vscode_index] + +// --8<-- [start:vscode_search] +export async function searchChunks( + db: lancedb.Connection, + query: string, + limit = 5, +) { + // The table stores its embedding function in its metadata, so a text query + // is embedded with the same model that embedded the rows. + const table = await db.openTable("chunks"); + return table + .search(query) + .select(["path", "line", "text", "_distance"]) + .limit(limit) + .toArray(); +} +// --8<-- [end:vscode_search] diff --git a/docs/web/.mintignore b/docs/web/.mintignore index b8da6c17a..79cce2724 100644 --- a/docs/web/.mintignore +++ b/docs/web/.mintignore @@ -1,6 +1,22 @@ # Functions are documented before their release. At release, remove these -# entries, add the pages back to the navigation in docs.json, restore the -# /feature-engineering/functions redirect to /management/function, and publish -# the drafts marked "Draft for the Functions release". +# 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 diff --git a/docs/web/agent-branch-experiments.mdx b/docs/web/agent-branch-experiments.mdx index 3f4f1cbfa..30a3893e7 100644 --- a/docs/web/agent-branch-experiments.mdx +++ b/docs/web/agent-branch-experiments.mdx @@ -64,13 +64,13 @@ The branch experiments leave you with the results side by side, and they deliberately never touch `main`. Once you've picked a winner, apply it to `main` yourself by rerunning that experiment's validated transformation directly against the `main` table. Rerunning the reviewed operation is the -reliable path on both OSS and Enterprise: it replays exactly the transformation +reliable path on both LanceDB Embedded and LanceDB Enterprise: it replays exactly the transformation you validated on the branch, and it works the same regardless of how the branch evolved. Suppose `nomic-embed-text` wins. Rerun the same Nomic embedding transformation you validated on `embed-nomic` against `main` in batches, then call -`table.optimize()` on OSS. Verify a bounded vector search on `main`, and keep +`table.optimize()` on LanceDB Embedded. Verify a bounded vector search on `main`, and keep the losing branch around until you're confident in the result. See [Branches](/tables/branching) for more on how branches, versions, and tags @@ -96,5 +96,5 @@ branch that's isolated from `main` until you decide you want the new derived column in `main`. Once you've chosen a winner, rerun that validated transformation to ingest it into `main` -yourself, on either LanceDB OSS or Enterprise. See our documentation on [branches](/tables/branching) +yourself, on either LanceDB Embedded or LanceDB Enterprise. See our documentation on [branches](/tables/branching) for more information. diff --git a/docs/web/api-reference/rest/index.mdx b/docs/web/api-reference/rest/index.mdx index d9bb26867..d6364d92c 100644 --- a/docs/web/api-reference/rest/index.mdx +++ b/docs/web/api-reference/rest/index.mdx @@ -9,7 +9,7 @@ description: "API reference for LanceDB" is an OpenAPI protocol that enables reading, writing and managing Lance tables by connecting those metadata services or building a custom metadata server in a standardized way. -LanceDB OSS allows you to interface with Lance tables via the REST Namespace. +LanceDB Embedded allows you to interface with Lance tables via the REST Namespace. LanceDB Enterprise provides an extended REST API with additional endpoints for managing tables and data. If you have specific needs or questions about the Enterprise REST API Namespace, diff --git a/docs/web/architecture.mdx b/docs/web/architecture.mdx deleted file mode 100644 index 997bb95b0..000000000 --- a/docs/web/architecture.mdx +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: "Architecture" -sidebarTitle: "Architecture" -description: "How LanceDB Enterprise separates query serving, background work, and storage, and how it compares with embedded LanceDB OSS." -icon: cubes -keywords: ["architecture", "embedded", "distributed", "object storage", "compute", "deployment"] ---- - -LanceDB OSS is an embedded library for working with Lance tables. LanceDB -Enterprise is a multimodal lakehouse for data curation, feature engineering, -search, and training data access. Its architecture separates query serving, -read execution, caching, and background work. Both use the open -[Lance](/basics/lance) format. - -Teams can curate datasets, derive features, search multimodal records, and -read the resulting tables into training frameworks. Enterprise separates the -resources that serve shared data from those that build indexes and run -background work, so teams can size them for these different workloads. - -![LanceDB OSS runs the application and embedded library in one process, using local disk or object storage. Enterprise applications connect to query serving, with separate read execution and caching, indexing and background workers, and durable object storage. Both use the Lance format, but they do not share a storage location automatically.](/static/assets/images/overview/lancedb-architecture.svg) - -The diagram shows the main compute and storage boundaries, not every request -path. The control plane governs the Enterprise service. - -## A shared format, different storage choices {#storage} - -Lance stores table data, versions, and indexes. OSS can read and write tables on -local disk or in object storage. Enterprise keeps durable table data and index -artifacts in object storage, independently of the machines serving requests. -Its caches accelerate reads; they are not the durable source of truth. - -Sharing a format does not mean that an Enterprise deployment automatically -opens an existing OSS database. Plan how to move or connect your data and -configure access for your deployment. - -## OSS: an embedded library inside your application {#embedded} - -With an embedded connection, the LanceDB library plans and executes queries, -builds indexes, and updates tables inside your process. There is no separate -database server to deploy. - -This fits local retrieval applications, notebooks, development, and -single-node data pipelines. Your application controls the compute resources and -when to run [table maintenance](/maintenance/compaction). You also manage access -to the local files or object storage that hold your tables. - -## Enterprise: a multimodal lakehouse for shared workloads {#distributed} - -Applications connect to remote tables through a LanceDB SDK. The service handles -requests across a fleet, with components sized for different kinds of work: - -- **Query serving** receives requests, resolves tables, and plans operations. - Add serving capacity as more applications and users depend on your data. -- **Read execution and caching** use separately provisioned resources. Executors - cache table data to reduce repeated reads from object storage. -- **Indexing and background workers** build indexes and perform maintenance - outside the query request path. Size this work separately from query serving - as your data grows. - -The control plane manages configuration, identity, policy, and cluster -lifecycle. It governs the service rather than executing table queries. -[Authorization](/governance/authorization) lets teams control access to catalog -objects when enabled and configured by the administrator. Deployment settings govern background -[compaction](/maintenance/compaction) and -[cleanup](/maintenance/cleanup), including retention. - -These boundaries support different parts of an AI data workflow. -[SQL curation](/curation) requires a deployment with SQL enabled. -[Feature engineering](/feature-engineering) can produce derived columns and -tables; computed columns and materialized views require a deployment that -enables them. [Geneva](/geneva) runs distributed Python feature backfills while -its capabilities continue to transition to LanceDB APIs. -[Training data loaders](/training/data-loading) read tables into model training -frameworks in both offerings. LanceDB provides data access for training; the -training framework runs the model. - -Size and monitor each tier for your workload. Read the -[Enterprise architecture](/enterprise/architecture) for the component details -and request flows. - -## Application changes for Enterprise {#differences} - -Core operations remain familiar: create a table, add data, and run a search. -With OSS, the application executes those operations. With Enterprise, the SDK -sends requests to the service, and the service manages execution and configured -background maintenance. - -To use Enterprise, configure the cluster endpoint, database URI and credentials, -and make your data available in the Enterprise database. Review SDK methods -that behave differently on remote tables, including result retrieval and -background jobs. [Moving to LanceDB Enterprise](/basics/sdk#moving-to-enterprise) -describes these application changes. If you plan to use materialized views, check the -[stable row ID requirements](/basics/limits#schema) before creating source tables. - -## Choose for the workload you need to run {#choosing} - -Choose OSS when you want an embedded library and can manage its resources and -maintenance in your application. - -Choose Enterprise when multiple applications or teams need a shared multimodal -lakehouse for curation, feature engineering, search, and training data access. -It also fits workloads whose query and indexing demand grow at different rates, -or that need configured service-level access controls and background operations. -You can begin with Enterprise. - -[Talk to us about your workload](https://www.lancedb.com/contact) to plan capacity, -deployment options, and the path from your existing data to Enterprise. - -## Where to go next {#next} - - - - Query serving, execution, and background work in detail. - - - Connect an application to your deployment. - - - What a write promises, and what a reader sees. - - - The open format underneath both offerings. - - diff --git a/docs/web/basics/agentic-skills.mdx b/docs/web/basics/agentic-skills.mdx index 771bb75ff..b87574dff 100644 --- a/docs/web/basics/agentic-skills.mdx +++ b/docs/web/basics/agentic-skills.mdx @@ -158,13 +158,13 @@ LANCEDB_REGION=us-east-1 LANCEDB_HOST_OVERRIDE=https://your-enterprise-endpoint.com ``` -If you're using LanceDB OSS, no connection settings are required, as it runs as an +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 OSS +# If using LanceDB Embedded Use the lancedb plugin to ingest the dataset in `data/` into a LanceDB -OSS table. +Embedded table. # If using enterprise Use the lancedb plugin to ingest the dataset in `data/` into a LanceDB @@ -208,7 +208,7 @@ to `batch_size` rows at a time, providing an iterable of batches for the ingesti shown next. #### Table maintenance {#table-maintenance} -For LanceDB OSS, the plugin instructs the agent to call +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. @@ -225,7 +225,7 @@ 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 OSS pipeline {#3-run-the-oss-pipeline} +### 3\. Run the Embedded pipeline {#3-run-the-oss-pipeline} ```bash uv run python ingest_multimodal.py @@ -258,9 +258,9 @@ The plugin shown in this tutorial should generalize reasonably well to other use 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 OSS or Enterprise based on how the work will run: +You can choose LanceDB Embedded or LanceDB Enterprise based on how the work will run: -Start with [LanceDB OSS](/quickstart) during the early stages of a project +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 @@ -271,9 +271,9 @@ 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 a remote `db://` table, leaves maintenance to the +the agent connects to an Enterprise `db://` table, leaves maintenance to the deployment instead of calling `optimize()`, and submits long-running work as -jobs. See [Moving to LanceDB Enterprise](/basics/sdk#moving-to-enterprise). +[jobs](/basics/jobs). ## What agents are good at here {#workflows} diff --git a/docs/web/basics/catalog.mdx b/docs/web/basics/catalog.mdx index c6950b9de..976aac300 100644 --- a/docs/web/basics/catalog.mdx +++ b/docs/web/basics/catalog.mdx @@ -1,16 +1,128 @@ --- -title: "Lance Catalog" -sidebarTitle: "Lance Catalog" -description: "Organize, find and control access to your data in LanceDB." +title: "LanceDB Catalog" +sidebarTitle: "LanceDB Catalog" +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"] +keywords: ["catalog", "namespace", "hierarchy", "governance", "database", "table", "view", "connect", "uri", "embedded", "object storage", "s3", "enterprise", "db://"] --- +import { + PyConnect, + PyConnectAsync, + PyConnectEnterprisePlaceholders, + PyConnectObjectStorage, + PyConnectObjectStorageAsync, + RsConnect, + TsConnect, + TsConnectEnterprisePlaceholders, + TsConnectObjectStorage, +} from '/snippets/connection.mdx'; + ## Catalog overview {#catalog} 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. +objects into databases and namespaces -- similar to a catalog in Postgres, +Snowflake, or other database systems. + +## 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: + +- **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. + +The table below shows which URI reaches which kind of database directly. + +| 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 | + +### A local directory {#local} + +Embedded in your application, LanceDB reads and writes the tables in a +directory on disk. + + + + {PyConnect} + + + + {PyConnectAsync} + + + + { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } + {TsConnect} + + + + { "use lancedb::connect;\n" } + { "\n" } + {RsConnect} + + + +### 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. + + + + {PyConnectObjectStorage} + + + + {PyConnectObjectStorageAsync} + + + + { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } + {TsConnectObjectStorage} + + + +In Rust, pass the same URI to `connect`. + +### 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, +region and endpoint from your administrator, then replace the placeholders +below. Use your cluster's region in place of `us-east-1`. In application code, +load credentials from environment variables or a secrets manager. + + + + {PyConnectEnterprisePlaceholders} + + + + { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } + {TsConnectEnterprisePlaceholders} + + + +In Rust, enable the crate's `remote` feature; the connection builder then takes +the same settings through `api_key`, `region` and `host_override`. To use OAuth +instead of an API key, see +[Authentication](/enterprise/authentication); for every connection option, see +[Database](/management/database#deployment). ## Databases, namespaces and tables {#objects} @@ -37,7 +149,7 @@ flowchart TD | [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. | +| [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: diff --git a/docs/web/basics/connect.mdx b/docs/web/basics/connect.mdx deleted file mode 100644 index ac7061bbc..000000000 --- a/docs/web/basics/connect.mdx +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: "Connect to LanceDB" -sidebarTitle: "Connect" -description: "Use the embedded LanceDB OSS library with tables in a local directory or object storage, or connect to LanceDB Enterprise." -icon: plug -keywords: ["connect", "uri", "embedded", "object storage", "s3", "enterprise", "db://"] ---- - -import { - PyConnect, - PyConnectAsync, - PyConnectEnterprisePlaceholders, - PyConnectEnterpriseQuickstart, - PyConnectObjectStorage, - PyConnectObjectStorageAsync, - RsConnect, - TsConnect, - TsConnectEnterprisePlaceholders, - TsConnectEnterpriseQuickstart, - TsConnectObjectStorage, -} from '/snippets/connection.mdx'; - -The URI you pass to `connect` decides where the work runs. The same Python, -TypeScript and Rust SDKs open all three kinds; -[OSS and Enterprise](/basics/offerings) describes how the two offerings differ. - -| URI | Where queries run | -| --- | --- | -| A local path, such as `./data` | OSS: in your process | -| `s3://`, `gs://` or `az://` | OSS: in your process, reading object storage | -| `db://` | LanceDB Enterprise: queries run on your cluster | - -## A local directory {#local} - -Embedded in your application, LanceDB reads and writes the tables in a -directory on disk. - - - - {PyConnect} - - - - {PyConnectAsync} - - - - { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } - {TsConnect} - - - - { "use lancedb::connect;\n" } - { "\n" } - {RsConnect} - - - -## 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. - - - - {PyConnectObjectStorage} - - - - {PyConnectObjectStorageAsync} - - - - { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } - {TsConnectObjectStorage} - - - -In Rust, pass the same URI to `connect`. - -## LanceDB Enterprise {#enterprise} - -A `db://` URI connects to LanceDB Enterprise, where your cluster runs queries -and background work. Get the database URI, API key, region and endpoint from -your administrator, then replace the placeholders below. Use your cluster's region -in place of `us-east-1`. In application code, load credentials from environment -variables or a secrets manager. - - - - {PyConnectEnterprisePlaceholders} - - - - { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } - {TsConnectEnterprisePlaceholders} - - - -In Rust, enable the crate's `remote` feature; the connection builder then takes -the same settings through `api_key`, `region` and `host_override`. To use OAuth -instead of an API key, see -[Authentication](/enterprise/authentication); for every connection option, see -[Database](/management/database#deployment). - - - - -Set these values in the shell that starts your application. Replace the URI, API -key, region and endpoint with your Enterprise connection settings. In production, a secrets -manager can supply these environment variables for you. - -```shell -export LANCEDB_URI="db://your-database" -export LANCEDB_API_KEY="your-api-key" -export LANCEDB_REGION="us-east-1" -export LANCEDB_HOST_OVERRIDE="https://your-endpoint" -``` - - - - {PyConnectEnterpriseQuickstart} - - - { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } - {TsConnectEnterpriseQuickstart} - - - - diff --git a/docs/web/basics/guarantees.mdx b/docs/web/basics/guarantees.mdx index 840ea2d50..bdfe86286 100644 --- a/docs/web/basics/guarantees.mdx +++ b/docs/web/basics/guarantees.mdx @@ -25,7 +25,7 @@ rewrite data; adding a derived column can write the new column independently. A read of a table uses a consistent snapshot. A consistent snapshot can still be older than another writer's latest commit. [Consistency](/tables/consistency) -explains how OSS and Enterprise choose the version a reader sees. +explains how LanceDB Embedded and LanceDB Enterprise choose the version a reader sees. For an experiment that must keep using the same data, select a specific retained table version rather than relying on a connection's default freshness. @@ -46,7 +46,7 @@ describes commit behavior and compatibility between operations. ## Storage durability {#durability} A committed table version is stored in the table’s configured storage. LanceDB -OSS uses your local filesystem or object store; LanceDB Enterprise uses the +Embedded uses your local filesystem or object store; LanceDB Enterprise uses the cluster’s configured storage. Table version history does not replace backups. Configure storage redundancy @@ -87,5 +87,5 @@ cannot undo `drop_table`. - [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. -- [Column refresh](/feature-engineering/refresh-column): understand partial progress. -- [Architecture](/architecture): understand storage and background maintenance. +- [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 0577cd120..a15f10fee 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -5,11 +5,8 @@ description: "Track background work from submission to completion." icon: hourglass-half keywords: ["job", "background", "progress", "events", "cancel"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Job handles track operations in OSS and Enterprise. Enterprise also - supports listing server jobs, reopening them by ID and reading their events. --- ## Job handles {#convention} @@ -19,25 +16,50 @@ column refresh. Use it to check progress, wait for completion and inspect failures. Methods such as Python's `create_index_async` and TypeScript's -`createIndexAsync` return job handles. In OSS, the work runs in your application -process; in Enterprise, it runs on server workers. A returned handle can -represent an operation that has already finished, so check its status before +`createIndexAsync` return job handles. In LanceDB Embedded, the work runs in your application +process; in Enterprise, it runs on server workers or through the SQL query +backend. A returned handle can represent an operation that has already finished, +so check its status before waiting or requesting cancellation. See the operation's API reference for when the method returns. +```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} 1. **Submit the operation.** Keep the returned job handle. For an Enterprise - job, also keep its ID if another process needs to look it up later. + registry job, also keep its ID if another process needs to look it up later. 2. **Check progress.** Read the current status while the operation runs. 3. **Wait for completion.** Check that the job succeeded before using its - result. If it failed or was cancelled, inspect the failure details and any - results it committed before stopping. + result. If it failed or was cancelled, inspect the failure details and any + 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. +```python +from datetime import timedelta +from lancedb.exceptions import JobFailedError, JobCancelledError + +job = tbl.create_index_async("vector", replace=True) + +try: + result = job.wait(timeout=timedelta(minutes=10)) +except JobFailedError: + print(f"job failed: {job.failure}") +except JobCancelledError: + print("job was cancelled") +except TimeoutError: + print(f"still running: {job.status()}") +``` + @@ -53,23 +75,68 @@ The timeout does not cancel the server job. 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 +job = db.open_job(job_id) # raises JobNotFoundError if unknown +job.refresh() # pull the latest status from the server +print(job.status()) + +events = job.events(limit=100) +print(events.to_pylist()) + +job.cancel() +``` + +List jobs on a connection, paging through the results: + +```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. -## OSS and Enterprise execution {#in-process} +## Embedded and Distributed execution {#in-process} -| | OSS | Enterprise | +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. + +| | Embedded | Enterprise registry job | | --- | --- | --- | | Execution | In your application process | On server workers | | Job identity | No server ID | A server ID for looking up the job | | Event history | No server event history | Available through the jobs API | | Reattaching after a client restart | No server job to reopen | Reopen by ID while the record is retained | +### 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. + +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. + +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. + +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. + ## Learn more {#next} - [Build and repair indexes](/indexing/reindexing): submit index work. -- [Column refresh](/feature-engineering/refresh-column): populate derived values. +- [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/lakehouse.mdx b/docs/web/basics/lakehouse.mdx deleted file mode 100644 index 04e07afaf..000000000 --- a/docs/web/basics/lakehouse.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: "LanceDB Lakehouse" -sidebarTitle: "LanceDB Lakehouse" -description: "Bring multimodal data, search and feature engineering together for AI workloads." -icon: layer-group -keywords: ["lakehouse", "multimodal", "search", "compute", "training", "feature engineering"] ---- - -## Multimodal storage and processing {#multimodal} - -LanceDB brings storage, search and data processing together for AI workloads. -You can store multimodal data, derive features, search your records and prepare -training datasets using tables built on the open [Lance format](/basics/lance). - -The format provides the storage foundation. The [catalog](/basics/catalog) -organizes your tables. LanceDB provides the tools to work with that data. - -## Example: a video search workflow {#capabilities} - -Consider a team building a video search application: - - - - - -1. **Ingest the clips.** Store video clips with metadata such as timestamps, - source and labels. -2. **Add features.** Generate captions and embeddings with your models, and - store them alongside each clip. -3. **Use the dataset.** Search for relevant clips using embeddings and metadata - filters, or select a dataset to read into a training framework. - -```mermaid -flowchart TD - clips["Video clips and metadata"] --> table["Store in a Lance table"] - table --> features["Add captions and embeddings"] - features --> search["Search for relevant clips"] - features --> training["Select data for training"] -``` - -The clips, metadata and derived features stay associated in the same table, -so retrieval and training workflows can use the same dataset. Your training -framework runs the model; LanceDB provides access to the training data. - -## Shared compute and maintenance in Enterprise {#where} - -LanceDB OSS runs as an embedded library in your application. LanceDB Enterprise -provides shared infrastructure for applications and teams working with larger -multimodal workloads. - - - -- **Scale resources for different workloads.** Provision query serving and - background workers independently as search traffic and indexing demand grow. -- **Share data across teams.** Give applications access to shared tables, with - Enterprise permissions controlling who can read or change them. -- **Manage ongoing maintenance.** Configure background indexing, compaction - and cleanup as your datasets grow. - -See [Architecture](/architecture) for how Enterprise separates storage, query -serving and background work. - -## Learn more {#next} - -- [Data ingestion](/ingestion): load and update your data. -- [Search](/search): retrieve records with vector, full-text and hybrid search. -- [Feature engineering](/feature-engineering): derive columns and datasets. -- [Training data access](/training/data-loading): read datasets into training workflows. -- [Enterprise](/enterprise): explore deployment options for shared workloads. - -{/* -Draft for the Functions release. Add this item to the list above, after -Feature engineering: -- [Functions](/management/function): run Python to compute column values. -*/} diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index f2dd0ecfa..42d474de9 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -2,7 +2,7 @@ title: "Lance format" sidebarTitle: "Lance Format" description: "The open format for multimodal data behind LanceDB." -icon: "/static/assets/logo/lance-logo-gray.svg" +icon: "/static/assets/logo/lance-logo-gray.png" keywords: ["lance", "format", "multimodal", "versioning", "column evolution"] --- @@ -14,7 +14,7 @@ multimodal AI. It defines how data is stored and organized into versioned tables -LanceDB OSS and LanceDB Enterprise both use Lance as their storage foundation. +LanceDB Embedded and LanceDB Enterprise both use Lance as their storage foundation. The format is developed as an independent open-source project, with its own specification and tools. @@ -42,4 +42,4 @@ those fields together. - [Lance format specification](https://lance.org/format): how the format works. - [Table versioning](/management/table#versioning): read and manage table versions. - [Computed columns](/feature-engineering/add-computed-column): add derived features to your data. -- [Architecture](/architecture): how LanceDB OSS and Enterprise build on Lance. +- [Architecture](/index#architecture): how LanceDB Embedded and Enterprise build on Lance. diff --git a/docs/web/basics/limits.mdx b/docs/web/basics/limits.mdx index 0d4f1b028..c4af28c45 100644 --- a/docs/web/basics/limits.mdx +++ b/docs/web/basics/limits.mdx @@ -38,9 +38,9 @@ See [SQL job commands](/sql/ddl/job#errors) and Data-type and index constraints belong to the operation you choose. Check [Data types](/sql/data-types) and [Vector indexes](/indexing/vector-index) -before choosing a schema or index. For materialized views, check -[stable row ID requirements](/feature-engineering/materialized-views#stable-row-ids) -before creating source tables. +before choosing a schema or index. For materialized views, confirm your +source table meets your deployment's requirements with your administrator +before creating one over it. ## Configurable limits {#not-quotas} diff --git a/docs/web/basics/naming.mdx b/docs/web/basics/naming.mdx index af61c2b6c..b570e5bee 100644 --- a/docs/web/basics/naming.mdx +++ b/docs/web/basics/naming.mdx @@ -14,7 +14,7 @@ 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. -Use the following rules for names that work across LanceDB OSS and Enterprise. +Use the following rules for names that work across LanceDB Embedded and LanceDB Enterprise. | Object | Characters | Length | | --- | --- | --- | diff --git a/docs/web/basics/offerings.mdx b/docs/web/basics/offerings.mdx deleted file mode 100644 index c66b77e78..000000000 --- a/docs/web/basics/offerings.mdx +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: "LanceDB OSS or Enterprise?" -sidebarTitle: "OSS and Enterprise" -description: "Start with an embedded library, or use the LanceDB Enterprise multimodal lakehouse for shared AI workloads." -icon: compass -keywords: ["oss", "enterprise", "embedded", "deployment", "availability", "comparison"] ---- - -LanceDB gives you two ways to work with multimodal data, both built on the open -[Lance](/basics/lance) format. - -**LanceDB OSS** is an embedded library. Run it inside your application -with tables on local disk or in object storage. You control the application, -its resources, and table maintenance, without a separate database service. -[Try the quickstart](/quickstart) to create a table and run your first search. - -**LanceDB Enterprise** is a multimodal lakehouse for data curation, feature -engineering, search, and training data access. It adds query-serving capacity, -data caching, and background operations for teams working with shared -multimodal datasets. -[Connect to Enterprise](/basics/connect#enterprise) when your cluster is ready. - - - - -## Why choose Enterprise? {#why-enterprise} - -### Serve growing workloads {#serving} - -Add query-serving capacity as more applications and users depend on your data. -Enterprise spreads query traffic across a fleet and caches frequently read -table data near compute, reducing repeated reads from object storage. Query -serving and background work use separate resources, so you can size each for -your workload. See [Enterprise architecture](/enterprise/architecture). - -### Reduce operational work {#operations} - -Let the service handle routine table maintenance instead of scheduling it in -application code. Enterprise handles background [compaction](/maintenance/compaction) and can -[clean up old table versions](/maintenance/cleanup) according to your retention -policy. Configure these maintenance tasks for your Enterprise cluster so each -application does not have to schedule them. - -### Fit your deployment requirements {#deployment} - -Choose a managed deployment or bring LanceDB into your own cloud account. -Enterprise integrates with OpenTelemetry for metrics and traces, helping your -team monitor the service alongside your applications. Talk to us about your -cloud, networking, and operational requirements to plan the right deployment. -The [Enterprise overview](/enterprise) explains the available options. - -### Connect your data workflows {#workflows} - -Use the same tables for retrieval, dataset preparation, and training data access. -With its [SQL endpoint](/basics/sql) enabled, Enterprise supports analytical -[curation](/curation), including joins, grouping, and sampling. -[Feature engineering](/feature-engineering) adds derived columns and tables; -computed columns and materialized views require the corresponding features to -be enabled for your Enterprise cluster. -[Geneva](/geneva) runs Python feature backfills as distributed jobs. -[Training data loaders](/training/data-loading), available in both offerings, -read the resulting datasets for model training. - -## Plan your Enterprise deployment {#get-started} - -[Talk to us about your workload](https://www.lancedb.com/contact) to discuss your -data, query traffic, pipelines, and deployment requirements. - -For a closer look at how the service runs, read the -[Enterprise architecture](/enterprise/architecture). diff --git a/docs/web/basics/query.mdx b/docs/web/basics/query.mdx deleted file mode 100644 index 624617918..000000000 --- a/docs/web/basics/query.mdx +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: "Queries" -sidebarTitle: "Query" -description: "Choose how to query your data and read the results." -icon: magnifying-glass -keywords: ["query", "search", "SQL", "async", "streaming", "results"] ---- - -## Querying tables {#queries} - -A query selects data from your tables. You can filter rows, choose columns, -search for similar content or combine those operations. For example, a video -application might find clips similar to a sample and return only those recorded -in the last month. - -## SDK searches and SQL queries {#searches} - -| Interface | When to use it | -| --- | --- | -| **SDK query builders** | Build vector, full-text and hybrid searches, apply filters and choose the fields to return. Available in OSS and Enterprise. | -| **Enterprise SQL** | Write SQL queries for filtering, aggregation, joins and other data curation tasks. Connect through Python or a Flight SQL client. | - -Both interfaces work with LanceDB tables. Choose the one that supports your -operation and fits your application. See [SQL](/basics/sql) for connection -instructions and SQL search support, and [Search](/search) for the query builders. - -## Collect or stream results {#results} - -- **Collect the results** when you want a list, Arrow table or DataFrame that - fits in memory. Use a result limit and select only the columns you need. -- **Read batches** when you want to process a large result incrementally. - Reading batches avoids loading the entire result into application memory. - It does not guarantee that the query can return its first batch immediately. - -### Asynchronous clients {#async-client} - -An async client lets your application do other work while a request is waiting. -That is separate from whether you collect results or read them in batches. -Python offers synchronous and asynchronous clients; TypeScript uses async APIs. -Check the SDK reference for the methods available in your client. - -### Query handles and background jobs {#jobs} - -An Enterprise SQL query handle lets you inspect query execution and request -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. - -## Learn more {#next} - -- [Quickstart](/quickstart): run a complete create, insert and search example. -- [Search](/search): choose vector, full-text or hybrid retrieval. -- [Filtering](/search/filtering): narrow results with predicates. -- [SQL](/basics/sql): connect a client and run SQL queries. -- [SDKs](/basics/sdk): choose a language and find its API reference. diff --git a/docs/web/basics/sdk.mdx b/docs/web/basics/sdk.mdx index fc386bc7a..1d9312f77 100644 --- a/docs/web/basics/sdk.mdx +++ b/docs/web/basics/sdk.mdx @@ -4,30 +4,26 @@ 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"] -availability: - oss: available - enterprise: available - summary: >- - Python, TypeScript and Rust support both LanceDB OSS and LanceDB Enterprise. - Java provides a client for the Enterprise REST API. --- Use a LanceDB SDK to create tables, add data, build indexes and run searches -from your application. Python, TypeScript and Rust work with both the embedded -OSS library and LanceDB Enterprise. +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. The [quickstart](/quickstart) includes installation instructions and complete examples in all three languages. For connection settings, see -[Connect to LanceDB](/basics/connect). +[Connect to LanceDB](/basics/catalog). ## Official SDKs {#supported-sdks} -| SDK | Use it with | API reference | -| --- | --- | --- | -| Python | Python applications, notebooks, pandas and PyArrow | [Python reference](https://lancedb.github.io/lancedb/python/python/) | -| TypeScript | Node.js and TypeScript applications | [TypeScript reference](https://lancedb.github.io/lancedb/js/) | -| Rust | Rust applications using the native library | [Rust reference](https://docs.rs/lancedb/latest/lancedb/index.html) | -| Java | Applications using the Enterprise REST API | [Java reference](https://lancedb.github.io/lancedb/java/java/) | +| SDK | API reference | +| --- | --- | +| Python | [Python reference](https://lancedb.github.io/lancedb/python/python/) | +| TypeScript | [TypeScript reference](https://lancedb.github.io/lancedb/js/) | +| Rust | [Rust reference](https://docs.rs/lancedb/latest/lancedb/index.html) | Guides show the available language examples together. Use the API reference for method signatures and options; SDKs do not expose every feature through the same @@ -38,12 +34,35 @@ For SQL joins, aggregations and window functions, use languages can use a Flight SQL client. TypeScript's table query API does not provide a SQL execution method. -## REST API {#rest} +## Lance Namespace SDKs {#lance-namespace-sdks} -LanceDB Enterprise also exposes an HTTP API for catalog and table operations. -Use it when integrating a language or tool without a LanceDB SDK. The -[REST API reference](/api-reference/rest) describes its endpoints and request -formats. For SQL queries, connect through [Flight SQL](/basics/sql). +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. + +| Language | Package | Used by | +| --- | --- | --- | +| Java | `org.lance:lance-namespace-core` | Spark, Flink, Kafka, Trino, Presto; also LanceDB's Java client | +| Python | `lance-namespace` | Core interface and connect functionality | +| Rust | `lance-namespace` | Core interface, in [lance-format/lance](https://github.com/lance-format/lance) | + +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. +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. + +See [lance.org/format/namespace](https://lance.org/format/namespace) for the +full spec and its other catalog implementations (Directory, Apache Polaris, +Unity Catalog, Apache Hive Metastore, Apache Iceberg REST Catalog, and more). ## Community SDKs {#community-sdks} @@ -58,59 +77,15 @@ features, installation instructions and releases before choosing one. | R | [lancedb](https://github.com/CathalByrneGit/lancedb) | | Flutter | [flutter_lancedb](https://github.com/Alexcn/flutter_lancedb) | -## Python multiprocessing {#multiprocessing} - - -Use `spawn` when starting Python worker processes with `multiprocessing`. -LanceDB uses threads internally, and forking a process with active threads can -cause deadlocks. Create a connection inside each worker instead of sharing an -open connection from the parent process. - - -For PyTorch worker setup and connection factories, see -[PyTorch integration](/training/torch). - -## Moving to LanceDB Enterprise {#moving-to-enterprise} - -The core table workflow stays familiar: connect, create or open a table, write -records, and query them. Enterprise runs those operations on remote compute and -manages background maintenance. - -- **Configure the connection.** Replace the local path with your database URI, - and supply the endpoint, region and credentials provided by your administrator. - [Connect to Enterprise](/basics/connect#enterprise) shows these settings. -- **Retrieve query results.** Python's remote tables do not support whole-table - `to_arrow()` or `to_pandas()` calls. Use a query and select the columns and - number of rows you need, for example `table.search().limit(10).to_arrow()`. -- **Handle table listings and namespaces.** Remote table listings are paginated. - Use the namespace and pagination options described in - [Namespaces](/management/namespace). -- **Use server-side jobs.** Index builds and feature refreshes can run as - [jobs](/basics/jobs). Each operation's guide explains how to submit work and - track completion. -- **Let Enterprise manage maintenance.** Use - [background maintenance](/maintenance/background-jobs) rather than calling - the embedded table's `optimize()` method. - -For SQL connection details, see [SQL](/basics/sql). For the operating model and -deployment options, see [LanceDB Enterprise](/enterprise). - -## Shared data across languages {#invariants} - -LanceDB uses Arrow schemas across its SDKs. A fixed-size vector column stores -vectors of a consistent dimension; the [data types reference](/sql/data-types) -describes the supported element types and other column types. - -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. - ## Related guides {#next} Query Enterprise tables with SQL from Python or a Flight SQL client. + + Use LanceDB tables in a DataLoader, including multiple worker processes. + Use the LanceDB plugin to help a coding agent work with your data. diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index 1c4ad46cd..bb4f2cd4a 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -4,11 +4,6 @@ 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"] -availability: - oss: unavailable - enterprise: available - summary: >- - Enterprise supports SQL through Arrow Flight SQL. Use the SDK table APIs for embedded OSS tables. See [Connection settings](#sql-is-remote) to connect. --- Use SQL in LanceDB Enterprise to filter records, join tables, calculate @@ -16,26 +11,45 @@ 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. -You can run SQL through the Python SDK or an Arrow Flight SQL client. This -guide covers connection settings, a first query, and how SQL fits alongside -the SDK table APIs. +This guide covers the two ways to run SQL, connection settings, a first query, +parameterized queries, and how to read and manage the results. -## Connect a SQL client {#flight-sql} +## Access LanceDB with SQL {#access} -Enterprise exposes an -[Arrow Flight SQL](https://arrow.apache.org/docs/format/FlightSql.html) -endpoint. A compatible client sends SQL statements to this endpoint and -receives results as Arrow record batches. +There are two ways to run SQL against LanceDB Enterprise, both against the +same [Arrow Flight SQL](https://arrow.apache.org/docs/format/FlightSql.html) +endpoint, returning results as Arrow record batches: -- **Python:** use `execute_query()` on an Enterprise connection, as shown below. -- **TypeScript:** use a separate Flight SQL client. The LanceDB TypeScript SDK - does not expose a SQL execution method. -- **Other languages and tools:** use a Flight SQL client or a tool with Flight - SQL integration. A LanceDB-specific SDK is not required to submit SQL. +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 + 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. The [SQL reference](/sql#connecting) shows a query from Python. See [SDKs](/basics/sdk) for the LanceDB language clients. +### Adaptive query execution {#adaptive} + +A standard Flight SQL client calls `GetFlightInfo` to plan a query and then +`DoGet` to fetch rows -- two round trips every time, even when the server +could stream results back immediately. + +`execute_query()` skips that extra round trip when it can. It calls `DoGet` +directly for a query with no parameters, or `DoExchange` when +[binding parameters](#parameters), and sends a +`lancedb-sql-protocol: adaptive-v1` header. The server decides per query +whether to stream results on that same call or defer execution and return a +poll ticket; when it defers, `execute_query()` follows up with +`PollFlightInfo` automatically, with no extra code on your side. A generic +Flight SQL client does not send that header, so it always takes the slower +`GetFlightInfo` path. + ### Connection settings {#sql-is-remote} Get the following values from your Enterprise administrator: @@ -49,20 +63,21 @@ The Flight SQL endpoint must be enabled and reachable from your client. Pass it explicitly as `sql_host_override` in Python, as in the example below. The API and SQL endpoints may use different hosts or ports. -See [Connect to Enterprise](/basics/connect#enterprise) for other connection options. +See [Connect to Enterprise](/basics/catalog#enterprise) for other connection options. SQL runs in Enterprise. Connections to a local directory or an object-storage -bucket use the embedded OSS library and cannot execute SQL statements. Use +bucket use LanceDB Embedded and cannot execute SQL statements. Use SDK table operations to query those tables. ## Run a query in Python {#sql-from-python} Install the SDK with `pip install lancedb`. Replace the connection placeholders with your Enterprise settings, including the region and both endpoint URLs. -This example reads an existing table named `my_docs` with `id` and `text` -columns. Change the query to match your table. +This example reads an existing `frames` table, with a `video_id` and a +`caption` column describing each frame. Change the query to match your table. -```python + +```python Python icon="python" import lancedb db = lancedb.connect( @@ -73,31 +88,97 @@ db = lancedb.connect( sql_host_override="https://your-sql-endpoint:443", ) -reader = db.execute_query("SELECT id, text FROM my_docs LIMIT 10") +reader = db.execute_query("SELECT frame_id, video_id, caption FROM frames LIMIT 10") table = reader.read_all() print(table.to_pylist()) ``` + In application code, load credentials from environment variables or a secrets -manager. The [connection guide](/basics/connect#enterprise) shows that setup. +manager. The [connection guide](/basics/catalog#enterprise) shows that setup. -`execute_query()` returns a blocking Arrow reader when results start arriving. -The example uses `read_all()` to collect the small result in memory. For larger -results, consume the reader in batches. To submit a query and check its status -separately, use `execute_query_async()`. See [Queries](/basics/query) for query -handles, streaming, and cancellation. +`execute_query()` returns a blocking Arrow reader; see +[Adaptive query execution](#adaptive) for how it starts streaming. The example +above uses `read_all()` to collect the small result in memory. For larger +results, or to track and cancel a running query, see +[Read and manage results](#results). To submit a query and check its status +separately, use `execute_query_async()`. + +## Parameters in SQL queries {#parameters} + +Pass a `parameters` argument to bind values into a query, instead of +formatting them into the SQL string: + +```python +import numpy as np + +reader = db.execute_query( + "SELECT id FROM docs ORDER BY distance(vector, $1) LIMIT $2", + 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 +parameter with `$1`, `$2`, ... for positional binding, or `$name` for named +binding: + +- A list or tuple binds positionally, in order, to `$1`, `$2`, ... +- A dict binds by key to `$name`. +- A one-row `pyarrow.RecordBatch` or `Table` binds its columns, by name and by + position. +- A 1-D NumPy or Arrow array becomes a single fixed-size-list value -- use + this form for a vector argument, as shown above. + + +`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. + + +## Read and manage results {#results} + +- **Collect the results** when you want a list, Arrow table or DataFrame that + fits in memory. Use a result limit and select only the columns you need. +- **Read batches** when you want to process a large result incrementally. + Reading batches avoids loading the entire result into application memory. + It does not guarantee that the query can return its first batch immediately. + +### Asynchronous clients {#async-client} + +An async client lets your application do other work while a request is +waiting. That is separate from whether you collect results or read them in +batches. Python offers synchronous and asynchronous clients; TypeScript uses +async APIs. Check the SDK reference for the methods available in your client. + +### Query handles and background jobs {#jobs} + +An Enterprise SQL query handle lets you inspect query execution and request +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} 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 the embedded OSS library. +with LanceDB Embedded. 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 @@ -128,7 +209,7 @@ server version supports this form, then use [`EXPLAIN`](/sql/dql/explain) to inspect the query plan. The [SDK vector search API](/search/vector-search) is also available in -Enterprise and OSS. Use it when you prefer the SDK query builder or need to +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 @@ -150,8 +231,14 @@ and data types. For SDK methods and their arguments, use the ## Next steps {#next} - - Read results, track long-running queries, and cancel work. + + Run a complete create, insert and search example. + + + Choose vector, full-text or hybrid retrieval. + + + Narrow results with predicates. Compare language clients and find their API references. diff --git a/docs/web/curation/aggregate.mdx b/docs/web/curation/aggregate.mdx index b6d02d7fb..4fbca58f4 100644 --- a/docs/web/curation/aggregate.mdx +++ b/docs/web/curation/aggregate.mdx @@ -5,10 +5,8 @@ description: "Measure coverage, missing values and class balance before selectin icon: chart-column keywords: ["aggregate", "group by", "class balance", "count", "profiling", "distinct"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports SQL aggregation. --- Use SQL aggregates to summarize a dataset: count records, find missing values, diff --git a/docs/web/curation/changes.mdx b/docs/web/curation/changes.mdx new file mode 100644 index 000000000..28f98f784 --- /dev/null +++ b/docs/web/curation/changes.mdx @@ -0,0 +1,93 @@ +--- +title: "Scope curation to what changed" +sidebarTitle: "Changes" +description: "Process only the rows added since your last curation run, instead of rescanning the whole table." +icon: clock-rotate-left +keywords: ["changes", "incremental", "cdc", "version", "append-only"] +availability: + embedded: unavailable + enterprise: available +--- + +A curation task you run repeatedly -- chunking, deduplication, profiling -- +does not need to rescan rows it already processed. `CHANGES` reads only the +rows appended to a table since an earlier +[version](/management/table#versioning), so a recurring job can scope itself +to what is new. + +## Example data {#example-data} + +`curation_batches` gets a batch of new documents appended periodically, with +no updates or deletes between appends: + +```sql +CREATE TABLE curation_batches (doc_id BIGINT, source VARCHAR, text VARCHAR); +INSERT INTO curation_batches VALUES + (1, 'web', 'A cat on a chair'), + (2, 'web', 'A dog in a field'); +-- note the version after this insert, for example 5 +INSERT INTO curation_batches VALUES + (3, 'books', 'A bird in a tree'), + (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 +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 +the APIs that read a table's current version. + +## Chain it into a curation task {#chain} + +`CHANGES` is a relation, like any other table reference, so it composes with +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 +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 +would otherwise go, and only the new rows flow through it. + +## Strictly append-only {#strict} + +The clause is named for what it requires, not just what it does. If anything +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 +-- 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 +incrementally for that run. See +[Changes since a version](/sql/dql/changes#strict) for the complete set of +refused forms. + +## What to read next {#next} + + + + The full SQL syntax, placement rules, and unsupported forms. + + + How table versions work, and how to find one to start from. + + diff --git a/docs/web/curation/chunking.mdx b/docs/web/curation/chunking.mdx new file mode 100644 index 000000000..f4c0197b7 --- /dev/null +++ b/docs/web/curation/chunking.mdx @@ -0,0 +1,210 @@ +--- +title: "Chunk records into multiple rows" +sidebarTitle: "Chunking" +description: "Expand one source row into many derived rows -- documents into passages, videos into clips, images into tiles." +icon: diagram-subtask +keywords: ["chunking", "function", "udf", "lateral", "unnest", "1:N", "passages", "clips", "video", "frames"] +availability: + embedded: unavailable + enterprise: available +--- + +Every other curation task on this page keeps the row count the same or +smaller: profiling, sampling, joining, deduplicating. Chunking goes the other +way -- one source row becomes many derived rows, each carrying its parent's +columns along with it. Use it to split a document into passages for +embedding, a video into clips, or an image into tiles. + +## Define a chunking Function {#function} + +A Function that returns a `list` produces more than one value per input row. +A chunker is a Function whose output is a list -- of structs, of strings, of +anything -- registered like any other Function. See +[Create a Function](/curation/create-function) for CPU, GPU and remote-service +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: + +**Source: `documents`** + +| doc_id | title | text | +| --- | --- | --- | +| 1 | "Intro to AI" | "Machine learning is a method of..." (long text) | + + +```python Python icon="python" +import pyarrow as pa +from lancedb.functions import udf + +@udf( + output_schema=pa.list_( + pa.struct([ + pa.field("chunk_index", pa.int64(), nullable=False), + pa.field("chunk_text", pa.utf8(), nullable=False), + ]) + ), +) +def split_into_passages(text: str) -> list[dict]: + size = 200 + return [ + {"chunk_index": i, "chunk_text": text[i : i + size]} + for i in range(0, len(text), size) + ] + +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 +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)]' +``` + + +## 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: + + +```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()) +``` + + +A document with five 200-character passages becomes five output rows, each +carrying `doc_id` and `title` from its parent. This is the fastest way to +check a chunker before committing to a materialized view: run it over a few +rows and inspect the output shape. + +## Video into frames {#video} + +Chunking a blob column is the same shape, with the chunker producing +timestamps rather than text spans, and a second Function pulling the actual +frame for each one. `videos` holds raw clips in a +[Blob v2](/management/table#managed-blobs) column, with each row's duration +already known: + +**Source: `videos`** + +| video_id | video | duration_seconds | +| --- | --- | --- | +| "clip-1" | (Blob v2 bytes) | 12.0 | + +A chunker that samples one timestamp per second needs no blob access at all +-- it only looks at `duration_seconds`: + + +```python Python icon="python" +@udf( + output_schema=pa.list_( + pa.struct([ + pa.field("frame_index", pa.int64(), nullable=False), + pa.field("ts", pa.float64(), nullable=False), + ]) + ), +) +def sample_frame_timestamps(duration_seconds: float) -> list[dict]: + every = 1.0 # one frame per second + count = int(duration_seconds // every) + return [{"frame_index": i, "ts": i * every} for i in range(count)] + +version = db.create_function_async(sample_frame_timestamps).wait() +``` + + +A second Function reads the blob -- incrementally, through a `BlobReader`, +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( + 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 + +extract_version = db.create_function_async(extract_frame).wait(timeout=timedelta(minutes=15)) +``` + + +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 +""") +``` + + +A 12-second clip becomes 12 output rows, each with its own extracted JPEG. A +Function in `FROM` position yields one row per list element the same way +regardless of what the list holds; whether the second step produces a blob, +a plain value, or another struct does not change the explosion. + +## Persist it as a materialized view {#persist} + +Wrap either query in [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view) +to keep a real table that stays current as the source changes, instead of +recomputing the explosion on every query: + + +```sql SQL +CREATE MATERIALIZED VIEW chunks AS +SELECT doc_id, title, p.chunk_index, p.chunk_text +FROM documents, split_into_passages(text) AS p +``` + + +**Derived: `chunks`** (1:N expansion) + +| doc_id | title | chunk_index | chunk_text | +| --- | --- | --- | --- | +| 1 | "Intro to AI" | 0 | "Machine learning is a method..." | +| 1 | "Intro to AI" | 1 | "...of teaching computers..." | + +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. + +## 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 +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/create-function.mdx b/docs/web/curation/create-function.mdx new file mode 100644 index 000000000..2d161e84b --- /dev/null +++ b/docs/web/curation/create-function.mdx @@ -0,0 +1,213 @@ +--- +title: "Create a Function" +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 +keywords: ["function", "udf", "cpu", "gpu", "batch", "scalar", "blob", "remote api", "embedding", "rate limiter"] +availability: + embedded: unavailable + enterprise: available +--- + +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. + +## Scalar: once per row {#scalar} + +The plain form takes one row's values and returns one result. Types are +inferred from the annotations: + + +```python Python icon="python" +from lancedb import udf + +@udf(pip=["numpy==2.2.0"]) +def score(value: float) -> float: + return value * 2 + +version = db.create_function_async(score).wait() +table.add_columns({"doubled": version(value=col("value"))}) +``` + + +`pip` declares the worker's dependencies; they are part of the function's +immutable version, so changing one produces a new version rather than +altering rows a previous version already filled. + +## Batch: once per call, many rows at a time {#batch} + +A function is called once per batch instead of once per row when its +parameters are annotated `pyarrow.Array`, or when it takes a single +`pyarrow.RecordBatch` parameter to read more than one column together. The +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 + +@udf(pip=["numpy==2.2.0"]) +def score_batch(value: pa.Array) -> pa.Array: + return pc.multiply(value, 2) +``` + + +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. + +## Stateful Functions: load once, call many times {#stateful} + +A `@udf`-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 + +@udf +class scale: + def __init__(self, factor: float, offset: float = 0.0): + self.factor = factor + self.offset = offset + + def __call__(self, value: float) -> float: + return value * self.factor + self.offset +``` + + +Constructor parameters are **initialization fields**, bound once per binding +rather than read per row -- mixed with per-row columns in the same call: +`version(value=col("value"), factor=2.0)`. Load models, open clients, and +build rate limiters in `__init__`; every batch the instance serves then +reuses them, since an instance's state is shared across its own batches but +never across other instances or workers. This is the pattern GPU inference +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: + + +```python Python icon="python" +import pyarrow as pa +from lancedb import udf + +@udf(gpu=True, 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 + from sentence_transformers import SentenceTransformer + + device = "cuda" if torch.cuda.is_available() else "cpu" + self.model = SentenceTransformer(model_name, device=device) + + def __call__(self, text: pa.Array) -> pa.Array: + texts = [t or "" for t in text.to_pylist()] + embeddings = self.model.encode(texts) + return pa.array(embeddings.tolist(), type=pa.list_(pa.float32(), list_size=384)) + +version = db.create_function_async(embed_text).wait() +table.add_columns({"embedding": version(text=col("caption"))}) +``` + + +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. + +## Calling a remote service {#remote} + +A function that calls an external API needs a credential without putting it +in the function's source. A Secret is a database-scoped named credential: +`db.create_secret` stores the value once, and binding it at registration time +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: + + +```python Python icon="python" +import os +from lancedb import EnvVarSecret, udf + +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} + +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): + + +```python Python icon="python" +import pyarrow as pa +import lancedb +from lancedb import BlobReader, udf + +@udf( + 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 +``` + + +`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. + +## What to read next {#next} + + + + A Function whose output is a list, exploded into one row per element. + + + Filling the column a Function is bound to, and re-filling it as inputs change. + + diff --git a/docs/web/curation/dedupe.mdx b/docs/web/curation/dedupe.mdx new file mode 100644 index 000000000..bdcf0b4b2 --- /dev/null +++ b/docs/web/curation/dedupe.mdx @@ -0,0 +1,142 @@ +--- +title: "Deduplicate near-duplicate records" +sidebarTitle: "Dedupe" +description: "Collapse records that are only approximately alike, judged by embedding distance, without a pairwise scan." +icon: clone +keywords: ["dedupe", "duplicate_pairs", "deduplication", "near-duplicate", "embedding", "distance_threshold"] +availability: + embedded: unavailable + enterprise: available +--- + +[Ranking and deduplication](/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 +camera holding one pose for a few seconds, or two scraped pages with the same +paragraph reworded. `dedupe` and `duplicate_pairs` find these directly over a +vector index, without a pairwise scan. + +## Example data {#example-data} + +Connect with an [Enterprise connection](/basics/catalog#enterprise). A small +fixture keeps the distances easy to check by hand. + + + +`curation_embeddings` has eight records. Rows 10 and 20 are near-identical; +rows 30, 40 and 50 form one looser cluster; the rest are distinct. + + +```python Python icon="python" +import pyarrow as pa +from lancedb.index import IvfFlat + +schema = pa.schema([ + pa.field("id", pa.int64(), nullable=False), + pa.field("caption", pa.utf8()), + pa.field("embedding", pa.list_(pa.float32(), 2)), +]) +table = db.create_table("curation_embeddings", [ + {"id": 10, "caption": "a cat on a chair", "embedding": [0.0, 0.0]}, + {"id": 20, "caption": "a cat on the chair", "embedding": [0.0, 0.03]}, + {"id": 30, "caption": "a dog in a field", "embedding": [5.0, 5.0]}, + {"id": 40, "caption": "a dog in the field", "embedding": [5.0, 5.05]}, + {"id": 50, "caption": "a dog out in a field", "embedding": [5.0, 5.10]}, + {"id": 60, "caption": "a bird in a tree", "embedding": [10.0, 10.0]}, + {"id": 70, "caption": "a boat on the water", "embedding": [20.0, 20.0]}, + {"id": 80, "caption": "a car on the road", "embedding": [30.0, 30.0]}, +], schema=schema) + +table.create_index("embedding", config=IvfFlat(num_partitions=1, distance_type="l2")) +table.wait_for_index(["embedding_idx"]) +``` + + +`dedupe` and `duplicate_pairs` read the vector index, so the column needs one +before either function runs; a query against unindexed fragments is rejected +rather than silently returning stale or wrong results. + + + +## 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: + + +```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, ...}] +``` + + +Every other column survives unchanged, since `dedupe` returns full rows, not +just which ones matched. Clustering is transitive: 30 and 40 are within +`distance_threshold` of each other, and so are 40 and 50, so all three +collapse into one representative even though 30 and 50 alone sit outside the +threshold. Pass `resolution => 'direct_representative'` +for a simpler, non-transitive selection instead, if a chained cluster like that +should not merge into one representative. + +Which row survives as the representative is not guaranteed to stay the same +across appends: a later row that bridges two previously separate clusters can +change which id represents the merged cluster. Do not treat a representative's +id as a stable identifier for its cluster. + +## Inspect the pairs instead {#pairs} + +`duplicate_pairs` returns the matching edges themselves, without collapsing +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 +""") +``` + + +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), +even though `dedupe` merges all three transitively above. + +## Keep it current with a materialized view {#materialized} + +Wrap either call in a [materialized view](/management/materialized-view) so +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) +""") +``` + + +See [Refresh a materialized view](/feature-engineering/refresh-materialized-view) +for manual and automatic refresh options to keep it current as new records land. + +## At production scale {#production} + +[LeRobotDataset](/integrations/lerobotdataset) runs the same `dedupe` +call over 27.6 million real embedding rows to remove near-static frames from a +robotics training set in under 30 seconds -- the mechanism does not change +with scale, only the table it runs against. + +## Continue with the curated data {#next} + +[Profile the result](/curation/aggregate) to check how much a threshold +removes before committing to it, or go back to +[choosing a curation task](/curation#questions). diff --git a/docs/web/curation/index.mdx b/docs/web/curation/index.mdx index fd8ea73aa..c4d6a48e5 100644 --- a/docs/web/curation/index.mdx +++ b/docs/web/curation/index.mdx @@ -17,14 +17,18 @@ 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. | +| [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. | | [Join datasets](/curation/join) | How to attach labels, metadata or scores stored elsewhere. | -| [Rank and deduplicate](/curation/windowing) | Which records to keep when several describe the same item. | +| [Rank and deduplicate](/curation/windowing) | Which records to keep when several share an explicit key. | +| [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 OSS or -Enterprise, see [Sample without SQL](/curation/sampling#training). +the [SQL guide](/basics/sql). For sampling through the Python SDK in LanceDB Embedded or +LanceDB Enterprise, see [Sample without SQL](/curation/sampling#training). ## Prepare a labeled document dataset {#shape} diff --git a/docs/web/curation/join.mdx b/docs/web/curation/join.mdx index 03a45326e..3306ca511 100644 --- a/docs/web/curation/join.mdx +++ b/docs/web/curation/join.mdx @@ -5,10 +5,8 @@ description: "Combine records with labels or metadata, and check for missing or icon: link keywords: ["join", "labels", "metadata", "enrichment", "namespace"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports SQL joins. --- A SQL join combines records from two tables using a shared key. Use joins to @@ -127,6 +125,38 @@ Use [Explain a query plan](/search/explain) 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. + ## Save the result or continue curating {#reference} Keep the query for reuse or [save the selected data](/curation#next). diff --git a/docs/web/curation/sampling.mdx b/docs/web/curation/sampling.mdx index 643b06bdf..82f1c1ecb 100644 --- a/docs/web/curation/sampling.mdx +++ b/docs/web/curation/sampling.mdx @@ -1,14 +1,12 @@ --- -title: "SQL sampling" -sidebarTitle: "SQL Sampling" +title: "Sampling" +sidebarTitle: "Sampling" description: "Choose a sample for exploration or evaluation and preserve the selected records when reproducibility matters." icon: dice keywords: ["sampling", "tablesample", "subset", "eval set", "reproducible", "shuffle"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports SQL `TABLESAMPLE`. For sampling in OSS and Enterprise through the Python SDK, see [Sample without SQL](#training). --- import { PySampleDataset } from '/snippets/curation_sampling.mdx'; @@ -143,7 +141,7 @@ for sampling. `TABLESAMPLE` cannot be applied directly to a subquery result. ## Sample without SQL {#training} The Python SDK provides a permutation builder for selecting and ordering rows -in OSS and Enterprise. A split selects a subset; a shuffle changes the order +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. @@ -163,7 +161,7 @@ promise the same IDs across SDK versions or changes to the source dataset. For shuffled training reads, worker configuration and data loaders, see -[Loading data for model training](/training/data-loading). +[PyTorch Data Loader](/training/data-loading). ## Related guides {#reference} diff --git a/docs/web/curation/windowing.mdx b/docs/web/curation/windowing.mdx index fa84ed5fe..6cb5322d6 100644 --- a/docs/web/curation/windowing.mdx +++ b/docs/web/curation/windowing.mdx @@ -5,10 +5,8 @@ description: "Choose records with explicit ranking rules and deterministic tie h icon: chart-simple keywords: ["window", "deduplication", "row_number", "rank", "train test split", "per class"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports SQL window functions. --- Window functions calculate values across related rows while keeping each row diff --git a/docs/web/deployment/monitoring.mdx b/docs/web/deployment/monitoring.mdx index b31293338..7d19fc1a5 100644 --- a/docs/web/deployment/monitoring.mdx +++ b/docs/web/deployment/monitoring.mdx @@ -11,7 +11,7 @@ LanceDB emits internal metrics (currently object store request counts, bytes tra The bridge is available in the Python and TypeScript SDKs. It is a thin wrapper over LanceDB's `metrics` recorder; your application supplies and configures the OpenTelemetry SDK. -This page covers LanceDB OSS instrumentation. LanceDB Enterprise clusters emit their own metrics from the server side. See [Enterprise monitoring](#enterprise) below. +This page covers LanceDB Embedded instrumentation. LanceDB Enterprise clusters emit their own metrics from the server side. See [Enterprise monitoring](#enterprise) below. ## Available metrics {#what-you-get} @@ -113,7 +113,7 @@ export them with data enrichment. No client-side instrumentation is needed. | Component | Metrics | | --- | --- | | Query node | RPS, query latency, error codes, slow-query count, CPU/memory utilization | -| Plan executor | SSD cache hit/miss rate, CPU/memory utilization | +| Executor | SSD cache hit/miss rate, CPU/memory utilization | [Contact support](/deployment/support) for the comprehensive metric list and help integrating them with your monitoring dashboard. diff --git a/docs/web/deployment/storage.mdx b/docs/web/deployment/storage.mdx index 35b6dd80f..50746d778 100644 --- a/docs/web/deployment/storage.mdx +++ b/docs/web/deployment/storage.mdx @@ -1,23 +1,16 @@ --- -title: "Embedded storage configuration" -sidebarTitle: "Embedded Storage" -description: "Choose and configure local disk or object storage for tables accessed by the embedded LanceDB OSS library." +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"] -availability: - oss: available - enterprise: unavailable - summary: >- - The embedded library chooses and configures its storage backend from the - connection URI and `storage_options`. In LanceDB Enterprise, storage is part of - the deployment's own configuration instead. --- -This page is about the embedded library, where your connection chooses and +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 -[Deployment](/enterprise/deployment) for how a deployment is set up. +[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). @@ -124,7 +117,7 @@ import { **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 [Azure deployment guide](/enterprise/deployment/azure) for the Enterprise flow. +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} diff --git a/docs/web/deployment/support.mdx b/docs/web/deployment/support.mdx index 5e35d9131..148e71648 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 OSS, dedicated support for Enterprise." +description: "Where to get help: community Discord for LanceDB Embedded (open source), dedicated support for LanceDB Enterprise." icon: circle-question keywords: ["support", "help", "discord", "community"] --- -## LanceDB OSS {#oss} +## LanceDB Embedded (open source) {#oss} For a quick question, the [Discord community](https://discord.gg/AUEWnJ7Txb) has channels for diff --git a/docs/web/docs.json b/docs/web/docs.json index a8fb44007..871e375f8 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -27,6 +27,42 @@ }, "favicon": "/static/favicon.ico", "redirects": [ + { + "source": "/architecture", + "destination": "/#architecture" + }, + { + "source": "/enterprise/architecture", + "destination": "/#architecture" + }, + { + "source": "/enterprise/deployment/azure", + "destination": "/enterprise/deployment/kubernetes" + }, + { + "source": "/basics/query", + "destination": "/basics/sql#results" + }, + { + "source": "/basics/offerings", + "destination": "/#embedded-and-enterprise" + }, + { + "source": "/enterprise/deployment", + "destination": "/enterprise#deployment" + }, + { + "source": "/feature-engineering/data-evolution", + "destination": "/feature-engineering/add-computed-column" + }, + { + "source": "/training/torch", + "destination": "/training/data-loading" + }, + { + "source": "/basics/lakehouse", + "destination": "/" + }, { "source": "/tables/update", "destination": "/ingestion/update" @@ -209,7 +245,7 @@ }, { "source": "/sql/refresh", - "destination": "/sql/dml/refresh" + "destination": "/sql/dml/refresh-column" }, { "source": "/sql/show", @@ -245,13 +281,17 @@ "group": "Getting Started", "pages": [ "index", - "basics/offerings", - "basics/connect", "quickstart", - "architecture", "basics/sdk", "basics/sql", - "basics/agentic-skills" + "basics/agentic-skills", + "deployment/support" + ] + }, + { + "group": "Tools", + "pages": [ + "tools/cli" ] }, { @@ -259,9 +299,8 @@ "pages": [ "basics/lance", "basics/catalog", - "basics/lakehouse", - "basics/query", "basics/jobs", + "tables/realtime-engine", "tables/consistency", "basics/guarantees", "basics/limits", @@ -276,7 +315,8 @@ "ingestion/insert", "ingestion/merge-insert", "ingestion/update", - "ingestion/delete" + "ingestion/delete", + "ingestion/realtime-write" ] }, { @@ -288,35 +328,42 @@ "search/hybrid-search", "search/filtering", "reranking/index", - "search/explain" + "search/explain", + "search/realtime-read", + "enterprise/distributed-search" ] }, { "group": "Data Curation", "pages": [ "curation/index", + "curation/create-function", + "curation/chunking", + "curation/changes", "curation/aggregate", "curation/sampling", "curation/join", - "curation/windowing" + "curation/windowing", + "curation/dedupe" ] }, { "group": "Feature Engineering", "pages": [ "feature-engineering/index", - "feature-engineering/data-evolution", "feature-engineering/add-computed-column", "feature-engineering/refresh-column", - "feature-engineering/materialized-views" + "feature-engineering/view", + "feature-engineering/materialized-views", + "feature-engineering/refresh-materialized-view" ] }, { "group": "Training", "pages": [ - "training/why-lancedb", + "training/permutation", "training/data-loading", - "training/torch" + "training/distributed-training" ] }, { @@ -327,18 +374,24 @@ "management/namespace", "management/table", "tables/branching", - "management/materialized-view", - "management/view" + "management/view", + "management/materialized-view" ] }, { "group": "Maintenance", "pages": [ - "indexing/index", - "indexing/vector-index", - "indexing/fts-index", - "indexing/scalar-index", - "indexing/reindexing", + { + "group": "Indexing", + "icon": "layer-group", + "pages": [ + "indexing/index", + "indexing/vector-index", + "indexing/fts-index", + "indexing/scalar-index", + "indexing/reindexing" + ] + }, "maintenance/compaction", "maintenance/cleanup", "maintenance/background-jobs" @@ -348,13 +401,10 @@ "group": "Deployment", "pages": [ "enterprise/index", - "enterprise/architecture", - "enterprise/deployment/index", "deployment/storage", "deployment/monitoring", - "enterprise/deployment/azure", - "enterprise/benchmarks", - "deployment/support" + "enterprise/deployment/kubernetes", + "enterprise/benchmarks" ] }, { @@ -373,6 +423,7 @@ { "group": "DDL", "pages": [ + "sql/ddl/database", "sql/ddl/namespace", "sql/ddl/table", "sql/ddl/view", @@ -389,7 +440,8 @@ "sql/dml/update", "sql/dml/delete", "sql/dml/copy", - "sql/dml/refresh" + "sql/dml/refresh-column", + "sql/dml/refresh-materialized-view" ], "icon": "database" }, @@ -402,7 +454,10 @@ "sql/dql/aggregation", "sql/dql/window", "sql/dql/sampling", + "sql/dql/changes", "sql/dql/fts", + "sql/dql/dedupe", + "sql/dql/duplicate-pairs", "sql/dql/explain" ], "icon": "filter" @@ -444,6 +499,7 @@ "integrations/embedding/imagebind", "integrations/embedding/instructor", "integrations/embedding/jina", + "integrations/embedding/nvidia", "integrations/embedding/ollama", "integrations/embedding/openai", "integrations/embedding/openclip", @@ -488,7 +544,8 @@ "integrations/ai/genkit", "integrations/ai/kiln", "integrations/ai/prompttools", - "integrations/ai/synthetic-data-kit" + "integrations/ai/synthetic-data-kit", + "integrations/ai/vscode" ] } ] diff --git a/docs/web/embedding/index.mdx b/docs/web/embedding/index.mdx index 4402feddf..91efcc566 100644 --- a/docs/web/embedding/index.mdx +++ b/docs/web/embedding/index.mdx @@ -4,12 +4,8 @@ sidebarTitle: "Managing Embeddings" description: "Use the embedding API in LanceDB: registry, functions, schemas, and multi-language SDK support." icon: "bars" availability: - oss: available + embedded: available enterprise: available - summary: >- - Embedding functions run in your process, whether the table is local or on a - deployment, which stores their configuration but never runs them. Python - and TypeScript also embed query text; in Rust you embed queries yourself. --- import { @@ -35,7 +31,7 @@ Modern machine learning models can be trained to convert raw data into embedding of floating point numbers. The position of an embedding in vector space captures the semantics of the data, so vectors that are close to each other are considered similar. -LanceDB provides an embedding function registry in OSS as well as its Enterprise versions +LanceDB provides an embedding function registry in LanceDB Embedded as well as LanceDB Enterprise ([see below](#embeddings-in-lancedb-enterprise)) that automatically generates vector embeddings during data ingestion. Query text is embedded automatically too, in the client, for local and Enterprise tables alike, with SDK-specific query @@ -181,7 +177,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` | -| Cohere | `cohere` | `embed-english-v3.0` | +| Cohere | `cohere` | `embed-multilingual-v3.0` | | ... | ... | ... | ### Multimodal embedding {#multimodal-embedding} @@ -198,7 +194,7 @@ You can find all supported embedding models in the [integrations](/integrations/ Enterprise In LanceDB Enterprise, embedding generation during data ingestion is client-side and the resulting vectors are -stored on the remote table. +stored in the Enterprise table. The Enterprise server does not currently generate embeddings from query text on its own. Any automatic @@ -207,13 +203,13 @@ query-time embedding happens on the client side. ### How string queries are interpreted {#how-string-queries-are-interpreted} -For the Python remote client, `table.search("hello")` can take two different paths: +When the Python SDK connects to Enterprise, `table.search("hello")` can take two different paths: - If the selected vector column has embedding metadata (i.e., the table schema stores the source-column, vector-column, and embedding-function mapping created from fields like `SourceField()` and `VectorField()` during table creation), then the embeddings are computed in the Python client process. - The client uses the same local LanceDB embedding registry used by OSS tables to + 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 diff --git a/docs/web/embedding/quickstart.mdx b/docs/web/embedding/quickstart.mdx index bcaf90f6f..1111743da 100644 --- a/docs/web/embedding/quickstart.mdx +++ b/docs/web/embedding/quickstart.mdx @@ -42,11 +42,11 @@ from lancedb.embeddings import get_registry ## Step 2: Connect to LanceDB {#step-2-connect-to-lancedb} -Establish a connection to your LanceDB OSS directory or Enterprise cluster: +Establish a connection to your LanceDB Embedded directory or Enterprise cluster: ```python Python icon="python" -# Enter your LanceDB connection URI for OSS or Enterprise here +# Enter your LanceDB connection URI for LanceDB Embedded or Enterprise here db = lancedb.connect(...) ``` @@ -126,8 +126,8 @@ LanceDB preserves them instead of filling only the missing rows. ## Step 6: Query with Automatic Embedding {#step-6-query-with-automatic-embedding} -Note: On LanceDB Enterprise, the server does not generate embeddings from query text. In the Python remote -client, `table.search("greetings")` can still work when the table schema includes embedding metadata, because +Note: On LanceDB Enterprise, the server does not generate embeddings from query text. When the Python +SDK connects to Enterprise, `table.search("greetings")` can still work when the table schema includes embedding metadata, because the client computes the query embedding before sending the vector search. If there is no embedding metadata for that search, `search("greetings")` in `auto` mode is treated as FTS instead. diff --git a/docs/web/enterprise/architecture.mdx b/docs/web/enterprise/architecture.mdx deleted file mode 100644 index c47dcbd2e..000000000 --- a/docs/web/enterprise/architecture.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: "Enterprise architecture" -sidebarTitle: "Architecture" -description: "The tiers a deployment runs, and how they scale independently." -icon: cubes -keywords: ["architecture", "control plane", "data plane", "indexer"] ---- - -Enterprise - -This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. - -A deployment separates compute from storage so each scales on its own: table -data and indexes live in object storage, while query serving and background work -run on machines that can be replaced without any of them owning the data. - -[Architecture](/architecture) covers this alongside the embedded form, which is -the comparison most readers want first. diff --git a/docs/web/enterprise/authentication.mdx b/docs/web/enterprise/authentication.mdx index 3a570d1d9..920275d16 100644 --- a/docs/web/enterprise/authentication.mdx +++ b/docs/web/enterprise/authentication.mdx @@ -3,19 +3,15 @@ title: "Authentication" sidebarTitle: "Authentication" description: "Authentication modes for LanceDB Enterprise: API keys and OAuth credentials." icon: key -keywords: ["authentication", "oauth", "api key", "azure managed identity", "client credentials"] +keywords: ["authentication", "oauth", "api key", "authorization code", "device code", "azure managed identity", "client credentials"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Requests to a deployment carry an API key or an OAuth token, whichever it is - configured to accept. Embedded LanceDB has no server to sign in to; see - [Architecture](/architecture). --- -A deployment authenticates every request before -[authorization](/governance/authorization) decides what it may do, against a -`db://` remote table, in one of two ways: +A deployment authenticates each request over a `db://` connection before +[authorization](/governance/authorization) decides what it may do. +Choose one of these methods: - **API keys**: a long-lived shared secret passed as `api_key` on connect. Works in every SDK. - **OAuth 2.0**: short-lived bearer tokens obtained from your identity provider, refreshed automatically by the client. @@ -28,55 +24,91 @@ identities so no secret material lives on the client. Pass the API key from your Enterprise tenant on `connect`. This works with both the synchronous and asynchronous Python clients, as well as TypeScript -and Rust. +and Rust. Load the key from an environment variable or secret manager. -```python + +```python Python icon="python" +import os import lancedb db = lancedb.connect( uri="db://your-database-uri", - api_key="your-api-key", + api_key=os.environ["LANCEDB_API_KEY"], region="us-east-1", host_override="https://your-enterprise-endpoint.com", ) ``` -An API key belongs in the environment rather than in source. See -[Database](/management/database#deployment) for the connection options. +```typescript TypeScript icon="square-js" +import * as lancedb from "@lancedb/lancedb"; + +const apiKey = process.env.LANCEDB_API_KEY; +if (!apiKey) throw new Error("LANCEDB_API_KEY is required"); + +const db = await lancedb.connect("db://your-database-uri", { + apiKey, + region: "us-east-1", + hostOverride: "https://your-enterprise-endpoint.com", +}); +``` + +```rust Rust icon="rust" +let api_key = std::env::var("LANCEDB_API_KEY")?; + +let db = lancedb::connect("db://your-database-uri") + .api_key(&api_key) + .region("us-east-1") + .host_override("https://your-enterprise-endpoint.com") + .execute() + .await?; +``` + + +For Rust, enable the `remote` feature on the `lancedb` dependency to use +API key or OAuth authentication. + +See [Database](/management/database#deployment) for the connection options. ## OAuth {#oauth} -The async Python client and the TypeScript client can obtain bearer tokens +The async Python, TypeScript, and Rust clients can obtain bearer tokens from an OIDC issuer and attach them to every request. Token acquisition, caching, and refresh are handled inside the client. Your application code only provides the configuration. A deployment accepts these tokens only when its administrator has configured -it with your identity provider. Ask them for the issuer URL, client ID and -scopes to use. +it with your identity provider. Ask them for the issuer URL, client ID, scopes, +and any resource or audience required by the provider. For Authorization Code, +register the loopback redirect URI with the provider. For Device Code, enable +the provider's device authorization grant for your application. In Python, OAuth is supported through `lancedb.connect_async`. The synchronous `connect` entry point continues to use API key authentication for `db://` URIs. In TypeScript, `lancedb.connect` accepts `oauthConfig` directly. +In Rust, use `.oauth_config(config)` on the connection builder. ### Supported flows {#supported-flows} -`OAuthFlowType` selects how the client acquires tokens: +`OAuthFlowType` (Python and TypeScript) or `OAuthFlow` (Rust) selects how the +client acquires tokens: -| Flow | Python value | TypeScript value | When to use | -| --- | --- | --- | --- | -| Client Credentials | `OAuthFlowType.CLIENT_CREDENTIALS` | `OAuthFlowType.ClientCredentials` | Service-to-service / machine-to-machine. Requires a client ID and client secret registered with your identity provider. | -| Azure Managed Identity | `OAuthFlowType.AZURE_MANAGED_IDENTITY` | `OAuthFlowType.AzureManagedIdentity` | Workloads running on Azure compute (VMs, AKS, App Service, Container Apps). Tokens are fetched from the Azure IMDS endpoint, so no client secret is stored on the client. | +| Flow | Python value | TypeScript value | Rust value | When to use | +| --- | --- | --- | --- | --- | +| 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. | +| 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} Build an OAuth config and pass it on connect. Use `oauth_config` in Python and -`oauthConfig` in TypeScript. +Rust, and `oauthConfig` in TypeScript. ```python Python icon="python" +import os import lancedb from lancedb.remote import OAuthConfig, OAuthFlowType @@ -84,7 +116,7 @@ from lancedb.remote import OAuthConfig, OAuthFlowType oauth_config = OAuthConfig( issuer_url="https://login.microsoftonline.com/{tenant}/v2.0", client_id="your-application-client-id", - client_secret="your-application-client-secret", + client_secret=os.environ["LANCEDB_OAUTH_CLIENT_SECRET"], scopes=["api://lancedb-api/.default"], flow=OAuthFlowType.CLIENT_CREDENTIALS, ) @@ -101,11 +133,14 @@ db = await lancedb.connect_async( import * as lancedb from "@lancedb/lancedb"; import { OAuthConfig, OAuthFlowType } from "@lancedb/lancedb"; +const clientSecret = process.env.LANCEDB_OAUTH_CLIENT_SECRET; +if (!clientSecret) throw new Error("LANCEDB_OAUTH_CLIENT_SECRET is required"); + // Client Credentials (service-to-service) const oauthConfig: OAuthConfig = { issuerUrl: "https://login.microsoftonline.com/{tenant}/v2.0", clientId: "your-application-client-id", - clientSecret: "your-application-client-secret", + clientSecret, scopes: ["api://lancedb-api/.default"], flow: OAuthFlowType.ClientCredentials, }; @@ -116,9 +151,34 @@ const db = await lancedb.connect("db://your-database-uri", { oauthConfig, }); ``` + +```rust Rust icon="rust" +use lancedb::remote::{OAuthConfig, OAuthFlow}; + +// Client Credentials (service-to-service) +let oauth_config = OAuthConfig { + issuer_url: "https://login.microsoftonline.com/{tenant}/v2.0".into(), + client_id: "your-application-client-id".into(), + client_secret: Some(std::env::var("LANCEDB_OAUTH_CLIENT_SECRET")?), + scopes: vec!["api://lancedb-api/.default".into()], + flow: OAuthFlow::ClientCredentials, + client_auth_method: None, + resource: None, + audience: None, + refresh_buffer_secs: None, + token_cache: None, +}; + +let db = lancedb::connect("db://your-database-uri") + .region("us-east-1") + .host_override("https://your-enterprise-endpoint.com") + .oauth_config(oauth_config) + .execute() + .await?; +``` -For workloads running on Azure compute, use a managed identity instead of a +For Azure workloads with access to IMDS, use a managed identity instead of a client secret: @@ -130,8 +190,8 @@ oauth_config = OAuthConfig( client_id="your-application-client-id", scopes=["api://lancedb-api/.default"], flow=OAuthFlowType.AZURE_MANAGED_IDENTITY, - # Optional: required only for user-assigned managed identities. - managed_identity_client_id="your-user-assigned-identity-client-id", + # Set only for a user-assigned managed identity: + # managed_identity_client_id="your-user-assigned-identity-client-id", ) ``` @@ -143,33 +203,221 @@ const oauthConfig: OAuthConfig = { clientId: "your-application-client-id", scopes: ["api://lancedb-api/.default"], flow: OAuthFlowType.AzureManagedIdentity, - // Optional: required only for user-assigned managed identities. - managedIdentityClientId: "your-user-assigned-identity-client-id", + // Set only for a user-assigned managed identity: + // managedIdentityClientId: "your-user-assigned-identity-client-id", +}; +``` + +```rust Rust icon="rust" +use lancedb::remote::{OAuthConfig, OAuthFlow}; + +let oauth_config = OAuthConfig { + issuer_url: "https://login.microsoftonline.com/{tenant}/v2.0".into(), + client_id: "your-application-client-id".into(), + client_secret: None, + scopes: vec!["api://lancedb-api/.default".into()], + flow: OAuthFlow::AzureManagedIdentity { + // Set to Some("your-user-assigned-identity-client-id".into()) + // only for a user-assigned managed identity. + client_id: None, + }, + client_auth_method: None, + resource: None, + audience: None, + refresh_buffer_secs: None, + token_cache: None, }; ``` +`managed_identity_client_id` / `managedIdentityClientId` selects a user-assigned +identity. Omit it for a system-assigned identity. The required `client_id` / +`clientId` field does not select the Azure managed identity. +In Rust, set the `client_id` inside `OAuthFlow::AzureManagedIdentity` to +`Some(...)` for a user-assigned identity, or `None` for a system-assigned +identity. The top-level `OAuthConfig::client_id` is the application client ID. + +For interactive sign-in, configure Authorization Code or Device Code. The +authorization URL or device verification instructions are written to standard +error. Authorization Code also tries to open a browser and listens for the +callback at `http://127.0.0.1:8400/callback` by default. Register that redirect +URI with your identity provider. Public clients can omit `client_secret`; +request a refresh token from your provider (often by including +`offline_access`) if you want to reuse the session. + + +```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. +oauth_config = OAuthConfig( + issuer_url="https://your-issuer.example.com", + client_id="your-public-client-id", + scopes=["openid", "offline_access", "lancedb.read"], + flow=OAuthFlowType.AUTHORIZATION_CODE, + token_cache=TokenCacheOptions(), +) + +db = await lancedb.connect_async( + uri="db://your-database-uri", + region="us-east-1", + host_override="https://your-enterprise-endpoint.com", + oauth_config=oauth_config, +) +``` + +```typescript TypeScript icon="square-js" +import * as lancedb from "@lancedb/lancedb"; +import { OAuthFlowType, type OAuthConfig } from "@lancedb/lancedb"; + +// Use OAuthFlowType.DeviceCode for a CLI without a local browser or callback server. +const oauthConfig: OAuthConfig = { + issuerUrl: "https://your-issuer.example.com", + clientId: "your-public-client-id", + scopes: ["openid", "offline_access", "lancedb.read"], + flow: OAuthFlowType.AuthorizationCode, + tokenCache: {}, +}; + +const db = await lancedb.connect("db://your-database-uri", { + region: "us-east-1", + hostOverride: "https://your-enterprise-endpoint.com", + oauthConfig, +}); +``` + +```rust Rust icon="rust" +use lancedb::remote::{AuthorizationCodeOptions, OAuthConfig, OAuthFlow, TokenCacheOptions}; + +// Use OAuthFlow::DeviceCode 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(), + client_secret: None, + scopes: vec![ + "openid".into(), + "offline_access".into(), + "lancedb.read".into(), + ], + flow: OAuthFlow::AuthorizationCode(AuthorizationCodeOptions::new()), + client_auth_method: None, + resource: None, + audience: None, + refresh_buffer_secs: None, + token_cache: Some(TokenCacheOptions::new()), +}; + +let db = lancedb::connect("db://your-database-uri") + .region("us-east-1") + .host_override("https://your-enterprise-endpoint.com") + .oauth_config(oauth_config.clone()) + .execute() + .await?; +``` + + +With `DEVICE_CODE` / `DeviceCode` / `OAuthFlow::DeviceCode`, the same +configuration and connection calls apply; only the `flow` value changes. + +### Reuse an interactive session {#reuse-an-interactive-session} + +By default, tokens stay in process memory. Set `token_cache` / `tokenCache` +for Authorization Code or Device Code to keep refresh tokens across process +restarts. Only refresh tokens are persisted; access tokens and client secrets +are not written to the cache. Set `cache_dir` / `cacheDir` to choose the +directory, or leave it unset to use the platform cache directory. Your +identity provider must issue a refresh token for a later process to sign in +without prompting again. + +Use `OAuthSession` with the same config to log in before connecting, inspect +whether a refresh token is cached, or remove the local cached credential: + + +```python Python icon="python" +from lancedb.remote import OAuthSession + +session = OAuthSession(oauth_config) +status = await session.login() +print(status.refreshable) +status = await session.status() # Does not contact the provider. +print(status.refreshable) +logout = await session.logout() +print(logout.removed) +``` + +```typescript TypeScript icon="square-js" +import { OAuthSession } from "@lancedb/lancedb"; + +const session = new OAuthSession(oauthConfig); +const status = await session.login(); +console.log(status.refreshable); +const current = await session.status(); // Does not contact the provider. +console.log(current.refreshable); +const logout = await session.logout(); +console.log(logout.removed); +``` + +```rust Rust icon="rust" +use lancedb::remote::OAuthSession; + +let session = OAuthSession::new(oauth_config)?; +let status = session.login().await?; +println!("{}", status.refreshable); +let status = session.status().await?; // Does not contact the provider. +println!("{}", status.refreshable); +let logout = session.logout().await?; +println!("{}", logout.removed); +``` + + +`login()` runs the interactive flow even when a session is cached. `logout()` +removes the local cache entry; it does not revoke the provider's token or end +a browser sign-in. `OAuthSession` requires a persistent cache and supports +only Authorization Code and Device Code. A cache is unused for Client +Credentials and rejected for Azure Managed Identity. + ### Configuration reference {#configuration-reference} -The same configuration is available in both SDKs. Python uses `snake_case` -field names; TypeScript uses `camelCase`. +The same configuration is available in all three SDKs. 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 +`AuthorizationCodeOptions`, and select a managed identity through +`OAuthFlow::AzureManagedIdentity { client_id: ... }`. | Python field / TypeScript field | Required | Description | | --- | --- | --- | | `issuer_url` / `issuerUrl` | Yes | OIDC issuer URL or OAuth authority URL. For Azure, use `https://login.microsoftonline.com/{tenant_id}/v2.0`. | | `client_id` / `clientId` | Yes | Application / client ID registered with your identity provider. | | `scopes` | Yes | List of OAuth scopes to request. For Azure managed identity, provide exactly one scope or resource, for example `["api://your-app-id/.default"]`. | -| `flow` | No | Selects the OAuth flow. Defaults to Client Credentials. | -| `client_secret` / `clientSecret` | Conditional | Required for Client Credentials. Redacted from the config's `repr` (Python) and `Debug` output (TypeScript native binding) so it does not leak into logs. | +| `flow` | Yes in Rust; otherwise no | Selects the OAuth flow. Defaults to Client Credentials in Python and TypeScript; Rust requires an explicit `OAuthFlow`. | +| `client_secret` / `clientSecret` | Conditional | Required for Client Credentials; only required for Authorization Code and Device Code when the provider registers a confidential client. Redacted from the config's `repr` (Python) and `Debug` output (Rust and TypeScript native binding). | +| `client_auth_method` / `clientAuthMethod` | No | Token endpoint authentication: `ClientAuthMethod.NONE` / `ClientAuthMethod.None` for a public client, `ClientAuthMethod.CLIENT_SECRET_BASIC` / `ClientAuthMethod.ClientSecretBasic`, or `ClientAuthMethod.CLIENT_SECRET_POST` / `ClientAuthMethod.ClientSecretPost`. Defaults to Basic when a client secret is set and no client authentication otherwise. The secret methods require `client_secret` / `clientSecret`. Omit for Azure Managed Identity. | +| `redirect_uri` / `redirectUri` | No | Authorization Code loopback callback URI. Defaults to `http://127.0.0.1:{callback_port}/callback`; register it with the provider. | +| `callback_port` / `callbackPort` | No | Authorization Code callback server port (default 8400). If `redirect_uri` / `redirectUri` has an explicit port, the two ports must match. | +| `use_pkce` / `usePkce` | No | Enable S256 PKCE for Authorization Code (default `true`). | | `managed_identity_client_id` / `managedIdentityClientId` | No | Client ID of a user-assigned managed identity. Only used with Azure Managed Identity; omit for system-assigned identities. | +| `resource` | No | RFC 8707 resource indicator, an absolute URI without a fragment. Sent to authorization and token endpoints, including refresh requests. Not supported for Azure Managed Identity. | +| `audience` | No | Provider-specific audience sent to authorization and token endpoints, including refresh requests. Not supported for Azure Managed Identity. | | `refresh_buffer_secs` / `refreshBufferSecs` | No | How many seconds before token expiry to proactively refresh. Defaults to 300. Keep this well below the token TTL: setting it greater than or equal to the TTL forces a refresh on every request. | +| `token_cache` / `tokenCache` | No | Opt in to a persistent refresh-token cache for Authorization Code or Device Code. Use `TokenCacheOptions()` in Python, `{}` in TypeScript, or `Some(TokenCacheOptions::new())` in Rust. Defaults to an in-memory session. | + +`TokenCacheOptions` also accepts `cache_dir` / `cacheDir` to select a cache +directory and `lock_timeout_secs` / `lockTimeoutSecs` to set the wait for a +cross-process refresh lock (default 30 seconds). +In Rust, use the `TokenCacheOptions::cache_dir(...)` and +`TokenCacheOptions::lock_timeout_secs(...)` builder methods. Token endpoint +authentication uses `Some(ClientAuthMethod::None)`, +`Some(ClientAuthMethod::ClientSecretBasic)`, or +`Some(ClientAuthMethod::ClientSecretPost)`; `None` selects the default. Treat the client secret like any other production credential. Load it from a secret manager or environment variable rather than committing it to source -control. Both SDKs deliberately omit the secret from their debug/repr output +control. All three SDKs deliberately omit the secret from their debug/repr output so accidental log lines do not expose the value. -Embedded LanceDB has nothing to authenticate to: your process opens the files +LanceDB Embedded has nothing to authenticate to: your process opens the files directly, and the object store's own credentials are the only gate. diff --git a/docs/web/enterprise/benchmarks.mdx b/docs/web/enterprise/benchmarks.mdx index feec4dfc4..402dfd56a 100644 --- a/docs/web/enterprise/benchmarks.mdx +++ b/docs/web/enterprise/benchmarks.mdx @@ -10,7 +10,7 @@ keywords: ["benchmarks", "performance", "throughput", "latency"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. +[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. diff --git a/docs/web/enterprise/deployment/azure.mdx b/docs/web/enterprise/deployment/azure.mdx deleted file mode 100644 index 702c6a2eb..000000000 --- a/docs/web/enterprise/deployment/azure.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: "Azure deployment guide" -sidebarTitle: "Azure" -description: "Deploying LanceDB Enterprise on Azure." -icon: cloud -keywords: ["azure", "deployment", "aks"] ---- - -Enterprise - -This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. - -The Azure deployment procedure is published with LanceDB Enterprise. See -[Deployment](/enterprise/deployment) for the general shape, and -[contact us](https://www.lancedb.com/contact) to get started. diff --git a/docs/web/enterprise/deployment/index.mdx b/docs/web/enterprise/deployment/index.mdx deleted file mode 100644 index efaa2c786..000000000 --- a/docs/web/enterprise/deployment/index.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: "Deployment guide" -sidebarTitle: "Deployment Models" -description: "Standing up a LanceDB Enterprise deployment." -icon: server -keywords: ["deployment", "install", "cluster", "kubernetes"] ---- - -Enterprise - -This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. - -Deployment is specific to your cloud and account, so the procedure is published -with LanceDB Enterprise. [Contact us](https://www.lancedb.com/contact) to get -started. - -Embedded LanceDB has nothing to deploy: it is a library your process links -against. See [Architecture](/architecture#embedded). diff --git a/docs/web/enterprise/deployment/kubernetes.mdx b/docs/web/enterprise/deployment/kubernetes.mdx new file mode 100644 index 000000000..0133cf065 --- /dev/null +++ b/docs/web/enterprise/deployment/kubernetes.mdx @@ -0,0 +1,17 @@ +--- +title: "Kubernetes deployment guide" +sidebarTitle: "Kubernetes" +description: "Deploying LanceDB Enterprise on Kubernetes." +icon: cloud +keywords: ["kubernetes", "k8s", "aks", "deployment", "helm"] +--- + +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. + +The Kubernetes deployment procedure is published with LanceDB Enterprise. See +[LanceDB Enterprise](/enterprise#deployment) for the general shape, and +[contact us](https://www.lancedb.com/contact) to get started. diff --git a/docs/web/enterprise/distributed-search.mdx b/docs/web/enterprise/distributed-search.mdx new file mode 100644 index 000000000..8b4e9b233 --- /dev/null +++ b/docs/web/enterprise/distributed-search.mdx @@ -0,0 +1,30 @@ +--- +title: "Distributed search" +sidebarTitle: "Distributed search" +description: "How LanceDB Enterprise distributes index execution and table-data reads." +icon: "network-wired" +availability: + embedded: unavailable + enterprise: available +--- + +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. + +## Search interfaces {#search-interfaces} + +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. diff --git a/docs/web/enterprise/index.mdx b/docs/web/enterprise/index.mdx index acf41f6d1..1c3a893a2 100644 --- a/docs/web/enterprise/index.mdx +++ b/docs/web/enterprise/index.mdx @@ -1,7 +1,7 @@ --- title: "LanceDB Enterprise" sidebarTitle: "Overview" -description: "What a deployment adds over embedded LanceDB." +description: "What a deployment adds over LanceDB Embedded." icon: building keywords: ["enterprise", "deployment", "cluster"] --- @@ -10,7 +10,7 @@ keywords: ["enterprise", "deployment", "cluster"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. +[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 @@ -30,4 +30,13 @@ Draft for the Functions release. Add this row to the table above, after SQL: | [Functions](/management/function) | Python running on workers | */} -See [Architecture](/architecture) for the two shapes side by side. +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/security.mdx b/docs/web/enterprise/security.mdx index f462203d4..96846daa0 100644 --- a/docs/web/enterprise/security.mdx +++ b/docs/web/enterprise/security.mdx @@ -10,11 +10,11 @@ keywords: ["compliance", "security", "soc2", "encryption", "audit"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. +[Architecture](/index#architecture) for what differs between the two. 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. -For embedded LanceDB, these are properties of the object store you point it at +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/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index c287d42f5..aecb0acf0 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -1,20 +1,42 @@ --- -title: "Add a computed column" -sidebarTitle: "Computed Columns" +title: "Create a computed column" +sidebarTitle: "Create Computed Column" description: "Declare a column from a SQL expression. Nothing is evaluated until you refresh it." icon: table-columns keywords: ["computed columns", "add_columns", "transforms", "schema"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Both offerings support computed columns. Enterprise requires the deployment to enable them; the embedded library evaluates them in your process. --- -A computed column is declared with an expression and starts with no values. -Declaring it is cheap on any table size, because nothing is evaluated until +import { + PySchemaAddSetup, + TsSchemaAddSetup, + RsSchemaAddSetup, + PyAddColumnsCalculated, + TsAddColumnsCalculated, + RsAddColumnsCalculated, +} from '/snippets/tables.mdx'; + +Lance can write a new column without rewriting the columns already in the +table. That matters most on a table that also holds large images, video or +embeddings, where rewriting everything just to add one small derived field +would be wasteful. See [Lance format](/basics/lance) for the storage model +this relies on. + +A computed column is how LanceDB formalizes that capability for feature +engineering specifically: instead of writing the derived values immediately, +it is declared with an expression and starts with no values. Declaring it is +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. + + ## Add a computed column {#declare} ```python @@ -49,6 +71,69 @@ 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: + +```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 +full behavior, including how to change the setting later. + +An eager `transforms` call looks like this, starting from a small product +table: + + + + {PySchemaAddSetup} + + + + {TsSchemaAddSetup} + + + + {RsSchemaAddSetup} + + + + + + {PyAddColumnsCalculated} + + + + {TsAddColumnsCalculated} + + + + {RsAddColumnsCalculated} + + + +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 +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. + + ## The expression {#expressions} The expression is SQL, evaluated over the row. It can reference any column in @@ -104,12 +189,35 @@ 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. diff --git a/docs/web/feature-engineering/data-evolution.mdx b/docs/web/feature-engineering/data-evolution.mdx deleted file mode 100644 index 37e396b8b..000000000 --- a/docs/web/feature-engineering/data-evolution.mdx +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: "Data evolution" -sidebarTitle: "Data Evolution" -description: "Derive new columns from data already in the table, without rewriting what is already there." -icon: wand-magic-sparkles -keywords: ["data evolution", "derived columns", "add_columns", "zero copy", "feature engineering"] -availability: - oss: available - enterprise: available - summary: >- - Adding columns computed from SQL expressions works in the embedded library - and in LanceDB Enterprise. ---- - -import { - PySchemaAddSetup, - TsSchemaAddSetup as TsSchemaAddSetup, - RsSchemaAddSetup as RsSchemaAddSetup, - PyAddColumnsCalculated as AddColumnsCalculated, - TsAddColumnsCalculated as TsAddColumnsCalculated, - RsAddColumnsCalculated as RsAddColumnsCalculated, - PyAddFeatureColumnsSql as AddFeatureColumnsSql, - TsAddFeatureColumnsSql as TsAddFeatureColumnsSql, - RsAddFeatureColumnsSql as RsAddFeatureColumnsSql, -} from '/snippets/tables.mdx'; - -Add derived columns to calculate features from data already in a table. -For example, compute a product score from existing fields without reading -and rewriting the table in your application. - -Lance can write the new columns without rewriting the existing columns. -This is useful when the table also contains large images, video or embeddings. -See [Lance format](/basics/lance) for the storage model. - - -In SQL, on an Enterprise cluster that enables computed columns, this is [`ALTER TABLE ... ADD COLUMN ... AS`](/sql/ddl/table#computed-column). - - -## Set up the example table {#set-up-the-example-table} - -The examples use `db`, a connection opened as in -[Connect to LanceDB](/basics/connect), and create a small product table in it: - - - - {PySchemaAddSetup} - - - - {TsSchemaAddSetup} - - - - {RsSchemaAddSetup} - - - -## Add derived columns {#add-derived-columns} - -You can add new columns that are derived from existing data using SQL expressions. -For feature engineering on large existing tables, group related derived features into -one `add_columns` operation instead of running many separate writes. This creates one -new table version for the schema change and computes the new columns from the existing -rows, which avoids growing the table's version history with many small updates. - - - - {AddColumnsCalculated} - - - - {TsAddColumnsCalculated} - - - - {RsAddColumnsCalculated} - - - -The same call can add multiple derived columns at once. For example, if you are -building several lightweight features from existing product fields, pass all of the -new column expressions together: - - - - {AddFeatureColumnsSql} - - - - {TsAddFeatureColumnsSql} - - - - {RsAddFeatureColumnsSql} - - - - -LanceDB `add_columns` does not currently accept Python callables, batch UDFs, or -PyArrow `RecordBatch` iterators for populating new columns. 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. - - -## When SQL is not enough {#beyond-sql} - -The expressions above are evaluated once, as part of the call. For other workflows: - -- A [computed column](/feature-engineering/add-computed-column) declares the - expression and leaves the column empty, so you choose when the work happens. - Use it when you want to schedule the computation separately. -- On LanceDB Enterprise, [Geneva](/geneva) fills a column with Python, for - values SQL cannot express: an embedding, a model call, an image decode. - -{/* -Draft for the Functions release. Replaces the Geneva item in the list above: -- A [function](/management/function) fills a column with Python, for values SQL - cannot express -- an embedding, a model call, an image decode. -*/} - -A deployment has to enable computed columns before you use them. -{/* Draft for the Functions release: Functions need enabling there too. */} - -## Related guides {#next} - - - - Declare now, fill later. - - - Change the table's shape instead of its contents. - - diff --git a/docs/web/feature-engineering/index.mdx b/docs/web/feature-engineering/index.mdx index 8f0253444..6807998ec 100644 --- a/docs/web/feature-engineering/index.mdx +++ b/docs/web/feature-engineering/index.mdx @@ -24,7 +24,7 @@ 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](/sql/dml/refresh) to fill it. +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. ## Computed columns and materialized views {#the-shape} @@ -36,8 +36,8 @@ refresh costs: | | Computed column | Materialized view | | --- | --- | --- | | Declaring or creating it | records the expression; no values are written | runs the query and stores its rows, unless created empty | -| A refresh | fills rows with no value and recomputes rows whose inputs changed | applies source changes or rebuilds the view, depending on the query and SDK version | -| A refresh when nothing changed | fills nothing | can be a no-op when incremental refresh is supported | +| A refresh | fills rows with no value and recomputes rows whose inputs changed | rebuilds the view completely from its source query | +| A refresh when nothing changed | fills nothing | still rebuilds the view and commits a new version | | In LanceDB Enterprise | runs as a [job](/basics/jobs) | runs as a server-side materialization job | ### Computed columns fill incrementally {#incremental} @@ -65,21 +65,19 @@ up-to-date features. A [materialized view](/feature-engineering/materialized-views) has no separate declaration step: creating one runs its query and stores the result, so the view -is ready to read. A refresh updates those stored results. Python SDK 0.40.0 can apply -changes incrementally for supported queries; other queries require a full rebuild. -See [refresh behavior](/feature-engineering/materialized-views#incremental) for -version-specific details. +is ready to read. A refresh rebuilds the stored result completely from the +source query; see [Refresh a materialized view](/feature-engineering/refresh-materialized-view) +for the full behavior, including automatic refresh. -Enterprise runs materialization on remote compute. Use the SDK and refresh -options supported by your server version; see -[Enterprise refreshes](/feature-engineering/materialized-views#availability). +Enterprise runs materialization on remote compute, as a server-side job. ## Choose a feature engineering workflow {#which-one} | | What it produces | Filled by | Available | | --- | --- | --- | --- | -| [Computed column](/feature-engineering/add-computed-column) | a new column on an existing table | a SQL expression | OSS and Enterprise | -| [Materialized view](/feature-engineering/materialized-views) | a new table derived by a query | a refresh | OSS and Enterprise | +| [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 | +| [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 | {/* @@ -88,6 +86,11 @@ Draft for the Functions release. Replace the Geneva row of the table above with: | [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 +or a materialized view, when the query is cheap enough to simply re-run on +every read. + **Computed columns** are the common case: a column declared with a SQL expression, filled by [a refresh](/feature-engineering/refresh-column). @@ -147,20 +150,26 @@ 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 failed run was kept depends on where it ran (see -[Refresh a column](/feature-engineering/refresh-column#failures)), and a retry +[Refresh a computed column](/feature-engineering/refresh-column#failures)), and a retry can recompute values that were already written, so do not count on it costing only the rows that did not complete. ## Related guides {#next} - + + A saved query, with no storage or refresh of its own. + + Declare a column from a SQL expression. - + Fill the rows that lack values, locally or as a job. - + + Store a query's result as a table. + + Bring a derived table up to date with its source. {/* diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index ffe4fc959..86a3667f3 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -1,115 +1,95 @@ --- -title: "Refresh a materialized view" -sidebarTitle: "Materialized View Refresh" -description: "Create a materialized view and refresh it when the source data changes." +title: "Create a materialized view" +sidebarTitle: "Create Materialized View" +description: "Store the result of a query as a table, ready to query, index and search." icon: table -keywords: ["materialized view", "create_materialized_view", "refresh", "full refresh"] +keywords: ["materialized view", "create_materialized_view"] availability: - oss: available + embedded: unavailable enterprise: available - summary: >- - Both offerings support materialized views. OSS refreshes run in your process; Enterprise runs the work on remote compute. See [Enterprise refreshes](#availability) for server compatibility requirements. --- -import { - PyMaterializedViewCreate as MaterializedViewCreate, - PyMaterializedViewRefresh as MaterializedViewRefresh, -} from '/snippets/materialized_view.mdx'; - A materialized view stores the result of a query as a table. Use it to keep a -filtered or transformed dataset that you can query, index and search repeatedly. -Refresh the view after its source data changes. +filtered or transformed dataset that you can query, index and search +repeatedly, instead of recomputing the query every time you read it. -In SQL this is [`REFRESH MATERIALIZED VIEW`](/sql/refresh#refresh-materialized-view). +In SQL this is [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view#create). -## Create and refresh {#create-and-refresh} +## Create a view {#create} - -{MaterializedViewCreate} - + +```python Python icon="python" +view = db.create_materialized_view( + "frames_captioned", + source="frames", + select=["frame_id", "video_id", "ts", "caption"], + where="selected = true", +) +``` + +```typescript TypeScript icon="square-js" +const view = await db.createMaterializedView("frames_captioned", "frames", { + select: ["frame_id", "video_id", "ts", "caption"], + 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. Creating the view computes its rows, so it is ready to read. Pass -`with_no_data=True` to create it empty instead. Later changes to the source -reach the view through a refresh: +`with_no_data=True` to create it empty instead; a later +[refresh](/feature-engineering/refresh-materialized-view) populates it. - -{MaterializedViewRefresh} - +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. -The example works with Python SDK 0.40.0. It creates the source with stable -row IDs, which that release requires for ordinary materialized-view sources. +## Automatic refresh at creation {#auto-refresh} -`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; `limit` caps the view. +Pass `auto_refresh_enabled` and `auto_refresh_interval_seconds` to schedule +refreshes instead of calling +[`refresh`](/feature-engineering/refresh-materialized-view) yourself: -## Prepare the source table {#stable-row-ids} +```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, +) +``` -In Python SDK 0.40.0, create the source with -`storage_options={"new_table_enable_stable_row_ids": "true"}`, as the example -above does. Stable row IDs let the view track source rows across updates and -compaction. Set this option when creating the table; it cannot be added later. - -A source with a MemWAL write spec or retained, uncompacted write-ahead-log -rows is not accepted by the local materialized-view implementation. - -## Refresh behavior {#incremental} - -With Python SDK 0.40.0, a refresh applies source changes incrementally when the -query supports it, and rebuilds the view otherwise. In the example, adding Bea -writes one new view row. Refreshing again without source changes writes none. -Use `refresh(full=True)` to force a rebuild. - -`rows_written` counts rows written by that refresh, not all rows in the view. -Use `view.table.count_rows()` to get the total. Pass `source_version=N` to -refresh against a particular source version instead of the latest. - - -Refresh behavior has changed between SDK versions. The earlier 0.40.0b13 -development build rebuilt every local view on refresh and did not accept -`full`; 0.39.0 created views empty. Use the reference for your installed SDK -when maintaining an existing pipeline. - - -## Enterprise refreshes {#availability} - -Enterprise - -Enterprise runs materialized-view creation and refresh on remote compute. -For SQL, see [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view) and -[`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh#refresh-materialized-view). - -Use an SDK version supported by your Enterprise deployment. Materialized-view -APIs and stored definitions have changed across releases; a local SDK example -alone does not establish compatibility with an older server. Before upgrading -an existing pipeline, confirm the supported refresh options and whether its -views need to be recreated with your administrator. - -Stable row IDs and feature configuration for Enterprise sources are managed on -the server. The source-table storage option in the local example does not -configure the Enterprise deployment, and Python SDK 0.40.0's `create_table` on a -`db://` connection does not accept `storage_options`: leave it out, and confirm -with your administrator that the deployment gives new tables stable row IDs. - -`list_materialized_views` requests the server's view listing. On a local -database it reads table schemas to find views. +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. ## 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()`. +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()`. -An existing view is reopened with `db.open_materialized_view(name)`. +An existing view is reopened with `db.open_materialized_view(name)`. Creation, +refresh and drop also have async, job-returning SDK methods; see +[Materialized view](/management/materialized-view#manage). ## Related guides {#next} - - Derive a column instead of a whole table. + + Bring the view up to date with its source. Inspect the table history and read a particular version. diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index f4550ed24..ba3934f1e 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -1,20 +1,25 @@ --- -title: "Refresh a column" -sidebarTitle: "Column Refresh" +title: "Refresh a computed column" +sidebarTitle: "Refresh Computed Column" description: "Populate a computed column and update it when its inputs change." icon: arrows-rotate keywords: ["refresh_column", "backfill", "job", "idempotent", "REFRESH COLUMN"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Both offerings support column refresh. The embedded library runs it in your process; Enterprise runs it as a server job that must be enabled for your Enterprise cluster. --- Refresh a [computed column](/feature-engineering/add-computed-column) to fill 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. + + ```python Python icon="python" table.refresh_column("doubled") @@ -57,6 +62,71 @@ That is what makes the call idempotent and safe to retry. However, unlike a spreadsheet formula, nothing is recomputed until you refresh, so a derived 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. + ## Refreshing part of a table {#partial} Enterprise In SQL a refresh can be scoped to a @@ -141,7 +211,7 @@ symptoms, which rarely name their cause. Waiting on, inspecting, and cancelling server-side work. - + The same idea, for a whole derived table. diff --git a/docs/web/feature-engineering/refresh-materialized-view.mdx b/docs/web/feature-engineering/refresh-materialized-view.mdx new file mode 100644 index 000000000..05ebff109 --- /dev/null +++ b/docs/web/feature-engineering/refresh-materialized-view.mdx @@ -0,0 +1,88 @@ +--- +title: "Refresh a materialized view" +sidebarTitle: "Refresh Materialized View" +description: "Bring a materialized view up to date after its source data changes." +icon: arrows-rotate +keywords: ["materialized view", "refresh", "auto_refresh_enabled", "auto_refresh_interval_seconds"] +availability: + embedded: unavailable + enterprise: available +--- + +Refresh a [materialized view](/feature-engineering/materialized-views) to +bring its stored rows up to date after the source table changes. + + +In SQL this is [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh-materialized-view). + + +## Refresh a view {#refresh} + +```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. + +The result reports what the refresh did: + +```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 +``` + +Pass `source_version=N` to refresh against a particular source version +instead of the latest: + +```python +view.refresh(source_version=12) +``` + +Use `view.table.count_rows()` for the view's row count at any time; it +always matches `rows_written` from the most recent refresh. + +## 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. + +## When a refresh fails {#failures} + +A refresh replaces the view's stored rows in one commit, so a failure leaves +the view as it was after its last successful refresh. Fix the cause and +refresh again. + +## Related guides {#next} + + + + Define the query a view stores. + + + The same idea, for a single derived column. + + diff --git a/docs/web/feature-engineering/view.mdx b/docs/web/feature-engineering/view.mdx new file mode 100644 index 000000000..e61b2118a --- /dev/null +++ b/docs/web/feature-engineering/view.mdx @@ -0,0 +1,73 @@ +--- +title: "Create a view" +sidebarTitle: "Create View" +description: "Define a derived dataset as a saved query, with no storage or refresh of its own." +icon: eye +keywords: ["view", "create view", "feature engineering", "saved query"] +availability: + embedded: unavailable + enterprise: available +--- + +A view is the lightest way to derive a feature-engineered dataset: it stores +a **query**, not rows, so there is nothing to refresh and nothing that can +fall out of date. Reach for one before +[a computed column](/feature-engineering/add-computed-column) or +[a materialized view](/feature-engineering/materialized-views) when the +underlying query is cheap enough to simply re-run on every read. + +## Define a view {#create} + +A view over a products table, selecting and deriving a few columns: + +```sql +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, +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 +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 +reason about, unlike a materialized view between refreshes. A predicate +applied when reading the view composes with the query inside it, rather than +filtering the view's output afterward, so a selective filter does not pay +for rows the view would have produced and then discarded. + +## When to use a view instead {#choosing} + +| | View | Computed column / materialized view | +| --- | --- | --- | +| Stores | the query | derived values | +| Freshness | always current | as of the last refresh | +| Read cost | the full query, every read | a column or table scan | +| Write cost | none | a refresh | + +Reach for a view when the query is cheap, or when reading a stale value would +be wrong for the workload. Reach for a computed column or a materialized view +when the query is expensive and the data changes less often than it is read. +See [View](/sql/ddl/view#choosing) for the full SQL reference comparison, +including the separate privileges each one needs. + +## What to read next {#next} + + + + CREATE VIEW, DROP VIEW, and listing views alongside tables. + + + The stored-rows counterpart, and when a refresh is worth paying for. + + diff --git a/docs/web/governance/authorization.mdx b/docs/web/governance/authorization.mdx index dc5b6fd26..c7831590b 100644 --- a/docs/web/governance/authorization.mdx +++ b/docs/web/governance/authorization.mdx @@ -5,10 +5,8 @@ description: "Who may do what: privileges granted on catalog objects to principa icon: shield-halved keywords: ["authorization", "authz", "privileges", "rbac", "access control"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports catalog privileges when its administrator configures enforcement. Embedded LanceDB has no catalog authorization layer: access is whatever the object store allows. --- [Authentication](/enterprise/authentication) establishes who is calling. diff --git a/docs/web/index.mdx b/docs/web/index.mdx index 75044ad0d..21c9134af 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -10,115 +10,194 @@ keywords: ["multimodal lakehouse", "training", "feature engineering", "search", one data layer for curation, feature engineering, search and retrieval, and model training. It is built on top of [Lance](/basics/lance), an open-source lakehouse format designed for multimodal AI data. -Move from data exploration to model training on one, unified platform without needing to manage a +Move from data exploration to model training on one unified platform without needing to manage a fragmented stack of storage, feature, retrieval, and training systems. -## Build better models, faster {#build-better-models-faster} +## Train on the right data faster {#train-on-the-right-data-faster} -Training data and experimentation slow down when raw data, metadata, embeddings, features, and governance +Search, curate, and train at petabyte scale, with all your multimodal data in one table. + +Preparing training data and running experiments slow down when raw data, metadata, embeddings, features, and governance artifacts live in separate systems. LanceDB keeps them together in one versioned multimodal table, so AI teams spend less time stitching infrastructure together and more time improving datasets, testing features, and keeping GPUs fed. -![Training data lifecycle: Curation, Feature Engineering, Search and Retrieval, Training](/static/assets/images/overview/training-data-lifecycle.svg) +## 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. +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. + + + 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 + run back to the exact data it used. + + + Define the [computed columns](/feature-engineering/add-computed-column) and + [materialized views](/feature-engineering/materialized-views) your experiment needs, such as extracted features + or embeddings, and refresh them as your data changes. On LanceDB Enterprise, column refreshes run as background + jobs on the cluster instead of in your code. + + + Keep GPUs fed. [`StreamingDataset`](/training/data-loading) streams multimodal training data into PyTorch with + globally shuffled, deterministic batches, combining fast random access with high-throughput scans. + + Use the same table to curate training data, add derived features, retrieve examples, and feed training jobs that rely on expensive GPUs. Training workloads can sample, shuffle, and scan projected columns from local storage or object storage, then assemble -GPU-ready batches from a tagged dataset version. +GPU-ready batches from a tagged dataset version. Training pipelines need curation, derived features, reproducible +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. -For a deeper look at how this works in training pipelines, start with [Why LanceDB for training](/training/why-lancedb). +## Architecture {#architecture} -## LanceDB suite {#lancedb-suite} +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. -The LanceDB suite includes LanceDB OSS, an open-source embedded retrieval library, and LanceDB Enterprise, -a multimodal lakehouse platform for the full AI data lifecycle. -OSS is easy to set up on a local machine for search and regular-scale workflows. LanceDB Enterprise is built -for teams that need scale without building bespoke infrastructure for curation, -feature engineering, search and retrieval, and efficient training data access. +![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) -![LanceDB suite: OSS search and Enterprise multimodal lakehouse on Lance format](/static/assets/images/overview/lancedb-suite.svg) +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. -## Why teams use LanceDB {#why-teams-use-lancedb} +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. - - - Store images, video, audio, text, annotations, embeddings, and model-generated features together in one schema-enforced table. - The same table can support dataset curation, feature backfills, experiment splits, retrieval, and training. - - - Training workloads mix fast random access with high-throughput sequential scans. LanceDB is designed for both, so - teams can shuffle data into GPU-ready batches more efficiently, improve input throughput, and iterate on experiments faster. - - - Whether the end user is a human or an agent, LanceDB powers production retrieval workloads such as semantic search, - hybrid search, RAG, agent memory, and recommendation systems. Retrieval runs against the same LanceDB tables used - for curation, feature engineering, and training workflows. - - +## 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) | ❌ | ✅ | + +## Projects using LanceDB {#projects-using-lancedb} + +### Training {#training} + +- [stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) -- a platform for reproducible world-model + research built on a LanceDB data layer, reporting 3-4x faster data loading on Push-T versus HDF5 / MP4 at a + 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 datasets with faster loading across robotics datasets. + +### Agentic applications {#agentic-applications} + +- [OpenClaw LanceDB Plugin](https://docs.openclaw.ai/plugins/memory-lancedb) -- stores an agent's long-term memory + in LanceDB, automatically recalling relevant memories before a model turn and capturing new facts afterward. +- [Cognee](https://github.com/topoteretes/cognee) -- an open-source AI memory platform that gives agents persistent + memory across sessions, using LanceDB as one of its vector store backends. +- [CrewAI](https://github.com/crewAIInc/crewAI) -- a multi-agent framework that + [rebuilt its agent memory on LanceDB](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb). + +Across these projects, LanceDB and Lance provide the multimodal data layer that keeps raw observations, annotations, +features, and training or memory access patterns in one format instead of scattering them across task-specific +stores. ## Start with your workload {#start-with-your-workload} - - Learn why LanceDB works well as the data layer for training workloads. - - - Use LanceDB tables and permutations for projected, shuffled, random-access training reads. - - - Explore Lance-formatted multimodal datasets with raw bytes, metadata, embeddings, and indices. + + Create tables, append records, and update or delete rows as your data changes. Use vector search, full-text search, hybrid search, reranking, filtering, and SQL. + + Profile, sample, chunk, join, and deduplicate records before training on them. + + + Derive computed columns and materialized views without moving data elsewhere. + + + Use LanceDB tables and permutations for projected, shuffled, random-access training reads. + + + Create, list, and drop tables, namespaces, and views from Python, TypeScript, or SQL. + -## From local development to production scale {#from-local-development-to-production-scale} - -LanceDB OSS and LanceDB Enterprise share the same Lance format and table model. Start locally with the embedded OSS -library, 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 OSS {#1-lancedb-oss} -The fastest way to get started is the open-source embedded library, with client SDKs in Python, TypeScript -and Rust. Run it locally in just a few steps, which lets you explore datasets, curate data, and run search and retrieval workloads -for agents. Start here: - - - - Get started with LanceDB in minutes. - - - Create tables, evolve schemas, version data, and modify rows in LanceDB. - - - -### 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. This eliminates the need for teams to build bespoke infrastructure to manage large multimodal datasets. -To set up LanceDB Enterprise in your organization, -[reach out to us](https://www.lancedb.com/contact). - - -**Built with scale, performance, and security in mind.** - -LanceDB Enterprise is designed for very large-scale, high-performance, distributed workloads in -private deployments, and can operate under strict [security requirements](/enterprise/security). - - - - Get started with LanceDB in minutes, including Enterprise `db://` connections. - diff --git a/docs/web/indexing/fts-index.mdx b/docs/web/indexing/fts-index.mdx index 832b67315..ac3ff36e5 100644 --- a/docs/web/indexing/fts-index.mdx +++ b/docs/web/indexing/fts-index.mdx @@ -4,17 +4,13 @@ sidebarTitle: "FTS Index" description: "Create and tune BM25-based full-text search indexes in LanceDB." icon: "book" availability: - oss: available + embedded: available enterprise: available - summary: >- - Full-text indexes are built in the embedded library and in LanceDB Enterprise. - The embedded library builds the index before the call returns; a - deployment builds it in the background. --- import { PyFtsIndexAsync as FtsIndexAsync, PyFtsIndexCreate as FtsIndexCreate, PyFtsIndexNested as FtsIndexNested, PyFtsIndexWait as FtsIndexWait } from '/snippets/indexing.mdx'; LanceDB provides performant full-text search based on BM25, allowing you to incorporate keyword-based search in your retrieval solutions. This page shows -examples on how to create and configure FTS indexes in LanceDB OSS and Enterprise, using the synchronous and asynchronous APIs. +examples on how to create and configure FTS indexes in LanceDB Embedded and LanceDB Enterprise, using the synchronous and asynchronous APIs. In LanceDB Enterprise, `create_fts_index` API returns immediately, but index building happens asynchronously. @@ -99,7 +95,7 @@ await async_table.create_index("payload.text", config=FTS(with_position=True)) | `stem` | bool | `True` | Apply stemming (`running` → `run`) | | `remove_stop_words` | bool | `True` | Drop common stop words | | `ascii_folding` | bool | `True` | Normalize accented characters | -| `custom_stop_words` | list[str] | `None` | Extra stop words to drop in addition to the language defaults. Requires `remove_stop_words=True`. | +| `custom_stop_words` | list[str] | `None` | Explicit stop-word list that replaces the built-in list. Requires `remove_stop_words=True`. | | `ngram_min_length` | int | `3` | Minimum n-gram length. Applies only when `base_tokenizer="ngram"`. | | `ngram_max_length` | int | `3` | Maximum n-gram length. Applies only when `base_tokenizer="ngram"`. | | `prefix_only` | bool | `False` | Index only prefix n-grams rather than all substrings. Applies only when `base_tokenizer="ngram"`. | @@ -123,7 +119,11 @@ await async_table.create_index("payload.text", config=FTS(with_position=True)) Model-backed tokenizers such as `jieba/default`, `lindera/ipadic`, and `lindera/ko-dic` 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 another model root. For example, `jieba/default` is resolved under `/jieba/default/...`. For a table in LanceDB Enterprise, the files must be present where the deployment builds and queries the index, so ask its administrator whether they are installed. -`language` is used by token filters, not by the base tokenizer. Stemming supports Arabic, Danish, Dutch, English, Finnish, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil, and Turkish. Built-in stop-word removal supports Danish, Dutch, English, Finnish, French, German, Hungarian, Italian, Norwegian, Portuguese, Russian, Spanish, and Swedish. For other stemming languages, set `remove_stop_words=False` or pass `custom_stop_words`. +`language` is used by token filters, not by the base tokenizer. Stemming and language-specific stop-word removal support Arabic, Danish, Dutch, English, Finnish, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil, and Turkish. The ICU tokenizer uses a combined multilingual stop-word list. An explicit `custom_stop_words` list replaces the built-in list for either tokenizer. + + +Lance `15.0.0-beta.1` revises the built-in stop-word lists, including the multilingual list used by ICU. Existing index metadata records tokenizer settings, but does not freeze these built-in lists. Rebuild affected FTS indexes with the same configuration before serving queries with the updated SDK, so stored terms and query tokens use the same lists. Indexes with stop-word removal disabled or an explicit `custom_stop_words` list are unaffected by this change. + ### Posting block size {#posting-block-size} diff --git a/docs/web/indexing/index.mdx b/docs/web/indexing/index.mdx index 78844527f..e408acb78 100644 --- a/docs/web/indexing/index.mdx +++ b/docs/web/indexing/index.mdx @@ -4,11 +4,8 @@ sidebarTitle: "Overview" description: "Optimize search performance with LanceDB using vector indexes, full-text search, scalar indexes, and more." icon: "list" availability: - oss: available + embedded: available enterprise: available - summary: >- - Indexes are built in the embedded library and in LanceDB Enterprise. Enterprise builds them in the background, and builds fewer vector index types than the - embedded library. --- Indexes speed up searches and filters by organizing data for specific query diff --git a/docs/web/indexing/reindexing.mdx b/docs/web/indexing/reindexing.mdx index 9df3235db..68d0f5d73 100644 --- a/docs/web/indexing/reindexing.mdx +++ b/docs/web/indexing/reindexing.mdx @@ -5,13 +5,8 @@ description: "Learn how to keep your indexes up-to-date in LanceDB using increme icon: "refresh" keywords: ["reindexing", "re-index", "incremental indexing", "reindex"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Indexes are kept up to date in the embedded library and in LanceDB Enterprise. In - the embedded library you add new rows to them with `optimize()`; a - deployment does it in the background, and `optimize()` is not available - there. --- import { @@ -65,7 +60,7 @@ LanceDB Enterprise supports incremental reindexing through an automated backgrou 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 OSS, you must manually manage the reindexing cadence based on your data growth and performance needs. +In LanceDB Embedded, you must manually manage the reindexing cadence based on your data growth and performance needs. ## Disk utilization {#disk-utilization} @@ -73,7 +68,7 @@ Compaction by itself does not immediately free disk space, and can temporarily i 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 OSS, use a shorter retention window: +If you need to reclaim space more aggressively in LanceDB Embedded, use a shorter retention window: ```python Python icon=Python from datetime import timedelta @@ -109,11 +104,11 @@ GPU acceleration changes how the vector index is built, not the lifecycle after 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 OSS {#gpu-manual-gpu-indexing-in-lancedb-oss} +### 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 OSS. +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. diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx index 9f1f9a176..d99bb6003 100644 --- a/docs/web/indexing/scalar-index.mdx +++ b/docs/web/indexing/scalar-index.mdx @@ -4,12 +4,8 @@ sidebarTitle: "Scalar Index" description: "Learn how to use scalar indexes in LanceDB for efficient metadata filtering and query optimization." icon: "tree" availability: - oss: available + embedded: available enterprise: available - summary: >- - Scalar indexes are built in the embedded library and in LanceDB Enterprise. A - deployment builds them in the background and keeps most of them up to date - itself; in the embedded library you update them with `optimize()`. --- import { diff --git a/docs/web/indexing/vector-index.mdx b/docs/web/indexing/vector-index.mdx index 2742a992f..3e2b7d6f0 100644 --- a/docs/web/indexing/vector-index.mdx +++ b/docs/web/indexing/vector-index.mdx @@ -4,13 +4,8 @@ sidebarTitle: "Vector Index" description: "Build and manage LanceDB vector indexes." icon: "arrow-up-right-dots" availability: - oss: available + embedded: available enterprise: available - summary: >- - Vector indexes are built in the embedded library and in LanceDB Enterprise. The - embedded library builds an index before `create_index()` returns; a - deployment builds it in the background, keeps it up to date, and builds - only `IVF_FLAT`, `IVF_PQ`, `IVF_RQ` and `IVF_HNSW_SQ`. --- import { @@ -58,7 +53,7 @@ Lance with `index_type`. | If your priority is... | Use this index | Why | Approx. compression ratio | Python config class | | :--- | :--- | :--- | :--- | :--- | -| Maximum compression | `IVF_RQ` | IVF indexing with RaBitQ quantization | Around `1/32` of raw size | `IvfRq` | +| 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` | | 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` | @@ -159,7 +154,7 @@ Learn how to configure, build, and search LanceDB vector indexes, including buil The `distance_type` can be specified at search time in addition to build time. If you do this, set it to the same value used to build the vector index. If the search metric does not match the index metric, LanceDB cannot use the index and falls -back to a costly flat search. On LanceDB Cloud, the brute-force KNN safety limit +back to a costly flat search. On LanceDB Cloud (legacy hosted service), the brute-force KNN safety limit can reject that search on a large table instead of executing it. An Enterprise deployment applies the same limit only when it is configured to. @@ -279,7 +274,7 @@ In LanceDB Enterprise, vector indexes are managed **automatically**. The system - GPU-based `IVF_PQ` builds are available on request. [Contact support](/deployment/support) to enable them for your deployment. Build time depends on dataset size, dimensions and GPU resources. Open-Source - LanceDB OSS users can manually create vector indexes by calling `table.create_index()`. + LanceDB Embedded users can manually create vector indexes by calling `table.create_index()`. See the above sections for guidance on manually tuning index parameters as data changes. @@ -290,7 +285,7 @@ In the embedded library the index is built before `create_index()` returns. -Rows appended after an initial index build remain outside the index until refreshed manually (OSS) or automatically (Enterprise). Normal +Rows appended after an initial index build remain outside the index until refreshed manually (Embedded) or automatically (Enterprise). Normal search still checks those unindexed rows with a slower fallback path; `fast_search()` skips that fallback and searches only indexed rows. @@ -330,7 +325,7 @@ Each entry returned by `list_indices()` also carries detailed per-index metadata -These fields are populated for local tables. In LanceDB Enterprise, `list_indices()` returns them except `num_unindexed_rows`; use `index_stats()` for index coverage. +These fields are populated for LanceDB Embedded tables. In LanceDB Enterprise, `list_indices()` returns them except `num_unindexed_rows`; use `index_stats()` for index coverage. #### Custom Index Names @@ -377,22 +372,27 @@ which has been compressed to $4$ chunks $\times 8$-bit integers $= 32$ bits of q RaBitQ is an advanced quantization technique that outperforms PQ in several ways. It needs no codebook to train, estimates distances very quickly at query-time, -and crucially, quantizes each vector in (with some small overhead) just **one bit per dimension!** +and can quantize each vector in (with some small overhead) as little as **one bit per dimension!** In practice, RaBitQ compresses a $1024$-dimensional `float32` vector into just a few thousand bits, while maintaining good recall. The inner workings of RaBitQ quantization are rather mathematically dense. It generates a quantization codebook by applying a uniformly random, approximately distance-preserving orthogonal transformation of the vertices of the $d$-dimensional hypercube, where $d$ is the dimensionality of the dataset. We defer the details, and an elegant theoretical error bound, to [the original paper.](https://arxiv.org/pdf/2405.12497) -##### Using RaBitQ -Use RaBitQ quantization by selecting quantized index types ending in the suffix `RQ`. For example, call `create_index` with `index_type="IVF_RQ"`. +##### Using RaBitQ {#using-rabitq} +Use RaBitQ quantization by selecting quantized index types ending in the suffix `RQ`. For example, import `IvfRq` from `lancedb.index` and call `table.create_index("vector", config=IvfRq())`. Note that when using `IVF_RQ`, the dimension of the dataset must be a multiple of `8`. `num_bits` determines how many bits are used to quantize each dimension. -`1` is the standard RaBitQ setting. Increase to `2`, `4`, or `8` bits to achieve better recall for additional storage and query-time compute. +By default, Python, Rust, and Node leave this unset and inherit Lance's default, currently `5` bits. +Higher values improve recall at the cost of additional storage and query-time compute. +To retain the previous one-bit default and maximum compression, explicitly set `num_bits=1` (for example, `IvfRq(num_bits=1)` in Python). +Five-bit quantized vector codes use roughly five times the storage of one-bit codes; total index size also includes other overhead. -RaBitQ-quantized indexes computed with `num_bits >= 2` use a newer on-disk layout, and cannot be read by some older LanceDB versions. +RaBitQ-quantized indexes computed with `num_bits >= 2` use a newer on-disk layout and cannot be read by some older LanceDB versions. +The new five-bit default therefore affects reader compatibility as well as index size. +Upgrade readers to versions that support multi-bit IVF_RQ before creating indexes with the default settings, or explicitly set `num_bits=1` when sharing indexes with readers that support only one-bit IVF_RQ. See this [blog post](https://lancedb.com/blog/feature-rabitq-quantization/) for further discussion and benchmarking of LanceDB's RaBitQ implementation. @@ -410,7 +410,7 @@ among all integral multiples $\{j \times 10^5: -128 \leq j \leq 127 \}$. | Parameter | Description | | :--- | :--- | -| `num_bits` | Bits per dimension for quantization. Only applies to `IVF_PQ`/`IVF_HNSW_PQ` (default `8`) and `IVF_RQ` (default `1`, RaBitQ); not used by `IVF_FLAT`/`IVF_SQ`/`IVF_HNSW_FLAT`/`IVF_HNSW_SQ`. Higher values improve accuracy at the cost of additional storage. | +| `num_bits` | Bits per dimension for quantization. Only applies to `IVF_PQ`/`IVF_HNSW_PQ` (default `8`) and `IVF_RQ` (`IvfRq()` inherits Lance's default, currently `5`, RaBitQ); not used by `IVF_FLAT`/`IVF_SQ`/`IVF_HNSW_FLAT`/`IVF_HNSW_SQ`. Higher values improve accuracy at the cost of additional storage. | `max_iterations` and `sample_rate` also affect quantizer training, but since they apply to every IVF/HNSW index type (not just quantized ones), they're documented as general [Build-time Parameters](/indexing/vector-index#build-time-parameters) instead. All three are passed as keyword arguments to `create_index`, alongside `index_type`: diff --git a/docs/web/ingestion/create-table.mdx b/docs/web/ingestion/create-table.mdx index 7d4363be7..ec13c02b7 100644 --- a/docs/web/ingestion/create-table.mdx +++ b/docs/web/ingestion/create-table.mdx @@ -5,10 +5,8 @@ description: "Create a table from records or a schema and choose input formats." icon: table keywords: ["create table", "ingest", "arrow", "pandas", "polars", "pydantic", "schema"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Create and open tables in OSS and Enterprise. --- import { @@ -146,11 +144,14 @@ You can define a custom Arrow schema for the table. This is useful when you want An explicit schema also determines which columns accept missing values (`null`). If later writes omit a non-nullable column, or provide actual nulls for it, ingestion fails; nullable columns can be omitted or written with null values. Without an explicit schema, Python infers list-like vector -values as fixed-size `float32` vector fields from the observed dimension. +values as fixed-size `float32` vector fields from the observed dimension. For images, audio, video, or +other binary columns whose payloads should load on demand, declare a [blob column](/management/table#multimodal-blob-v2) in the schema. -For Python ingest, malformed vector values fail by default. If you expect occasional wrong-length, -null, or NaN vectors, choose an `on_bad_vectors` policy: `"drop"` removes those rows, `"fill"` writes -`fill_value`, and `"null"` writes nulls. +For Python ingestion, malformed vectors fail by default (`on_bad_vectors="error"`). This includes +vectors with incorrect sizes, NaNs, or null components, including pandas NaNs converted to Arrow +nulls. Use `"drop"` to remove affected rows, or `"null"` to replace affected vectors with nulls. +Use `"fill"` to replace NaN or null components with `fill_value` while preserving valid components. +This also pads short vectors with `fill_value` and truncates long vectors to the expected dimension. ### From an Arrow Table {#from-an-arrow-table} You can also create LanceDB tables directly from Arrow tables. diff --git a/docs/web/ingestion/delete.mdx b/docs/web/ingestion/delete.mdx index b7b1f9432..2b961fc4b 100644 --- a/docs/web/ingestion/delete.mdx +++ b/docs/web/ingestion/delete.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Delete" description: "Select and delete records, verify the remaining rows, and understand storage retention." icon: trash availability: - oss: available + embedded: available enterprise: available - summary: >- - Delete rows through the SDKs in OSS and Enterprise. Storage reclamation follows compaction and retention policy. --- import { RsExample as RsDeleteRows } from '/snippets/ingestion_delete.mdx'; @@ -70,7 +68,7 @@ Compaction rewrites the live data layout; cleanup removes eligible retained versions and files. Retained history can continue to reference data that no longer appears in the latest table version. -In OSS, `optimize()` provides maintenance operations. In Enterprise, managed +In LanceDB Embedded, `optimize()` provides maintenance operations. In Enterprise, managed 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 diff --git a/docs/web/ingestion/index.mdx b/docs/web/ingestion/index.mdx index c37b46a62..28cfce650 100644 --- a/docs/web/ingestion/index.mdx +++ b/docs/web/ingestion/index.mdx @@ -5,10 +5,8 @@ description: "Choose how to create a table, append records or change existing da icon: inbox keywords: ["ingest", "create table", "add", "insert", "arrow", "pandas", "polars", "pydantic"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Create tables and write records through the SDKs in OSS and Enterprise. Enterprise also provides SQL write statements. --- import { PyWriteWorkflow, TsWriteWorkflowBody, TsWriteWorkflowTail, RsWriteWorkflow } from '/snippets/ingestion_examples.mdx'; @@ -32,7 +30,7 @@ with a stable key when the incoming data should update existing records. ## Connect and prepare the data {#connect-to-lancedb} -Use the [connection guide](/basics/connect) to connect to OSS or Enterprise. +Use the [connection guide](/basics/catalog) to connect to Embedded or Enterprise. The SDK write operations in this section work with both. Enterprise also supports [SQL write statements](/sql#dml); an SDK filter expression does not require a separate SQL connection. diff --git a/docs/web/ingestion/insert.mdx b/docs/web/ingestion/insert.mdx index f2ee0d7db..cd15bc65b 100644 --- a/docs/web/ingestion/insert.mdx +++ b/docs/web/ingestion/insert.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Insert" description: "Append records, load file-backed data or batches, and verify ingestion." icon: plus availability: - oss: available + embedded: available enterprise: available - summary: >- - Append records through the SDKs in OSS and Enterprise. For large Enterprise writes, see [large upload settings](#bulk-ingests-into-a-remote-table). --- import { @@ -167,7 +165,7 @@ Wait for the write operation's result, then check the expected records. Progress callbacks describe activity; they do not establish that a write succeeded. If a request fails after the server may have committed it, blindly repeating an append can duplicate rows. The client's automatic retries can do -the same: on a remote table, the Python and TypeScript 0.40.0 clients resend an +the same: on an Enterprise table, the Python and TypeScript 0.40.0 clients resend an append after a retryable status such as `504`, even when the server had already committed it, and `add()` still returns success. Reconcile using your record IDs, or choose an upsert policy designed for replay. @@ -176,9 +174,9 @@ IDs, or choose an upsert policy designed for replay. Enterprise -This section applies only to remote tables (`db://` connections). Embedded (local) writes are unaffected. +This section applies only to LanceDB Enterprise tables (`db://` connections). LanceDB Embedded writes are unaffected. -When you write to a remote LanceDB Enterprise table, the client sends the write as one HTTP `insert` request unless it splits the data into more than one partition, which it does for a large input it can measure or when you set [`write_parallelism`](#write-parallelism). A partitioned write goes up as a multipart write: the client cuts each partition into one or more `insert` parts and uploads them under a single upload id. Each part is streamed. Its size and duration still affect resource use and +When you write to a LanceDB Enterprise table, the client sends the write as one HTTP `insert` request unless it splits the data into more than one partition, which it does for a large input it can measure or when you set [`write_parallelism`](#write-parallelism). A partitioned write goes up as a multipart write: the client cuts each partition into one or more `insert` parts and uploads them under a single upload id. Each part is streamed. Its size and duration still affect resource use and timeouts: it has to finish within the client read timeout while the server writes it to object storage, so on very large ingests an oversized part can run past that timeout and surface as: ```text diff --git a/docs/web/ingestion/merge-insert.mdx b/docs/web/ingestion/merge-insert.mdx index 6fa59fd9c..a9ad3071c 100644 --- a/docs/web/ingestion/merge-insert.mdx +++ b/docs/web/ingestion/merge-insert.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Merge Insert" description: "Match incoming records by key and choose which rows to update, insert or remove." icon: code-merge availability: - oss: available + embedded: available enterprise: available - summary: >- - Merge insert is available through the SDKs in OSS and Enterprise. Use it for key-based updates and inserts. --- import { @@ -230,7 +228,7 @@ when changing the input used to generate it. Rust's `when_matched_update_all_expr` and `when_not_matched_by_source_delete_expr` accept DataFusion expressions for -local tables. Use the string predicate variants for Enterprise tables. +LanceDB Embedded tables. Use the string predicate variants for Enterprise tables. ## Complete write workflow {#complete-example} diff --git a/docs/web/ingestion/realtime-write.mdx b/docs/web/ingestion/realtime-write.mdx new file mode 100644 index 000000000..bed77eed5 --- /dev/null +++ b/docs/web/ingestion/realtime-write.mdx @@ -0,0 +1,196 @@ +--- +title: "Real Time writes" +sidebarTitle: "Real Time Write" +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 + 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). + +## Getting started {#getting-started} + +### 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 +single `int32`, `int64`, string, or binary column, and cannot be changed once +set. + +The table below holds frames captioned and embedded as they stream in from a +live camera feed, such as a robot recording episodes into a dataset shaped +like [LeRobotDataset](/integrations/lerobotdataset)'s `frames` table — +`frame_id` is the primary key so a re-captioned frame upserts in place: + + +```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 + +db = lancedb.connect("db://my_db", api_key="...", host_override="https://...") + +dim = 768 +schema = pa.schema([ + pa.field("frame_id", pa.int64(), nullable=False), + pa.field("video_id", pa.utf8(), nullable=False), + pa.field("embedding", pa.list_(pa.float32(), dim)), + pa.field("caption", pa.utf8()), +]) +frames = db.create_table("frames", schema=schema) +frames.set_unenforced_primary_key("frame_id") +``` + + +Or in SQL: + + +```sql SQL +ALTER TABLE frames SET UNENFORCED PRIMARY KEY (frame_id) +``` + + +### 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 +required for partial updates and deletes. + + +```python Python icon="python" +frames.create_index("embedding", config=IvfPq()) +frames.create_index("caption", config=FTS()) +frames.create_index("frame_id", config=BTree()) +frames.wait_for_index(["embedding_idx", "caption_idx", "frame_id_idx"], timeout=timedelta(minutes=5)) +``` + + +### 3. Enable RTE {#enable} + + +```python Python icon="python" +frames.enable_rte(RTEWriteSpec.unsharded()) +``` + + +Or in SQL: + + +```sql SQL +ALTER TABLE frames SET RTE +``` + + +### 4. Write {#write} + + +On an RTE table, an upsert through `merge_insert` is the only way to write +rows. Use the form below exactly: `when_matched_update_all()` with no filter, +plus `when_not_matched_insert_all()`. Other `merge_insert` forms, such as +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 +back: + + +```python Python icon="python" +new_frames = pa.table({ + "frame_id": pa.array([2000, 2001], pa.int64()), + "video_id": pa.array(["clip-9", "clip-9"]), + "embedding": pa.FixedSizeListArray.from_arrays( + pa.array(np.random.rand(2 * dim).astype("float32")), dim), + "caption": pa.array(["a gripper closing on a cup", "a cup set down on the table"]), +}, schema=schema) + +frames.merge_insert("frame_id") \ + .when_matched_update_all() \ + .when_not_matched_insert_all() \ + .execute(new_frames) +``` + + +**Partial updates.** Send the primary key plus only the columns you want to +change; omitted columns keep their current values. This requires a scalar +index on the primary key. A re-captioning job, for example, only touches +`caption`: + + +```python Python icon="python" +patch = pa.table( + {"frame_id": [2000, 2001], "caption": ["a two-finger gripper closing on a cup", "the cup resting upright"]}, + schema=pa.schema([schema.field("frame_id"), schema.field("caption")]), +) +frames.merge_insert("frame_id").when_matched_update_all().when_not_matched_insert_all().execute(patch) +``` + + +**Deletes.** The predicate must bind the primary key to literal values. Ranges, +`OR`, and filters on other columns are rejected. Deletes require a scalar index +on the primary key. + + +```python Python icon="python" +frames.delete("frame_id IN (2000, 2001)") +``` + + +### Disabling RTE {#disable} + +Stop writes and wait for in-flight writes to finish, then flush pending writes +into the base table and disable. `checkpoint_rte()` only drains writes that +existed when it started, so anything written during the checkpoint can be left +behind. `disable_rte()` is rejected while the write-ahead log still holds rows, +so run `checkpoint_rte()` first. + + +```python Python icon="python" +frames.checkpoint_rte() +frames.disable_rte() +``` + + +## Write performance {#write-performance} + +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. + +**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. + +## 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) +- [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 d44a2561e..ad4ae23b2 100644 --- a/docs/web/ingestion/update.mdx +++ b/docs/web/ingestion/update.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Update" description: "Select existing rows, change values or expressions, and verify the changes." icon: pen availability: - oss: available + embedded: available enterprise: available - summary: >- - Update rows through the SDKs in OSS and Enterprise. Enterprise also supports the SQL UPDATE statement. --- import { @@ -71,7 +69,7 @@ Rust's `column` argument is an expression, so the string value includes SQL quot In this separate example, Bob keeps his name and his login count becomes **21**. Python's `values_sql` and TypeScript's `valuesSql` accept expressions. -These SDK expressions work with embedded OSS tables; they do not require an +These SDK expressions work with LanceDB Embedded tables; they do not require an Enterprise SQL endpoint. Enterprise also offers [`UPDATE`](/sql/dml/update). ## Verify the affected data {#verify} @@ -83,7 +81,7 @@ connection or table handle, account for its 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 column](/feature-engineering/refresh-column). +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) diff --git a/docs/web/integrations/ai/agno.mdx b/docs/web/integrations/ai/agno.mdx index b5edef031..9ad9daeac 100644 --- a/docs/web/integrations/ai/agno.mdx +++ b/docs/web/integrations/ai/agno.mdx @@ -139,7 +139,7 @@ We get the response based on the transcript's contents and title as expected. ## Why this works well {#why-this-works-well} -To start, LanceDB OSS can run from a local directory, so transcript data can stay on your machine when you are using the OSS stack. +To start, LanceDB Embedded can run from a local directory, so transcript data can stay on your machine. - You do not need to maintain a separate transcript parser in your application code. - You do not need to hand-roll chunking and retrieval orchestration across multiple modules. diff --git a/docs/web/integrations/ai/hermes-agent.mdx b/docs/web/integrations/ai/hermes-agent.mdx index 12fc39da3..e899e2e60 100644 --- a/docs/web/integrations/ai/hermes-agent.mdx +++ b/docs/web/integrations/ai/hermes-agent.mdx @@ -29,7 +29,7 @@ prompt, plus lexical (keyword) search over past sessions. Both are useful, but k misses paraphrases of what you originally typed, the exact thing you need when recalling a fact you phrased differently months ago. -LanceDB OSS is an embedded retrieval library, which makes it a natural fit here: +LanceDB Embedded is a retrieval library that runs inside your application, which makes it a natural fit here: - **No server to stand up**: it reads and writes a table on local disk, so the plugin ships as a dependency rather than a service to operate. diff --git a/docs/web/integrations/ai/huggingface.mdx b/docs/web/integrations/ai/huggingface.mdx index 0a38c208b..b284d38a2 100644 --- a/docs/web/integrations/ai/huggingface.mdx +++ b/docs/web/integrations/ai/huggingface.mdx @@ -3,11 +3,8 @@ 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." availability: - oss: available - enterprise: unavailable - summary: >- - The embedded library opens Lance datasets on the Hugging Face Hub in place - through `hf://` URIs. A deployment does not read `hf://` datasets. + 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. diff --git a/docs/web/integrations/ai/vscode.mdx b/docs/web/integrations/ai/vscode.mdx new file mode 100644 index 000000000..4c9319dd5 --- /dev/null +++ b/docs/web/integrations/ai/vscode.mdx @@ -0,0 +1,297 @@ +--- +title: "VS Code extensions" +sidebarTitle: "VS Code" +description: "Embed LanceDB in a VS Code extension to search a workspace by meaning, with no server, and bundle and package its native binaries correctly." +keywords: ["vscode", "visual studio code", "extension", "electron", "esbuild", "vsix", "semantic search"] +--- + +import { + TsVscodeChunk, + TsVscodeConnect, + TsVscodeImports, + TsVscodeIndex, + TsVscodeSearch, +} from '/snippets/vscode_search.mdx'; +import { TsVscodeExtension } from '/snippets/vscode_extension.mdx'; + +A VS Code extension runs in the *extension host*, a Node.js process, so LanceDB's TypeScript SDK +(`@lancedb/lancedb`) runs inside it like any other npm package. There's no database server to +start: the extension opens a table on local disk and queries it in-process. That makes LanceDB +a good fit for features such as semantic search over a workspace, retrieval for an AI assistant, +or a cache of embeddings that survives restarts. + +The extension host differs from a plain Node.js script in three ways that trip people up: + +- **Where you can write.** Relative paths resolve against the extension host's working + directory, not the workspace, and that directory may be read-only. +- **Bundling.** The default extension template bundles everything with esbuild, which can't + bundle LanceDB's native `.node` binary. +- **Packaging.** LanceDB installs a native binary for the current platform only, so a VSIX + built on one OS doesn't run on another. + +This guide builds a small extension that handles all three. It indexes the Markdown files in a +workspace and searches them by meaning, using a local embedding model, so no API key is needed. + + +**What you'll build** + +- **LanceDB: Index Markdown in Workspace** splits every `*.md` file into paragraphs and stores + them in a LanceDB table, with embeddings from `Xenova/all-MiniLM-L6-v2` run locally through + Transformers.js. +- **LanceDB: Search Markdown** embeds your query, shows the five closest paragraphs, and opens + the one you pick. + + +## Create the extension {#create-the-extension} + + + +Use the official generator. Choose **New Extension (TypeScript)** and **esbuild** as the bundler. + +```bash +npx --package yo --package generator-code -- yo code +``` + + + +```bash +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 +newer `apache-arrow`, installing LanceDB fails with `ERESOLVE`. + +LanceDB also needs `@types/node` 22 or later. The generator's template already uses a recent +version; an old one causes `Cannot find module 'node:stream'` errors. + +You don't need to install `@huggingface/transformers` yourself. LanceDB pins it as an optional +dependency, and installing a different version gives your code a copy that LanceDB doesn't use. + + + +The type declarations of `apache-arrow` and the ONNX runtime used by Transformers.js refer to +browser types such as `ReadableStreamReadResult` and `HTMLCanvasElement`. The template's +`tsconfig.json` doesn't include the DOM library, so `tsc` reports errors inside `node_modules`. +Turn on `skipLibCheck`: + +```json tsconfig.json icon="brackets-curly" +{ + "compilerOptions": { + "skipLibCheck": true + } +} +``` + + + +## Store the database in extension storage {#store-the-database-in-extension-storage} + +Give LanceDB an absolute path inside the storage VS Code reserves for your extension: + +- `context.storageUri`: a folder for the current workspace. It's `undefined` when no folder is + open. Use it for anything derived from the workspace, such as this index. +- `context.globalStorageUri`: a folder shared by all workspaces. Use it for things like + downloaded models. + +Neither folder is guaranteed to exist, so create it before connecting. Both live outside the +user's project, so the index never shows up in their files or in version control. + +Don't pass a relative path such as `lancedb.connect("data")`. It resolves against the extension +host's working directory, which isn't the workspace and may be read-only: this causes the +`Read-only file system (os error 30)` error on macOS. + +Put the LanceDB code in its own module, `src/search.ts`: + + + {TsVscodeImports} + + + + {TsVscodeConnect} + + +## Index and search {#index-and-search} + +Split each file into paragraphs, and keep the line each one starts on so a result can open the +file at the right place: + + + {TsVscodeChunk} + + +Create the table with LanceDB's built-in `huggingface` [embedding function](/embedding/quickstart). +Because the `text` column is declared as the function's source field, LanceDB computes the +`vector` column for you as the rows are written: + + + {TsVscodeIndex} + + +The table remembers its embedding function, so you can search it with plain text after VS Code +restarts: + + + {TsVscodeSearch} + + +`mode: "overwrite"` rebuilds the index each time, which is fine for a few thousand paragraphs. +For larger workspaces, update only the files that changed with +[`mergeInsert`](/ingestion/merge-insert). + +## Wire up the commands {#wire-up-the-commands} + +Declare the two commands in `package.json`: + +```json package.json icon="brackets-curly" +"contributes": { + "commands": [ + { + "command": "lancedbSearch.index", + "title": "Index Markdown in Workspace", + "category": "LanceDB" + }, + { + "command": "lancedbSearch.search", + "title": "Search Markdown", + "category": "LanceDB" + } + ] +} +``` + +Then register them in `src/extension.ts`: + + + {TsVscodeExtension} + + +A few details in this file are specific to running inside VS Code: + +- The index goes in `storageUri`, so each workspace gets its own table. +- The embedding model (about 90 MB) downloads on first use. By default Transformers.js caches it + inside `node_modules` in the installed extension, which is replaced on every update. Setting + `env.cacheDir` keeps it in global storage. Load the module with `import()`, not `require()`: + LanceDB loads the ES module build of `@huggingface/transformers`, and `require()` returns a + separate copy whose settings LanceDB never sees. +- Each paragraph is stored with its file's URI, not a path relative to a workspace folder. In a + multi-root workspace, `findFiles` searches every folder and two folders can hold the same + relative path, so only the URI opens the right file. `asRelativePath` turns it back into a + short label, which names the folder when there's more than one. +- When another extension or a test passes a query to `lancedbSearch.search`, it returns the + rows instead of opening a picker. That's how the results below were produced, with each URI + shown through `asRelativePath`. + +## Sample results {#sample-results} + +Here are the results of running the extension in VS Code against a small workspace of six +Markdown files that document a fictional CLI. The columns are the vector distance (lower is +closer), the file and line, and the paragraph. + +```text +query: my credentials were exposed, what should I do? + 33.100 docs/auth.md:5 If a token leaks, revoke it on the Tokens page and generate a replacement. Revoked tokens stop working immediately. + 40.091 docs/troubleshooting.md:5 Run `acme doctor` to print diagnostics you can attach to a bug report. + 42.334 CONTRIBUTING.md:3 Run `npm test` before opening a pull request. New commands need a page in docs/. + 43.105 docs/auth.md:3 Acme uses personal access tokens. Create one under Settings > Tokens. + 45.664 README.md:5 Install it with `npm install -g acme-cli`, then run `acme login`. + +query: uploads are stuck behind the company firewall + 38.420 docs/troubleshooting.md:3 If `acme sync` hangs, check that your proxy allows connections to api.acme.dev on port 443. + 39.212 docs/sync.md:3 Run `acme sync` to upload changed notes. Only files modified since the last sync are sent. + 40.859 docs/auth.md:5 If a token leaks, revoke it on the Tokens page and generate a replacement. Revoked tokens stop working immediately. + 42.537 docs/troubleshooting.md:5 Run `acme doctor` to print diagnostics you can attach to a bug report. + 45.853 CONTRIBUTING.md:3 Run `npm test` before opening a pull request. New commands need a page in docs/. +``` + +Neither top result shares a keyword with its query: "credentials were exposed" matches "a +token leaks", and "stuck behind the company firewall" matches "hangs … proxy". Picking a result +in the search box opens the file at that paragraph. + +## Bundle with esbuild {#bundle-with-esbuild} + +The template bundles your code and its dependencies into `dist/extension.js`. esbuild can't +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" +external: [ + "vscode", + "@lancedb/lancedb", + "@huggingface/transformers", + // LanceDB loads apache-arrow from node_modules anyway; bundling it ships a second copy. + "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 +leaves out the dev dependencies. If you skip this step, the packaged extension fails to +activate with `Cannot find module '@lancedb/lancedb'`, and its commands report +`command 'lancedbSearch.index' not found`. + +## Package a VSIX for each platform {#package-a-vsix-for-each-platform} + +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 +npx @vscode/vsce package --target win32-x64 +``` + +| `vsce` target | LanceDB native package | +|:--|:--| +| `win32-x64` | `@lancedb/lancedb-win32-x64-msvc` | +| `win32-arm64` | `@lancedb/lancedb-win32-arm64-msvc` | +| `linux-x64` | `@lancedb/lancedb-linux-x64-gnu` | +| `linux-arm64` | `@lancedb/lancedb-linux-arm64-gnu` | +| `alpine-x64` | `@lancedb/lancedb-linux-x64-musl` | +| `alpine-arm64` | `@lancedb/lancedb-linux-arm64-musl` | +| `darwin-arm64` | `@lancedb/lancedb-darwin-arm64` | + +LanceDB doesn't publish a binary for Intel Macs (`darwin-x64`). + +The table covers LanceDB's own binaries. This sample's local model also needs +`onnxruntime-node`, which Transformers.js loads when the extension activates. Its Linux binaries +link against glibc and it publishes no musl build, so the sample as written doesn't run on +Alpine, whatever `--target` you pass. To ship the `alpine-*` targets, embed with a hosted API or +use [full-text search](/search/full-text-search) instead, or build ONNX Runtime for musl yourself. + + +Native binaries make the VSIX large: the `win32-x64` build of this extension is about 200 MB. +`onnxruntime-node`, which Transformers.js uses, ships binaries for every platform. Excluding +the ones a target doesn't need brings the `win32-x64` build to about 150 MB. Keep one ignore +file per target and pass it with `--ignoreFile`: + +```text .vscodeignore.win32-x64 +node_modules/onnxruntime-node/bin/napi-v3/darwin/** +node_modules/onnxruntime-node/bin/napi-v3/linux/** +node_modules/onnxruntime-node/bin/napi-v3/win32/arm64/** +``` + +If you don't need a local model, embed text with a hosted API instead, or use +[full-text search](/search/full-text-search), which needs no model at all. + + +## Keep the extension host responsive {#keep-the-extension-host-responsive} + +All extensions share one extension host, and loading the model and computing embeddings in it +can stall the others. While the sample indexes, VS Code may briefly report that the extension +host is unresponsive. That's fine for a handful of files. For a large workspace, move indexing into a +[worker thread](https://nodejs.org/api/worker_threads.html) or a child process, and index in +batches as files change instead of all at once. + +## Troubleshooting {#troubleshooting} + +| Error | Cause | Fix | +|:--|:--|:--| +| `Read-only file system (os error 30)` | A relative database path resolved against the extension host's working directory | Connect to an absolute path under `context.storageUri` or `context.globalStorageUri` | +| `No loader is configured for ".node" files` | esbuild tried to bundle a native binary | Mark `@lancedb/lancedb` and `@huggingface/transformers` as `external` | +| `Cannot find module '@lancedb/lancedb'`, or `command '…' not found` | The VSIX doesn't contain `node_modules` | Remove `node_modules/**` from `.vscodeignore` | +| A native module isn't found on another OS | The VSIX was built on a different platform | Package one VSIX per `--target` on a matching machine | +| `Cannot find module 'node:stream' or its corresponding type declarations` | `@types/node` is too old | Use `@types/node` 22 or later | +| `Cannot find name 'HTMLCanvasElement'` and similar errors in `node_modules` | Dependency typings refer to DOM types | Set `"skipLibCheck": true` | +| `ERESOLVE` with `peer apache-arrow@">=15.0.0 <=18.1.0"` | The project depends on a newer `apache-arrow` | Install `apache-arrow@18.1.0` | +| The model downloads again after an update | Transformers.js caches inside the extension's `node_modules` | Set `env.cacheDir` through `import("@huggingface/transformers")` | diff --git a/docs/web/integrations/data/dlt.mdx b/docs/web/integrations/data/dlt.mdx index 04d688fb9..f5ede936b 100644 --- a/docs/web/integrations/data/dlt.mdx +++ b/docs/web/integrations/data/dlt.mdx @@ -40,7 +40,7 @@ In this example, we will be fetching movie information from the [Open Movie Data 3. **Specify necessary credentials and/or embedding model details:** - To fetch data from the OMDb API, you will need to pass a valid API key into your pipeline. Depending on whether you're using LanceDB OSS or LanceDB Enterprise, you also may need to provide the necessary credentials to connect to the LanceDB instance. These can be pasted inside `.dlt/secrets.toml`. + To fetch data from the OMDb API, you will need to pass a valid API key into your pipeline. Depending on whether you're using LanceDB Embedded or LanceDB Enterprise, you also may need to provide the necessary credentials to connect to the LanceDB instance. These can be pasted inside `.dlt/secrets.toml`. 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 @@ -52,7 +52,7 @@ In this example, we will be fetching movie information from the [Open Movie Data embedding_model = "all-MiniLM-L6-v2" [destination.lancedb.credentials] uri = ".lancedb" - api_key = "api_key" # API key to connect to LanceDB Enterprise. Leave out if you are using LanceDB OSS. + api_key = "api_key" # API key to connect to LanceDB Enterprise. Leave out if you are using LanceDB Embedded. embedding_model_provider_api_key = "embedding_model_provider_api_key" # Not needed for providers that don't need authentication (ollama, sentence-transformers). ``` See [here](https://dlthub.com/docs/dlt-ecosystem/destinations/lancedb#configure-the-destination) for more information and for a list of available models and model providers. diff --git a/docs/web/integrations/data/duckdb.mdx b/docs/web/integrations/data/duckdb.mdx index 23c4891f9..25c982b90 100644 --- a/docs/web/integrations/data/duckdb.mdx +++ b/docs/web/integrations/data/duckdb.mdx @@ -6,7 +6,7 @@ description: "Learn how to use the DuckDB-Lance extension to query Lance tables LanceDB integrates with [DuckDB](https://duckdb.org/) through the [Lance extension](https://github.com/lance-format/lance-duckdb) for DuckDB. In this page, we'll show how LanceDB manages table lifecycle, and DuckDB provides SQL analytics (including joins) and search over those tables. -Note that earlier versions of LanceDB used to recommend converting Lance tables to Arrow tables via `table.to_arrow()`. Although this method is still available for local tables (because DuckDB [natively scans Arrow tables](https://duckdb.org/2021/12/03/duck-arrow)), it is no longer the recommended workflow for working with Lance tables in DuckDB. This page shows how to use the Lance extension with namespace-attached LanceDB tables, allowing you to pushdown SQL queries directly to the Lance layer. +Note that earlier versions of LanceDB used to recommend converting Lance tables to Arrow tables via `table.to_arrow()`. Although this method is still available for LanceDB Embedded tables (because DuckDB [natively scans Arrow tables](https://duckdb.org/2021/12/03/duck-arrow)), it is no longer the recommended workflow for working with Lance tables in DuckDB. This page shows how to use the Lance extension with namespace-attached LanceDB tables, allowing you to pushdown SQL queries directly to the Lance layer. ## Install {#install} diff --git a/docs/web/integrations/data/pandas_and_pyarrow.mdx b/docs/web/integrations/data/pandas_and_pyarrow.mdx index c646e7f3b..810536587 100644 --- a/docs/web/integrations/data/pandas_and_pyarrow.mdx +++ b/docs/web/integrations/data/pandas_and_pyarrow.mdx @@ -2,12 +2,8 @@ title: "Pandas and PyArrow" sidebarTitle: "Pandas & PyArrow" availability: - oss: available + embedded: available enterprise: available - summary: >- - DataFrames go into `create_table` and come back from query results the same - way for local and deployment tables. - --- import { diff --git a/docs/web/integrations/data/polars_arrow.mdx b/docs/web/integrations/data/polars_arrow.mdx index 3acfcfea5..4ff759211 100644 --- a/docs/web/integrations/data/polars_arrow.mdx +++ b/docs/web/integrations/data/polars_arrow.mdx @@ -2,13 +2,8 @@ title: "Polars" sidebarTitle: "Polars & Arrow" availability: - oss: available + embedded: available enterprise: available - summary: >- - Polars data goes into `create_table`, and query results come back as Polars - DataFrames, for local and deployment tables alike; a LazyFrame over a whole - table is local only. - --- import { @@ -43,7 +38,7 @@ Run vector search and keep the results as a Polars `DataFrame` for further proce ## Work with LazyFrames {#work-with-lazyframes} -When you want to operate on the entire table (potentially larger than RAM), convert to a Polars `LazyFrame` so you can chain transformations without loading everything at once. This works for local tables only; with LanceDB Enterprise, `search(...).to_polars()` returns an eager DataFrame of query results. +When you want to operate on the entire table (potentially larger than RAM), convert to a Polars `LazyFrame` so you can chain transformations without loading everything at once. This works for LanceDB Embedded tables only; with LanceDB Enterprise, `search(...).to_polars()` returns an eager DataFrame of query results. {PyPlatformsPolarsLazyframe} diff --git a/docs/web/integrations/data/pydantic.mdx b/docs/web/integrations/data/pydantic.mdx index 3ac660774..132ce7801 100644 --- a/docs/web/integrations/data/pydantic.mdx +++ b/docs/web/integrations/data/pydantic.mdx @@ -2,13 +2,8 @@ title: "Pydantic" sidebarTitle: "Pydantic" availability: - oss: available + embedded: available enterprise: available - summary: >- - The SDK converts `LanceModel` schemas to Arrow, and query rows back to - models, in your process, so they work the same with local and deployment - tables. - --- import { diff --git a/docs/web/integrations/embedding/cohere.mdx b/docs/web/integrations/embedding/cohere.mdx index b9a8e3378..3c56fec76 100644 --- a/docs/web/integrations/embedding/cohere.mdx +++ b/docs/web/integrations/embedding/cohere.mdx @@ -18,16 +18,20 @@ Supported models are: - embed-multilingual-v3.0 - embed-english-light-v3.0 - embed-multilingual-light-v3.0 -- embed-english-v2.0 -- embed-english-light-v2.0 -- embed-multilingual-v2.0 + +The v2.0 models (`embed-english-v2.0`, `embed-english-light-v2.0` and `embed-multilingual-v2.0`) were retired by Cohere on April 4, 2026. + +The previous default, `embed-multilingual-v2.0`, produced 768-dimensional vectors. +The new default, `embed-multilingual-v3.0`, produces 1024-dimensional vectors. +Existing tables containing vectors from a v2.0 model must be re-embedded with an +active model into a table whose vector column has the matching dimension. Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | |---|---|--------|---------| -| `name` | `str` | `"embed-english-v2.0"` | The model ID of the cohere model to use. Supported base models for Text Embeddings: embed-english-v3.0, embed-multilingual-v3.0, embed-english-light-v3.0, embed-multilingual-light-v3.0, embed-english-v2.0, embed-english-light-v2.0, embed-multilingual-v2.0 | +| `name` | `str` | `"embed-multilingual-v3.0"` | The model ID of the cohere model to use. Supported base models for Text Embeddings: embed-english-v3.0, embed-multilingual-v3.0, embed-english-light-v3.0, embed-multilingual-light-v3.0 | | `source_input_type` | `str` | `"search_document"` | The type of input data to be used for the source column. | | `query_input_type` | `str` | `"search_query"` | The type of input data to be used for the query. | @@ -52,4 +56,4 @@ Usage Example: {PyEmbeddingCohereUsage} - \ No newline at end of file + diff --git a/docs/web/integrations/embedding/nvidia.mdx b/docs/web/integrations/embedding/nvidia.mdx new file mode 100644 index 000000000..c0664684a --- /dev/null +++ b/docs/web/integrations/embedding/nvidia.mdx @@ -0,0 +1,107 @@ +--- +title: NVIDIA Nemotron +sidebarTitle: NVIDIA +description: Text embeddings with Nemotron 3.5 Embed 1B and 8B in the Python SDK. +--- + +The Python SDK registers `nvidia` for client-side text embedding with NVIDIA-hosted +and self-hosted NIM endpoints. Documents use `input_type="passage"`; searches use +`input_type="query"`. This provider supports text only, with floating-point output. +Null and empty text values get a null vector without a request; pass +`on_bad_vectors="null"` or `"drop"` to `add` to keep or skip those rows. +Image and combined text/image inputs are not supported by this integration. + +Install the optional client and set your NVIDIA API key: + +```shell +pip install openai +export NVIDIA_API_KEY="your-api-key" +``` + +```python +import lancedb +from lancedb.embeddings import get_registry +from lancedb.pydantic import LanceModel, Vector + +func = get_registry().get("nvidia").create( + name="nvidia/nemotron-3.5-embed-1b", +) + +class Document(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + +db = lancedb.connect("./nemotron-db") +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, +`add`, and `search` calls compute embeddings in the Python client. The NVIDIA key +is separate from the LanceDB database key. Use a fresh table name when creating a +table; reopening an existing table restores its embedding configuration. + +## Models and configuration + +The hosted API documents these exact IDs and dimensions: + +| Model ID | Default dimensions | Supported `dim` | +|---|---:|---:| +| `nvidia/nemotron-3.5-embed-1b` | 2048 | 128–2048 | +| `nvidia/nemotron-3.5-embed-8b` | 4096 | 1–4096 | + +| Parameter | Default | Description | +|---|---|---| +| `name` | `nvidia/nemotron-3.5-embed-1b` | Model ID sent to the endpoint. | +| `dim` | Model default above | Output dimensions; required for other served model IDs. | +| `base_url` | `https://integrate.api.nvidia.com/v1` | API base including `/v1`. | +| `api_key` | `NVIDIA_API_KEY` for the hosted API | Alternatively, a registry reference such as `$var:nvidia-key`. | +| `batch_size` | `32` | Maximum inputs per request. Reduce for your deployment's limits. | +| `truncate` | `END` | Truncate overlong text at the end, or use `NONE` to reject it. | +| `max_retries` | `7` | LanceDB's retry policy, applied to each request during automatic document/query embedding. | + +Requests specify `modality="text"` and `encoding_format="float"`. Returned vectors +are checked for count, input indices, dimensions, and finite numeric values. +The hosted input limit is 10,240 tokens per item; self-hosted limits depend on the +served profile. This provider batches by item count, not token count. + +## Self-hosted NIM + +Set `name` to the exact ID returned by your deployment's `GET /v1/models` and +`dim` to an output dimension that deployment supports: + +```python +func = get_registry().get("nvidia").create( + name="nvidia/Nemotron-3.5-Embed-1B-BF16", + base_url="http://localhost:8000/v1", + dim=2048, +) +``` + +Custom endpoints may run without a key. `NVIDIA_API_KEY` is only sent to the +hosted API, so for authenticated endpoints use +`get_registry().set_var("nvidia-key", key)` with `api_key="$var:nvidia-key"`. Registry references, rather than secret values, are +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")`. + +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. + +NVIDIA references (checked October 23, 2026): +[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), +[NIM support matrix](https://docs.nvidia.com/nim/nemo-retriever/embedding/2.4/support-matrix.html). diff --git a/docs/web/integrations/embedding/ollama.mdx b/docs/web/integrations/embedding/ollama.mdx index 120cde8f2..bd161a692 100644 --- a/docs/web/integrations/embedding/ollama.mdx +++ b/docs/web/integrations/embedding/ollama.mdx @@ -10,6 +10,9 @@ Generate embeddings via the [ollama](https://github.com/ollama/ollama-python) py - [Ollama docs on embeddings](https://github.com/ollama/ollama/blob/main/docs/api.md#generate-embeddings) - [Ollama blog on embeddings](https://ollama.com/blog/embedding-models) +For direct calls, `compute_source_embeddings` accepts a list of strings or a +one-dimensional NumPy string array. Both inputs are sent to Ollama in one batch. + | Parameter | Type | Default Value | Description | |------------------------|----------------------------|--------------------------|------------------------------------------------------------------------------------------------------------------------------------------------| | `name` | `str` | `nomic-embed-text` | The name of the model. | diff --git a/docs/web/integrations/embedding/voyageai.mdx b/docs/web/integrations/embedding/voyageai.mdx index cfa795841..957ab2b4d 100644 --- a/docs/web/integrations/embedding/voyageai.mdx +++ b/docs/web/integrations/embedding/voyageai.mdx @@ -45,6 +45,8 @@ Supported parameters (to be passed in `create` method) are: | `output_dimension` | `int` | `None` | Output embedding dimension. Only supported by `voyage-multimodal-3.5`. Valid options: 256, 512, 1024 (default), 2048. | +For text models, `compute_source_embeddings()` accepts a single string, a list of strings, a one-dimensional NumPy array, or a PyArrow `Array` or `ChunkedArray`. Batch inputs retain their order. + Usage Example: @@ -55,10 +57,15 @@ Usage Example: ### Multimodal Example {#multimodal-example} -The `voyage-multimodal-3.5` model can embed text alongside images. You can use image URLs, file paths, or PIL Image objects: +The `voyage-multimodal-3.5` model can embed text alongside images. You can use image URLs, local `pathlib.Path` objects, raw image bytes, or PIL Image objects. + +For source embeddings, PIL images and images loaded from bytes or local paths are +converted to RGB and encoded as JPEG. This supports RGBA, grayscale with alpha, +and palette images; transparency is discarded. Composite transparent images onto +your chosen background before embedding if the background color matters. {PyEmbeddingVoyageaiMultimodal} - \ No newline at end of file + diff --git a/docs/web/integrations/lerobotdataset.mdx b/docs/web/integrations/lerobotdataset.mdx index cfb66b69b..260921034 100644 --- a/docs/web/integrations/lerobotdataset.mdx +++ b/docs/web/integrations/lerobotdataset.mdx @@ -138,6 +138,25 @@ class EmbedFromBlob: # SigLIP2 loads once per worker ... ``` +**Deduplication** removes near-static runs before they skew curation or +training. A stopped gripper holding one pose for a few seconds produces many +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 +db.execute_query(""" + CREATE MATERIALIZED VIEW frames_deduped AS + 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 +rows, not just which ones matched. Wrap it in a materialized view, as above, +to keep the deduplicated set current as new episodes land; see +[Materialized views](/feature-engineering/materialized-views). + **Search** is an index on those columns: a vector index over the embeddings built in 29.7 s across 27.6M rows, a full-text index over the instructions in 7.0 s, queries in 10 to 54 ms. **Curation** is one query across all of it. Semantic search with a predicate on the derived score, no join, no second system: diff --git a/docs/web/integrations/reranking/openai.mdx b/docs/web/integrations/reranking/openai.mdx index 6ceb8a030..71fe63117 100644 --- a/docs/web/integrations/reranking/openai.mdx +++ b/docs/web/integrations/reranking/openai.mdx @@ -26,7 +26,7 @@ credentials from environment variables or a secrets manager. ## Accepted Arguments {#accepted-arguments} | Argument | Type | Default | Description | | --- | --- | --- | --- | -| `model_name` | `str` | `"gpt-4-turbo-preview"` | The name of the reranker model to use.| +| `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. | | `api_key` | `str` | `None` | The API key to use. If None, will use the OPENAI_API_KEY environment variable. diff --git a/docs/web/maintenance/background-jobs.mdx b/docs/web/maintenance/background-jobs.mdx index dcfa31321..3c2718cfe 100644 --- a/docs/web/maintenance/background-jobs.mdx +++ b/docs/web/maintenance/background-jobs.mdx @@ -5,16 +5,13 @@ description: "Understand the Enterprise background jobs that maintain tables, in icon: gears keywords: ["background jobs", "job type", "wal", "spfresh", "prewarm", "archive"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - LanceDB Enterprise schedules background maintenance jobs according to your - cluster configuration. --- The jobs documented elsewhere in these docs ([Build & Repair](/indexing/reindexing), [Compaction](/maintenance/compaction), [Cleanup](/maintenance/cleanup), -[Column Refresh](/feature-engineering/refresh-column)) start from a call you +[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) @@ -27,13 +24,13 @@ also start cache-warming jobs through the admin API. ## Write-ahead log maintenance {#wal} -For a table with a [write-ahead log](/sql/ddl/table#properties) enabled, two jobs keep the +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 | | --- | --- | -| `sstable_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. | -| `wal_index_catchup` | Extends a base-table index over the rows `sstable_compaction` just folded in, and records how far the index has caught up. Nothing else advances that record. | +| `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} @@ -48,7 +45,7 @@ log from growing without bound: | --- | --- | | `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 a plan executor's own startup, rather than on a schedule, when the deployment enables it. | +| `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} diff --git a/docs/web/maintenance/cleanup.mdx b/docs/web/maintenance/cleanup.mdx index 7833fa8a0..365eb66e8 100644 --- a/docs/web/maintenance/cleanup.mdx +++ b/docs/web/maintenance/cleanup.mdx @@ -5,10 +5,8 @@ description: "Pruning old versions and the files only they referenced." icon: broom keywords: ["cleanup", "retention", "prune", "delete_unverified", "vacuum"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Both offerings support cleanup. Embedded `optimize()` uses a retention window of 7 days by default; Enterprise uses configured background cleanup and retention, and does not support `optimize()`. --- Every write keeps the version before it, which is what makes @@ -18,7 +16,7 @@ those versions referenced. **Enterprise job type:** `cleanup`. Distinct from `compact`: compaction -merges files, cleanup removes them. `optimize()` in OSS runs both in one call; +merges files, cleanup removes them. `optimize()` in LanceDB Embedded runs both in one call; Enterprise schedules them as separate jobs, and runs cleanup only when the deployment's configuration enables it. @@ -89,8 +87,9 @@ directly can corrupt current or historical snapshots. Upgrade all clients and maintenance workers to a version that understands Managed blobs before using them, and reopen handles created before that upgrade. -For local tables, `optimize()` performs compaction and cleanup. Enterprise runs -these as background jobs; the remote Python table does not support `optimize()`. +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. ## Disk usage does not drop immediately {#disk} diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 5bee9c65e..64f18b095 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -4,15 +4,11 @@ sidebarTitle: "Compaction" description: "Merge small files, prune old versions, and fold new rows into existing indexes." icon: broom availability: - oss: available + embedded: available enterprise: available - summary: >- - Tables are compacted in the embedded library and in LanceDB Enterprise. In the - embedded library you call `optimize()`; a deployment compacts tables in the - background, and `optimize()` is not available there. --- -import { PyStorageRebuildVectorIndex } from '/snippets/doc_storage_examples.mdx'; +import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompactionTuning } from '/snippets/doc_storage_examples.mdx'; Every write commits a new table version, and versions accumulate: small files from frequent appends, superseded files from updates and deletes, and rows added @@ -23,6 +19,24 @@ three; a deployment handles them in the background and does not support Run optimization as regular table maintenance, particularly after many small writes or a large ingest. +{/* +Draft for the LanceDB Embedded compaction SQ partition check release. Keep this section +unpublished until that behavior ships. + +### Recover from an oversized SQ partition {#oversized-sq-partition} + +Compacting a table with an IVF scalar-quantized (SQ) vector index can stop +before rewriting files if an affected partition is too large to remap. The +error identifies the index, segment, partition size, and vector dimension +instead of letting the remap fail at Arrow's fixed-size-list `u32` +child-array limit. + +Rebuild the affected vector index with enough IVF partitions to keep each +partition at or below `floor(u32::MAX / dimension)` vectors, then retry the +optimize. Rebuilding with the default IVF partitioning can also choose enough +partitions. +*/} + ## Optimize a table {#what-it-does} ```python @@ -44,7 +58,7 @@ needs to. **Enterprise job type:** `compact`. Runs automatically as data accumulates, separately from [`cleanup`](/maintenance/cleanup). The two are distinct jobs -even though `optimize()` bundles both in one OSS call. +even though `optimize()` bundles both in one LanceDB Embedded call. ## Retraining indexes {#retrain} @@ -80,7 +94,7 @@ continuous small writes needs it on a schedule. Compaction rewrites files, which conflicts with a concurrent [computed-column refresh](/feature-engineering/add-computed-column) or -[view refresh](/feature-engineering/materialized-views) planned against the +[view refresh](/feature-engineering/refresh-materialized-view) planned against the version it replaces. Sequence them rather than running both at once. @@ -95,7 +109,7 @@ Two things accumulate on a long-lived table as more and more data gets added to - **Many small fragments build up as you write**, slowing down queries that have to scan across more files. **Compaction** merges them back into larger fragments. - **Old versions build up as the table changes**, growing disk usage beyond the live data size (LanceDB retains them for time-travel and rollback). **Cleanup** prunes versions older than a retention window. -In OSS, you run them yourself via `optimize()`, which bundles both into a single call: +In LanceDB Embedded, you run them yourself via `optimize()`, which bundles both into a single call: ```python Python icon="python" from datetime import timedelta @@ -104,3 +118,41 @@ 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. + +{/* +Draft for the Python compaction_options release. Keep this section unpublished +until the first supported release is confirmed. + +### Tune compaction for wide rows {#tune-wide-rows} + +For an existing LanceDB Embedded table, derive a fragment row target from the expected +row size. These examples use rows averaging 1 KiB and a 64 KiB fragment +target; choose sizes for your workload. Smaller scan batches and one compaction +task at a time can also reduce memory use. + + + + {PyStorageCompactionTuning} + + + {RsStorageCompactionTuning} + + + +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. + +Planning remains row based. The row target bounds later passes after existing +oversized fragments have been rewritten; the first pass rewrites those +fragments whole, so peak memory can exceed the target. `max_bytes_per_file` +limits output file size rather than compaction memory. + +The `max_source_rows` and `max_source_bytes` budgets admit whole planned tasks. +If the first task exceeds a budget, that run performs no compaction. See the +[CompactionOptions reference](https://lancedb.github.io/lancedb/python/python/#lancedb.table.CompactionOptions) +for all options and their limits. +*/} diff --git a/docs/web/management/database.mdx b/docs/web/management/database.mdx index a4b76f195..6651d6409 100644 --- a/docs/web/management/database.mdx +++ b/docs/web/management/database.mdx @@ -5,11 +5,8 @@ description: "Connect to LanceDB and configure storage, credentials and read con icon: database keywords: ["connect", "database", "uri", "api key", "storage options", "consistency"] availability: - oss: available + embedded: available enterprise: available - summary: >- - OSS opens tables in a local directory or object storage. Enterprise connects - to remote compute with a database URI and credentials. --- import { PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; @@ -22,11 +19,11 @@ objects, and configure how your application reaches the data. | URI | Offering | Where queries run | | --- | --- | --- | -| `./.lancedb` | OSS, with local storage | In your application | -| `s3://bucket/path`, `gs://bucket/path`, `az://container/path` | OSS, with object storage | In your application | -| `db://my-database` | Enterprise | On remote compute | +| `./.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) | -[Connect to LanceDB](/basics/connect) has examples for each connection type. +[Connect to LanceDB](/basics/catalog) has examples for each connection type. A connection to object storage still uses the embedded library: your process reads and writes the bucket directly. Enterprise runs operations remotely and manages the supporting compute and maintenance. @@ -60,7 +57,7 @@ manager. See [Authentication](/enterprise/authentication) for OAuth and ## Storage options {#storage-options} -For OSS tables in object storage, `storage_options` configures credentials, +For LanceDB Embedded tables in object storage, `storage_options` configures credentials, endpoints and options for new tables. This example enables stable row IDs for tables created through the connection: @@ -91,7 +88,7 @@ See [Storage](/deployment/storage) for provider credentials and other options. ## Read consistency {#consistency} -For OSS connections, `read_consistency_interval` controls how often reads check +For LanceDB Embedded connections, `read_consistency_interval` controls how often reads check for table versions committed by other writers. For example, check at most once every five seconds: @@ -112,7 +109,7 @@ const db = await lancedb.connect("./.lancedb", { readConsistencyInterval: 5 }); ``` -By default, an OSS table handle does not automatically pick up another +By default, an Embedded table handle does not automatically pick up another process's writes. Reopen the table, check out its latest version, or configure a consistency interval when you need those updates. A zero interval checks on every read, with the cost of a metadata check. @@ -139,7 +136,7 @@ versions and lifecycle operations. Dropping a table removes its history as well as its current data. You cannot -recover a dropped table through table versioning. The OSS `drop_database()` +recover a dropped table through table versioning. The LanceDB Embedded `drop_database()` and `drop_all_tables()` operations remove all tables without a confirmation prompt. diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 8e5b53e4a..415de7613 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -4,11 +4,6 @@ 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: - oss: unavailable - enterprise: available - summary: >- - Enterprise supports Functions when enabled for your Enterprise cluster; the embedded library cannot register or run them. --- import { @@ -19,6 +14,8 @@ import { PyFunctionApply as FunctionApply, PyFunctionRefresh as FunctionRefresh, PyFunctionInspect as FunctionInspect, + PyFunctionClassDefine as FunctionClassDefine, + PyFunctionClassApply as FunctionClassApply, } from '/snippets/function.mdx'; import { PyConnectEnterprisePlaceholders as FunctionConnect } from '/snippets/connection.mdx'; @@ -29,8 +26,8 @@ rather than pulling rows to your process. Registering and running a function needs a LanceDB Enterprise deployment with Functions enabled, which they are not by default. On a -local connection `create_function` raises `NotImplementedError`; to derive a -column locally, declare a +LanceDB Embedded connection `create_function` raises `NotImplementedError`; to +derive a column there, declare a [SQL computed column](/feature-engineering/add-computed-column) instead. @@ -108,6 +105,26 @@ with `db.get_function(name, version=...)`. the function is baked into an image before the version becomes usable. +## Try it in SQL {#try-sql} + +A registered function is callable in SQL by its name, the same as any other +scalar function. Before applying it as a column, call it directly over the +table to check the registration succeeded, without committing a schema +change: + + +```python Python icon="python" +reader = db.execute_query("SELECT value, double(value) AS doubled FROM function_demo") +print(reader.read_all().to_pylist()) +# [{'value': 1.0, 'doubled': 2.0}, {'value': 2.0, 'doubled': 4.0}, {'value': 3.0, 'doubled': 6.0}] +``` + + + +Equivalent SQL: `SELECT value, double(value) AS doubled FROM function_demo`. +See [Querying with SQL](/basics/sql) for `execute_query` and other languages. + + ## Apply it as a column {#apply} Calling the registered version binds each parameter, by name, to a column with @@ -122,6 +139,51 @@ function application keeps its scalar or named-struct result in the named column. A bare named-struct application expands its result fields as one atomic 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: + + +```python Python icon="python" +@udf +def ratio(numerator: float, denominator: float) -> float: + return numerator / denominator + +version = db.create_function_async(ratio).wait() +table.add_columns({"ratio": version(numerator=col("value"), denominator=col("count"))}) +``` + + +A named-struct output fills more than one column from a single application. +Declare the fields with `output_schema`, then alias each field to the column +it fills with `rename(columns=...)` and pass the application itself, not a +mapping, so both columns come from one atomic binding: + + +```python Python icon="python" +import pyarrow as pa + +@udf( + output_schema=pa.schema([ + pa.field("half", pa.float64(), nullable=False), + pa.field("double", pa.float64(), nullable=False), + ]), +) +def scale(value: float): + return {"half": value / 2, "double": value * 2} + +version = db.create_function_async(scale).wait() +application = version(value=col("value")).rename( + columns={"half": "value_half", "double": "value_double"} +) +table.add_columns(application) +``` + + +A single refresh fills `value_half` and `value_double` together: there is no +state where one is filled and the other is still empty. + ## Fill the column {#refresh} A refresh runs the function on the cluster as a [job](/basics/jobs). `wait()` @@ -143,50 +205,104 @@ rows added since the last one and recomputes rows whose inputs changed, and leaves filled rows with unchanged inputs alone. See [Refresh a column](/feature-engineering/refresh-column). +## Keep state in a class {#classes} + +A function that loads a model or opens a client should not do it for every +row. Decorate a class instead: its `__init__` does the expensive setup once, +and `__call__` handles each row or batch. + + +{FunctionClassDefine} + + +Registering the class does not construct it. `@udf` 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 +when it retires. Import heavy packages inside `__init__`, as above, so only the +worker needs them installed, and declare them in `pip`. + +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. + +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: + + +{FunctionClassApply} + + +Pass the application to `add_columns` as [above](#apply). Initialization values +are fixed for every row of a binding and take booleans, integers, floats, +strings, and lists or structs of them. A parameter with a default may be +omitted. Initialization values are stored with the binding, so keep +credentials out of them: pass `secrets=[EnvVarSecret(...)]` to +`create_function` and read the variable in `__init__`. + +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} 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. The worker reads the payload before -calling your function. Return bytes and let the destination table store the -Managed payload and descriptor. +`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. -Declare blob inputs and outputs explicitly. This example reverses the bytes -to demonstrate the round trip without requiring an image library. Here `db` -is an Enterprise database and `table` contains an `image` Blob v2 column -with table schema metadata `lance.blob.managed=true`, as in the -[table creation example](/management/table#managed-blobs-read-write): - -```python -from datetime import timedelta +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 -from lancedb import col -from lancedb.functions import udf import pyarrow as pa -@udf( - name="reverse_image", - python_version="3.12", - pip=["pyarrow==26.0.0"], - input_schema=pa.schema([lancedb.blob("image")]), - output_schema=lancedb.blob("reversed", nullable=False), -) -def reverse_image(image): - return b"missing" if image is None else image[::-1] - -function = db.create_function_async(reverse_image).wait( - timeout=timedelta(minutes=15) -) -table.add_columns({"reversed": function(image=col("image"))}) -result = table.refresh_column_async("reversed").wait( - timeout=timedelta(minutes=15) -) -assert result.rows_failed == 0 - -hits = table.search().select(["id", "reversed"]).with_row_id(True).to_arrow() -values = table.fetch_blobs("reversed", hits).to_pylist() +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 @@ -194,29 +310,139 @@ 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)`. -On deployments that support computed-column inputs, another Function can bind -to `col("reversed")`. 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. + +`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. + ## Declare the environment {#environment} -The function runs remotely, so its dependencies are part of its definition: +The function runs on the Enterprise service, not in your application, so its +dependencies are part of its definition: | | | | --- | --- | -| `pip` | requirements for the remote environment | +| `pip` | requirements for the function's execution environment | | `conda`, `conda_channels` | conda packages instead of pip; channels in priority order | | `env` | environment variables | -| `python_version` | remote Python major/minor, defaulting to yours | +| `python_version` | Python major/minor for the execution environment, defaulting to yours | | `gpu` | whether every execution requires a GPU | + +```python Python icon="python" +@udf(gpu=True) +def extract_frame(video: BlobReader, ts: float) -> bytes: + ... # runs only on a GPU-capable worker +``` + + These are part of the **immutable function version**. Changing a dependency produces a new version rather than altering the one already registered, so a column filled by version 1 is unaffected by version 2. @@ -246,6 +472,46 @@ The client version defaults `python_version`, so a function registered from a right and occasionally surprising. Pin it when the function is sensitive to it. +## Remote calls and credentials {#secrets} + +A function that calls an external API needs a credential without putting it +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`: + + +```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. + ## Failure handling {#failures} A function that raises fails the job. There is no per-row retry or skip policy @@ -274,6 +540,25 @@ In practice this means a function should be self-contained: take its inputs as arguments, import what it needs at module level, and avoid capturing state from 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: + + +```python Python icon="python" +import caption_worker # a sibling module with the model-loading logic + +@udf(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. + ## Drop it {#drop} `db.drop_function(name, version=...)` drops the function's name and the object diff --git a/docs/web/management/index.mdx b/docs/web/management/index.mdx index 21222f418..9fc02ad6b 100644 --- a/docs/web/management/index.mdx +++ b/docs/web/management/index.mdx @@ -64,7 +64,7 @@ Enterprise, it requests the server's view listing. See [Materialized views](/management/materialized-view) for creating one, and -[Refresh a materialized view](/feature-engineering/materialized-views) for keeping +[Refresh a materialized view](/feature-engineering/refresh-materialized-view) for keeping it current. ### Views {#views} diff --git a/docs/web/management/materialized-view.mdx b/docs/web/management/materialized-view.mdx index 221e02dcb..90283e198 100644 --- a/docs/web/management/materialized-view.mdx +++ b/docs/web/management/materialized-view.mdx @@ -5,10 +5,8 @@ description: "Create, open, list and drop a table whose contents are defined by icon: table keywords: ["materialized view", "create_materialized_view", "catalog", "ddl"] availability: - oss: available + embedded: unavailable enterprise: available - summary: >- - Both offerings support materialized views. See [Enterprise compatibility](#deployment) for connection and server requirements. --- A materialized view is a table whose contents are defined by a query over @@ -19,10 +17,10 @@ The result is an ordinary table: queryable, indexable, searchable, and present in `table_names()`. Nothing about reading it is special. This page covers creating and managing one. Keeping it current is -[Refresh a materialized view](/feature-engineering/materialized-views). +[Refresh a materialized view](/feature-engineering/refresh-materialized-view). -In SQL, see [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh#refresh-materialized-view) and [`SHOW MATERIALIZED VIEWS`](/sql/ddl/materialized-view#show). +In SQL, see [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh-materialized-view) and [`SHOW MATERIALIZED VIEWS`](/sql/ddl/materialized-view#show). ## Create a materialized view {#create} @@ -30,25 +28,25 @@ In SQL, see [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh#refresh-materialized- ```python Python icon="python" view = db.create_materialized_view( - "recent_docs", - source="documents", - select=["id", "title", "embedding"], - where="created_at > TIMESTAMP '2026-01-01 00:00:00'", + "frames_captioned", + source="frames", + select=["frame_id", "video_id", "ts", "caption"], + where="selected = true", ) ``` ```typescript TypeScript icon="square-js" -const view = await db.createMaterializedView("recent_docs", "documents", { - select: ["id", "title", "embedding"], - where: "created_at > TIMESTAMP '2026-01-01 00:00:00'", +const view = await db.createMaterializedView("frames_captioned", "frames", { + select: ["frame_id", "video_id", "ts", "caption"], + where: "selected = true", }); ``` -`source` names the table the view reads. With Python SDK 0.40.0, create that -table with stable row IDs before creating the view. The -[complete example](/feature-engineering/materialized-views#create-and-refresh) -shows the setup. `select`, `where` and `limit` define the query. +`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. ## Open, list and drop views {#manage} @@ -60,6 +58,30 @@ shows the setup. `select`, `where` and `limit` define the query. | refresh | `refresh` | `refresh` | `REFRESH MATERIALIZED VIEW` | | drop | `drop_table` | `dropTable` | `DROP TABLE` | +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). + On a local database, `list_materialized_views` reads table schemas to find views. On Enterprise, it asks the server for the view listing, as @@ -80,14 +102,12 @@ That also means dropping one removes stored rows, unlike dropping a 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). See -[Enterprise refreshes](/feature-engineering/materialized-views#availability) -for compatibility considerations when upgrading an existing pipeline. +[SQL interface](/sql/ddl/materialized-view). ## Related guides {#next} - + How a refresh works, and what it writes. diff --git a/docs/web/management/namespace.mdx b/docs/web/management/namespace.mdx index dda6b918f..99e53d793 100644 --- a/docs/web/management/namespace.mdx +++ b/docs/web/management/namespace.mdx @@ -5,11 +5,8 @@ description: "Grouping tables into a hierarchy, and addressing them through it." icon: folder-tree keywords: ["namespace", "catalog", "hierarchy", "directory namespace", "rest namespace"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Namespaces work in the embedded library, through directory or REST - catalogs, and in LanceDB Enterprise. --- import { @@ -22,7 +19,7 @@ import { } from '/snippets/connection.mdx'; LanceDB organizes Lance tables through a catalog-level abstraction defined by -the *namespace spec*. LanceDB OSS is an embedded library for accessing those +the *namespace spec*. LanceDB Embedded is an embedded library for accessing those tables, and LanceDB Enterprise is a multimodal lakehouse that provides shared compute and catalog services on top of the Lance format. If you're coming from traditional databases or lakehouses, you can think of a namespace as the catalog path that says where a table name lives. @@ -76,7 +73,7 @@ directory. Namespaces can nest inside it, as in this hierarchy: The hierarchy is logical, not a tree of folders: a directory namespace records it in a `__manifest` table in the root directory, and stores each table in a directory of its own there. -As a user of LanceDB OSS, you might never notice namespaces at first, because a plain connection +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: @@ -165,7 +162,7 @@ println!("Created table: {}", table.name()); -- For simple use cases in LanceDB OSS, you don't need to go too deep into namespaces. +- For simple use cases in LanceDB Embedded, you don't need to go too deep into namespaces. - To integrate LanceDB with external catalogs, understand how each namespace implementation resolves table names and locations in your organization's setup. @@ -243,8 +240,11 @@ let db = lancedb::connect_namespace("rest", properties) ``` [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 -contract can be used to interact with it. It does not serve the contract's `exists` routes, so checks such as `namespace_exists` -fail against it. For authentication examples in LanceDB Enterprise, visit +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 +`lancedb.connect_async("db://...")` support `namespace_exists` and `table_exists` +through the existing describe routes instead. For authentication examples in LanceDB Enterprise, visit the [Namespaces in SDKs](#namespaces-in-lancedb-enterprise) page. ## Best practices {#best-practices} diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index ed9883277..0b71fb315 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -5,12 +5,8 @@ description: "The object most operations act on: creating, opening, renaming, cl icon: table keywords: ["table", "create_table", "open_table", "clone", "rename", "drop"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Tables are created, evolved, versioned and dropped in the embedded library - and in LanceDB Enterprise. Renaming, cloning, dropping every table and pruning old - versions differ between the two. --- import { @@ -110,15 +106,40 @@ import { PyProcessResults as ProcessResults, TsProcessResults as TsProcessResults, RsProcessResults as RsProcessResults, + PyBlobApiSetup as BlobApiSetup, + TsBlobApiSetup as TsBlobApiSetup, + RsBlobApiImports as RsBlobApiImports, + RsBlobApiSetup as RsBlobApiSetup, PyBlobApiSchema as BlobApiSchema, TsBlobApiSchema as TsBlobApiSchema, RsBlobApiSchema as RsBlobApiSchema, PyBlobApiIngest as BlobApiIngest, + PyBlobApiBytes as BlobApiBytes, TsBlobApiIngest as TsBlobApiIngest, RsBlobApiIngest as RsBlobApiIngest, + PyBlobApiFiles as BlobApiFiles, + TsBlobApiFiles as TsBlobApiFiles, + RsBlobApiFiles as RsBlobApiFiles, + PyBlobApiFetch as BlobApiFetch, + TsBlobApiFetch as TsBlobApiFetch, + RsBlobApiFetch as RsBlobApiFetch, + PyBlobApiRanges as BlobApiRanges, + TsBlobApiRanges as TsBlobApiRanges, + RsBlobApiRanges as RsBlobApiRanges, + TsBlobApiBytesMode as TsBlobApiBytesMode, + PyLegacyBlobApiSchema as LegacyBlobApiSchema, + TsLegacyBlobApiSchema as TsLegacyBlobApiSchema, + RsLegacyBlobApiSchema as RsLegacyBlobApiSchema, + PyLegacyBlobApiIngest as LegacyBlobApiIngest, + TsLegacyBlobApiIngest as TsLegacyBlobApiIngest, + RsLegacyBlobApiIngest as RsLegacyBlobApiIngest, + PyLegacyBlobApiToPandas as LegacyBlobApiToPandas, + PyLegacyQueryToPandasKwargs as LegacyQueryToPandasKwargs, +} from '/snippets/multimodal.mdx'; +import { PyBlobApiToPandas as BlobApiToPandas, PyQueryToPandasKwargs as QueryToPandasKwargs, -} from '/snippets/multimodal.mdx'; +} from '/snippets/blob_pylance.mdx'; 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 @@ -189,14 +210,21 @@ await db.tableNames(); Each accepts `namespace_path` to act inside a [namespace](/management/namespace) rather than at the database root. -To find out whether a table exists, open it and handle the error, or look for -its name in a listing. A missing table raises `ValueError` on a local directory -or a deployment, and `lance_namespace.TableNotFoundError` on a connection from -`connect_namespace`. A listing returns one page of names at a time, so check -every page. Python's `table_exists` is no substitute: a local directory or a -deployment raises `NotImplementedError` for it, and on a connection from -`connect_namespace("dir", ...)` or `connect_namespace("rest", ...)` it fails with -an `AttributeError`. TypeScript has no `tableExists`. +For Python remote connections created with `lancedb.connect("db://...")`, use +`db.table_exists(["documents"])` to check whether a table exists. For an async +remote connection, use `await db.table_exists(["documents"])`. Include namespace +segments before the table name, for example `["analytics", "documents"]`. These +checks return `False` when the table is missing and propagate other errors, +including permission errors. + +Local synchronous directory connections still raise `NotImplementedError` for +`table_exists`. On a connection from `connect_namespace("dir", ...)` or +`connect_namespace("rest", ...)`, it fails with an `AttributeError`. For these +connections, open the table and handle the error, or look for its name in a +listing. A missing table raises `ValueError` on a local directory and +`lance_namespace.TableNotFoundError` on a connection from `connect_namespace`. +A listing returns one page of names at a time, so check every page. TypeScript +has no `tableExists`. ## Rename and clone tables {#rename-clone} @@ -223,7 +251,7 @@ set to the exact version a model saw. A shallow clone depends on the source's files continuing to exist. If the source is [compacted](/maintenance/compaction) past the retention window, the version -the clone points at can be pruned. Local OSS connections support shallow clones +the clone points at can be pruned. LanceDB Embedded connections support shallow clones only; `is_shallow=False` is not implemented. If the copy must outlive the source's history, copy its data into an independent table instead. A deployment that supports cloning also makes shallow clones only, and one whose catalog @@ -307,138 +335,307 @@ extension types and pseudo-columns. ## Multimodal data {#multimodal} -Binary data (images, audio, video, model artifacts) lives in the table -beside the structured columns and embeddings that describe it, and is governed -by the same versioning and search. +Store images, audio, video, and documents alongside structured columns and +embeddings in the same versioned table. -Small values go in an ordinary `binary` column. Large ones go in a **blob** -column, stored out of line so a scan over the other columns stays fast. See -[Data types](/sql/data-types#blobs) for how the two differ to a reader. +Use `blob` columns for these payloads. Small values stay inline in the data +file, up to 64 KiB by default, and larger values are stored outside it. -### Store binary data {#multimodal-store-binary-data} +### Blob columns {#multimodal-blob-v2} -To store binary data, define a binary Arrow field in your schema (`pa.binary()` in Python, `Binary` in TypeScript, and `DataType::Binary` in Rust). + +Blob V2 is in early access. + -#### 1\. Setup and imports {#multimodal-1-setup-and-imports} +A `blob` column keeps metadata separate from the payload bytes, so queries can +filter rows without loading the blobs. -First, import the necessary libraries for LanceDB and Arrow in your SDK. +Most queries return descriptors, which contain metadata about the blob instead +of its bytes. You can +[read the bytes in the query results](#multimodal-blob-query-results) or +[fetch them by row ID](#multimodal-read-blobs). + +In Python, plain `to_pandas()` scans can also return `BlobFile` handles when +`pylance` is installed. + +When you write raw bytes, Lance chooses a storage layout based on the payload +size. A descriptor's `kind` tells you which one was used: + +| Storage mode | `kind` | Default placement | Storage behavior | +| --- | --- | --- | --- | +| `Inline` | `0` | Up to 64 KiB | Stored in the main data file. | +| `Packed` | `1` | Above 64 KiB, up to 4 MiB | Packed with other blobs into a shared sidecar file, up to 1 GiB per file by default. | +| `Dedicated` | `2` | Above 4 MiB | Stored in its own raw sidecar file. | +| `Managed` | `4` or `5` | Out-of-line values when managed storage is enabled | Stored in a Lance-owned object independently of the data file. | + +Managed storage must be enabled separately. See +[Managed blobs](#managed-blobs) for details. `kind=5` identifies a Managed +object using an explicitly registered base. + +Lance uses the default thresholds unless you customize them. Explicitly +configured thresholds are stored in the table schema and preserved on append. + +#### Setup {#multimodal-blob-v2-setup} + +Import the SDK and open a local database. The examples in this section use `db`. - {MultimodalImports} + {BlobApiSetup} - {TsMultimodalImports} + {TsMultimodalImports}{"\n"}{TsBlobApiSetup} - {RsMultimodalImports} + {RsBlobApiImports}{"\n"}{RsBlobApiSetup} -#### 2\. Prepare data {#multimodal-2-prepare-data} +#### Define a blob schema {#multimodal-blob-v2-schema} -For this example, we'll create some dummy in-memory images. In a real application, you would read these from files or an API. The key is to convert your data (image, audio, etc.) into a raw `bytes` object. +Declare a blob column with `lancedb.blob()` in Python and TypeScript, or +`blob()` in Rust: - {CreateDummyData} + {BlobApiSchema} - {TsCreateDummyData} + {TsBlobApiSchema} - {RsCreateDummyData} + {RsBlobApiSchema} -#### 3\. Define the schema {#multimodal-3-define-the-schema} +#### Ingest blobs {#multimodal-blob-v2-ingest} -When creating the table, it is **highly recommended** to define the schema explicitly. This ensures that your binary data is correctly interpreted as a `binary` type by Arrow/LanceDB and not as a generic string or list. +Pass raw bytes for each blob value. In Python, a blob column accepts `bytes`. +In TypeScript, it accepts a `Buffer`. The Python example creates two JPEGs +with EXIF metadata, which we'll read using a blob handle below. - {DefineSchema} + {BlobApiIngest} - {TsDefineSchema} + {TsBlobApiIngest} - {RsDefineSchema} + {RsBlobApiIngest} -#### 4\. Ingest data {#multimodal-4-ingest-data} +#### Read bytes in query results {#multimodal-blob-query-results} -Now, create the table using the data and the defined schema. +Python and TypeScript can return blob bytes in query results without +collecting `_rowid`. Rust uses [`fetch_blobs`](#multimodal-read-blobs) with +row IDs instead. + +##### Python {#multimodal-blob-python} + +`to_list(blob_mode="bytes")` returns the `image` bytes from the `photos` table +above: - {IngestData} - - - - {TsIngestData} - - - - {RsIngestData} + {BlobApiBytes} -### Retrieve and use blobs {#multimodal-retrieve-and-use-blobs} +In the Python SDK, `Table.to_pandas()`, `Table.to_arrow()`, and the query builder +methods `to_pandas()`, `to_arrow()`, `to_list()`, and `to_batches()` accept a +`blob_mode` argument. Sync and async query builders support the same modes: -When you search your LanceDB table, you can retrieve the binary column just like any other metadata. +| `blob_mode` | `to_pandas()` | `to_arrow()` and `to_list()` | +| --- | --- | --- | +| `"lazy"` | Default. Plain scans return seekable `BlobFile` handles. Vector, full-text, hybrid, and ordered queries return descriptor dicts. | Default. Returns descriptors carrying `_lance_row_id` so the result table can be passed to `fetch_blobs` or `fetch_blob_files`. | +| `"descriptions"` | Returns descriptor dicts with `kind`, `position`, `size`, `blob_id`, and `blob_uri`. | Returns the 5-field descriptor without `_lance_row_id`. | +| `"bytes"` | Materializes each blob as `bytes` in the DataFrame. | Materializes each blob as `large_binary` in Arrow or `bytes` in Python dicts. | + +For supported local v2 blob projections, `to_pandas(blob_mode="bytes")` and +`to_pandas(blob_mode="descriptions")` use native Arrow conversion without +pylance. Pandas conversions that need the Lance scanner, including plain-scan +`"lazy"` handles and legacy blobs, still require pylance. `to_arrow()`, +`to_list()`, `to_batches()`, and the fetch methods do not require pylance. + +`blob_mode="bytes"` requires a LanceDB Embedded table snapshot, so Enterprise +and in-memory tables raise `NotImplementedError`. On an Enterprise table, +`Table.to_pandas()` and +`Table.to_arrow()` aren't supported, and a query's `to_pandas()` also raises in +the default `"lazy"` mode because it would open `BlobFile` handles. Query with +`blob_mode="descriptions"`, then read bytes with `fetch_blobs` or +`fetch_blob_files`. + +`blob_mode="bytes"` materializes top-level and struct-nested blob columns. It +raises `ValueError` when the selected columns include blobs +inside a list. Select those columns with `blob_mode="descriptions"`, or leave +them out of the projection. Extra keyword arguments on +`to_pandas()`, such as `split_blocks` and `self_destruct`, are forwarded to +PyArrow. + +###### Stream blob results {#multimodal-blob-batches} + +`to_batches(blob_mode="bytes")` fetches blob v2 payloads one batch at a time +and returns them as Arrow `large_binary` values. Iterate over the reader and +call `batch.to_pandas()` to convert each batch to a DataFrame without collecting +all payloads at once. + +For sync queries, call `query.to_batches(batch_size=64, blob_mode="bytes")` +and iterate with `for`. For async queries, call +`await query.to_batches(max_batch_length=64, blob_mode="bytes")` and iterate +with `async for`. Sync full-text and hybrid queries do not support +`to_batches()`. + +The default `"lazy"` mode returns descriptors and keeps automatic `_rowid` +columns visible for manual fetches. `"descriptions"` returns the five-field +descriptors. Both `"bytes"` and `"descriptions"` hide automatic row IDs; +explicitly requested row IDs remain visible. + +Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, +including no legacy blobs, blobs inside lists, Enterprise tables, or namespace +`QueryTable` pushdown. If concurrent writers can overwrite the table, use a +separate reader checked out to a fixed version before querying. Otherwise, +an overwrite can invalidate the row IDs used to fetch bytes and raise +`ValueError`. + +###### Optional pandas examples {#multimodal-blob-pandas} + +The lazy-handle calls below require pylance. The query example expects `tbl_async`, +`query_vector`, and a `video` column, which the `photos` table does not define. - {SearchData} - - - - {TsSearchData} - - - - {RsSearchData} + {BlobApiToPandas} -#### Convert bytes back to objects {#multimodal-convert-bytes-back-to-objects} - -Once you have the bytes back from the search result, you can decode them into the original format (for example, an image object or audio buffer). +Sync and async query builders accept the same `blob_mode` values: - {ProcessResults} + {QueryToPandasKwargs} + + + +##### TypeScript {#multimodal-blob-typescript} + +In TypeScript, `toArray()` and `toArrow()` accept a `blobMode` option: + +| `blobMode` | Result | +| --- | --- | +| `"descriptions"` | Default. Returns descriptors. | +| `"bytes"` | Returns each top-level blob as bytes, or `null` for a null blob. Blobs nested in a struct or list keep their descriptors. | + +With `"bytes"`, the rows and the bytes come from the same table version. If the +table changes while the query runs, the query runs again, up to three times: + + + + {TsBlobApiBytesMode} + + + +#### Read blobs on demand {#multimodal-read-blobs} + +Query the rows you want and pass their `_rowid` values to a fetch method. +`fetch_blob_files` opens a seekable handle and loads bytes only when you read. +The Python example opens the JPEG from the ingest step and reads its EXIF +Make tag with Pillow. TypeScript and Rust read the first bytes from the handle. + + + + {BlobApiFiles} - {TsProcessResults} + {TsBlobApiFiles} - {RsProcessResults} + {RsBlobApiFiles} +The other fetch methods load bytes directly: + +| Need | Python | TypeScript | Rust | +| --- | --- | --- | --- | +| Whole payloads for a set of rows | `fetch_blobs` | `fetchBlobs` | `fetch_blobs` | +| Byte slices across many rows in one call | `fetch_blob_ranges` | Not available. Use `fetchBlobFiles` and `readRanges`. | `fetch_blob_ranges` | + +- `fetch_blobs` returns the full bytes for each row ID in order. Null blobs + produce null entries, and empty blobs produce empty byte strings. +- `fetch_blob_files` loads bytes when you call `read`, `read_range`, or + `read_ranges`. Range reads don't move the file cursor. Null blobs produce + null handles. +- `fetch_blob_ranges` takes `(row_id, offset, length)` requests and returns one + slice per request, in order. A request list can repeat a row to read more + than one slice of that blob. + + + + {BlobApiFetch} + + + + {TsBlobApiFetch} + + + + {RsBlobApiFetch} + + + +Python and Rust read slices across rows with `fetch_blob_ranges`. On a handle, +`read_ranges` reads more than one slice of one blob. Python takes +`(offset, length)` pairs, TypeScript takes `{ start, end }` ranges with an +exclusive `end`, and Rust takes `start..end` ranges: + + + + {BlobApiRanges} + + + + {TsBlobApiRanges} + + + + {RsBlobApiRanges} + + + +#### Notes and limits {#multimodal-blob-notes} + +Blob fetches fail if any requested row ID is missing or deleted. With stable +row IDs enabled, IDs remain valid across compaction. + +A blob field can sit at the top level of the schema or inside a struct or list. +Struct-nested blob columns use dotted paths such as `clip.video` in the fetch +APIs. Blobs inside lists can be written and queried as descriptors. A table +row ID does not address one list element, so `blob_columns()`, `fetch_blobs`, +`fetch_blob_files`, and `blob_mode="bytes"` can't return those bytes. + +See the Lance [blob guide](https://lance.org/guide/blob/) for the storage format. + ### Managed blobs (Blob v2) {#managed-blobs} -Use `lancedb.blob()` for images, audio, videos, and other binary values whose -payloads should load separately from the rest of a row. Write Python `bytes` -normally. Set the table schema metadata `lance.blob.managed` to `true` to -store small values inline and larger values in managed objects under the table's `_blobs/` directory. Medium values can share a packed -object; large values use a dedicated object. +Set the table schema metadata `lance.blob.managed` to `true` on a table with +[`lancedb.blob()`](#multimodal-blob-v2) columns to store small values inline and +larger values in managed objects under the table's `_blobs/` directory. Medium +values can share a packed object, and large values use a dedicated object. The table owns these objects. You do not upload them separately, keep an object -catalog, or delete their files yourself. A descriptor records where to read the -bytes. Compaction preserves the descriptor and its payload object, so merging -table fragments does not rewrite the blob payloads. +catalog, or delete their files yourself. Compaction preserves each descriptor +and its payload object, so merging table fragments does not rewrite the blob +payloads. Use an SDK and Enterprise deployment that support Blob v2 Managed storage. @@ -484,22 +681,16 @@ assert by_id[1] == b"" assert len(by_id[2]) == 102400 ``` -`None` is a null value; `b""` is a present, empty blob. `fetch_blobs` returns -bytes in the order of the supplied row IDs. It materializes the selected -payloads, so fetch bounded batches when blobs are large. Row IDs belong to -their table; fetch them from the same table and snapshot that produced the -query result. - -Keep descriptors opaque in application code. Their representation can differ -between inline values, Managed objects, and externally referenced blobs. For -streaming and range reads, see the -[Lance blob guide](https://lance.org/guide/blob/). +`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 +descriptors opaque in application code, because their representation can differ +between inline values and Managed objects. #### Derived blobs and maintenance {#managed-blobs-lifecycle} Enterprise Functions can consume blob columns and return new blobs. Their output payloads are managed by the destination table. -Local tables can also derive blob columns with +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 @@ -509,92 +700,190 @@ any of its contained blobs is still referenced. ### Legacy large-binary blobs {#multimodal-large-blobs-blob-api} -The schema below describes the earlier large-binary Blob API. It is distinct -from the `lancedb.blob()` schema above; changing the field's metadata alone does -not migrate an existing column to Blob v2. - -For larger files like high-resolution images or videos, Lance provides a specialized **Blob API**. By using a large-binary Arrow type (`pa.large_binary()` in Python, `LargeBinary` in TypeScript, and `DataType::LargeBinary` in Rust) and specific metadata, you enable **lazy loading** and optimized encoding. This allows you to work with massive datasets without loading all binary data into memory upfront. +Use [`lancedb.blob()`](#multimodal-blob-v2) for new tables. The sections below +cover existing tables that use the V1 large-binary Blob API +(`pa.large_binary()` in Python, `LargeBinary` in TypeScript, and +`DataType::LargeBinary` in Rust with `{"lance-encoding:blob": "true"}` field +metadata). Changing a field's metadata alone does not migrate an existing V1 +column to Blob v2. #### 1\. Define a blob schema {#multimodal-1-define-a-blob-schema} -To use the Blob API, you must mark the column with `{"lance-encoding:blob": "true"}` metadata. +V1 blob columns use a `large_binary` field marked with `{"lance-encoding:blob": "true"}` metadata: - {BlobApiSchema} + {LegacyBlobApiSchema} - {TsBlobApiSchema} + {TsLegacyBlobApiSchema} - {RsBlobApiSchema} + {RsLegacyBlobApiSchema} #### 2\. Ingest large blobs {#multimodal-2-ingest-large-blobs} -You can then ingest data normally, and Lance will handle the optimized storage. +Write raw bytes to a V1 blob column: - {BlobApiIngest} + {LegacyBlobApiIngest} - {TsBlobApiIngest} + {TsLegacyBlobApiIngest} - {RsBlobApiIngest} + {RsLegacyBlobApiIngest} - -For more advanced usage, including random access and file-like reading of blobs, see the -Lance format's [blob API documentation](https://lance.org/guide/blob/). - - #### 3\. Convert blob tables to pandas {#multimodal-3-convert-blob-tables-to-pandas} -When you call `to_pandas()` on a local LanceDB table that contains Blob API columns, the `blob_mode` argument controls how those columns materialize. This is available in the Python SDK on local tables; remote tables raise `NotImplementedError`. - -`blob_mode` accepts: - -- `"lazy"` (default): returns blob columns as lazy `BlobFile` objects without eagerly materializing their payloads. Use this when you want to stream blob bytes on demand or only inspect a subset of rows. Namespace-backed local tables also use the Lance native blob-aware pandas conversion for lazy blobs; in-memory datasets fall back to the standard PyArrow `to_pandas()` path. -- `"bytes"`: eagerly materializes each blob as `bytes`. Use this when you need the raw payload in the DataFrame, for example to decode an image or audio clip in-process. -- `"descriptions"`: returns blob descriptors (offsets, sizes, and positions) instead of the data itself. Use this when you want to plan I/O without paying the cost of loading every blob. - -`"bytes"` is not supported on in-memory tables. - -Extra keyword arguments are forwarded to the underlying PyArrow / Lance pandas conversion, so you can also pass options like `split_blocks` or `self_destruct`: +On LanceDB Embedded tables with V1 blob columns, `to_pandas()` in Python accepts +`blob_mode` (`"lazy"`, `"bytes"`, or `"descriptions"`). Enterprise tables raise +`NotImplementedError`, and `"bytes"` is not supported on in-memory tables. +Extra keyword arguments such as `split_blocks` or `self_destruct` are forwarded +to the PyArrow / Lance pandas conversion: - {BlobApiToPandas} + {LegacyBlobApiToPandas} -Query builders also accept `blob_mode` on their `to_pandas()` method: - -- Plain scans support `"lazy"`, `"bytes"`, and `"descriptions"` with filters, projections, aliases, `limit`, and `offset`. -- Vector, FTS, hybrid, and ordered queries can't materialize blob columns through `to_pandas()`; omit blob columns from the projection for those query shapes. -- This works on both sync and async query builders. Extra PyArrow kwargs like `split_blocks` and `self_destruct` are still forwarded. +On query builders with V1 blob columns, plain scans support `"lazy"`, `"bytes"`, +and `"descriptions"`. Vector, FTS, hybrid, and ordered queries cannot +materialize V1 blob columns through `to_pandas()`, so omit those columns from +the projection: - {QueryToPandasKwargs} + {LegacyQueryToPandasKwargs} + + + +### Store binary data {#multimodal-store-binary-data} + +Use a `binary` column when the query should return the raw bytes. Declare it as `pa.binary()` in Python, `Binary` in TypeScript, and `DataType::Binary` in Rust. + +#### 1\. Setup and imports {#multimodal-1-setup-and-imports} + +Import LanceDB and Arrow in your SDK. + + + + {MultimodalImports} + + + + {TsMultimodalImports} + + + + {RsMultimodalImports} + + + +#### 2\. Prepare data {#multimodal-2-prepare-data} + +Encode each image or file into raw bytes before writing. + + + + {CreateDummyData} + + + + {TsCreateDummyData} + + + + {RsCreateDummyData} + + + +#### 3\. Define the schema {#multimodal-3-define-the-schema} + +Declare the schema explicitly so Arrow and LanceDB store the field as `binary` instead of inferring a string or integer list. + + + + {DefineSchema} + + + + {TsDefineSchema} + + + + {RsDefineSchema} + + + +#### 4\. Ingest data {#multimodal-4-ingest-data} + +Create the table from the rows and schema. + + + + {IngestData} + + + + {TsIngestData} + + + + {RsIngestData} + + + +### Retrieve binary data {#multimodal-retrieve-and-use-blobs} + +When you search the table, select the `binary` column alongside your metadata columns. + + + + {SearchData} + + + + {TsSearchData} + + + + {RsSearchData} + + + +#### Convert bytes back to objects {#multimodal-convert-bytes-back-to-objects} + +Decode the returned bytes into an image or media buffer in your application. + + + + {ProcessResults} + + + + {TsProcessResults} + + + + {RsProcessResults} ### Other modalities {#multimodal-other-modalities} -The `pa.binary()` and `pa.large_binary()` types are universal. You can use this same pattern for other types of multimodal data: - -- **Audio:** Read `.wav` or `.mp3` files as bytes. -- **Video:** Store video transitions or full clips using the Blob API. -- **PDFs/Documents:** Store the raw file content for document search. +For PDFs, audio recordings, and other files, keep searchable fields in separate +columns so you can filter rows before fetching blob bytes. ### bfloat16 {#multimodal-bfloat16} @@ -660,8 +949,8 @@ First, let's create a sample table with product data to demonstrate schema evolu Columns derived from existing data (SQL expressions over other columns) are -covered in [Data evolution](/feature-engineering/data-evolution), because -deriving values is a feature-engineering job rather than a schema one. +covered in [Create a computed column](/feature-engineering/add-computed-column), +because deriving values is a feature-engineering job rather than a schema one. #### Add columns with default values {#schema-add-columns-with-default-values} @@ -921,7 +1210,6 @@ on finding this information in a consistent place. Use them when they fit your u | --- | --- | --- | | `lancedb:description` | Human-readable description of the field. | `"CLIP embedding of the product image"` | | `lancedb:tag:` | User-defined key/value tag, where the suffix names the tag category. | `"lancedb:tag:model": "clip"` | -| `lancedb:logical-column` | Groups related columns into one logical column. For example, `feature_v1` and `feature_v2` might belong to the same logical column. | `"lancedb:logical-column": "feature"` | | `lancedb:status` | Life cycle state of the column: `production`, `candidate`, `deprecated`, or `archived`. | `"lancedb:status": "production"` | @@ -1253,7 +1541,7 @@ mixing in lower-level Lance file operations. **System Operations** System operations like `optimize()`, index updates, and table compaction also increment table version numbers. -In LanceDB OSS, `optimize()` can prune older versions based on its retention setting (`cleanup_older_than`, 7 days by default), +In LanceDB Embedded, `optimize()` can prune older versions based on its retention setting (`cleanup_older_than`, 7 days by default), which is when old-version files are removed and disk space is reclaimed. A deployment prunes them in the background when its configuration enables [cleanup](/maintenance/cleanup); `optimize()` is not available there. diff --git a/docs/web/management/view.mdx b/docs/web/management/view.mdx index de6cd38a5..e01120034 100644 --- a/docs/web/management/view.mdx +++ b/docs/web/management/view.mdx @@ -1,14 +1,12 @@ --- title: "Views" sidebarTitle: "View" -description: "A saved query, evaluated when read. The non-materialized counterpart to a materialized view." +description: "A saved query, evaluated when read." icon: eye keywords: ["view", "create view", "sql", "catalog"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports views when enabled for your Enterprise cluster; the embedded library cannot create them. --- A view saves a query that you can refer to by name. Reading the view executes diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 788dd6585..02ec850bb 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -4,25 +4,30 @@ sidebarTitle: "Quickstart" description: "Install LanceDB, create a table, and run your first vector search." icon: rocket --- -import { PyConnect, TsConnect, RsConnect, PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders, RsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; -import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartVectorSearch1, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1 } from '/snippets/quickstart.mdx'; +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'; -This quickstart uses a local database and works without an account or API key. +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. -Follow the steps below, or jump to the [complete examples](#code) to copy a runnable program. + +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 Polars to display the search results. TypeScript needs Node.js 22.18 or later to run the `.mts` example directly. +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. ```bash Python (pip) icon="python" -pip install lancedb polars +pip install lancedb pandas ``` ```bash Python (uv) icon="python" uv venv -uv pip install lancedb polars +uv pip install lancedb pandas ``` ```bash TypeScript icon="square-js" @@ -58,6 +63,33 @@ 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: + + +```bash Python (pip) icon="terminal" +pip install --pre \ + --extra-index-url https://pypi.fury.io/lancedb/ \ + --extra-index-url https://pypi.fury.io/lance-format/ \ + "lancedb[pylance]" +``` + +```bash Python (uv) icon="terminal" +uv pip install --prerelease allow \ + --index https://pypi.fury.io/lancedb/ \ + --index https://pypi.fury.io/lance-format/ \ + --index-strategy unsafe-best-match \ + "lancedb[pylance]" +``` + + +The LanceDB preview index contains old `pylance` releases; current Lance previews +are published to the `lance-format` index. By default, uv only considers versions +from the first index containing a package, which can select an old `pylance` or +backtrack to an older LanceDB release. `unsafe-best-match` searches all configured +indexes, like pip; use it only with indexes you trust. Install the extra rather +than an unconstrained `pylance` so LanceDB's minimum supported version is enforced. + Pre-release builds receive the same level of testing as stable releases, but their availability is not guaranteed for more than 6 months after release. For real-world workloads, we recommend you use the latest stable release @@ -84,7 +116,7 @@ uninstall the other first (`pip uninstall lancedb && pip install lancedb-compat` ## 2\. Connect to a database {#2-connect-to-a-lancedb-database} -### Use a local directory {#connect-via-local-directory-path} +### Local directory {#connect-via-local-directory-path} LanceDB creates an `ex_lancedb` directory to store your tables. No server is needed. @@ -102,10 +134,27 @@ LanceDB creates an `ex_lancedb` directory to store your tables. No server is nee -The [complete examples](#code) include the imports and entry points for each language. For Python's async API, see [Connecting to a database](/basics/connect). +For Python's async API, see [Connecting to a database](/basics/catalog). - -### Connect to LanceDB Enterprise {#connect-to-lancedb-enterprise} +### 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. + + + + {PyConnectObjectStorage} + + + {"import * as lancedb from \"@lancedb/lancedb\";\n\n"} + {TsConnectObjectStorage} + + + {"use lancedb::connect;\n\n"} + {RsConnectObjectStorage} + + + +### Enterprise {#connect-to-lancedb-enterprise} Use the database URI, API key, and endpoint provided by your administrator or the LanceDB team. Replace the placeholders below with those details. Use the deployment's region if provided; otherwise keep `us-east-1`. @@ -124,27 +173,20 @@ 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/connect#enterprise) for an example. +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 [Moving to LanceDB Enterprise](/basics/sdk#moving-to-enterprise). - - - -### Connect via object storage URIs {#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. - +Need a deployment? [Contact the LanceDB team](https://www.lancedb.com/contact). For differences between local and server execution, see [LanceDB Enterprise](/enterprise). ## 3\. Create a table and add data {#3-create-a-new-table} -Each row describes a character and stores a vector alongside their name, description, and stats. +Each row describes a frame from a robot video clip and stores an embedding alongside its video, caption, and quality stats. -These vectors are made up for this example. In your application, use an embedding model to generate vectors from your data. +These embeddings are made up for this example. In your application, use an embedding model to generate them from your data. - + {PyQuickstartData} @@ -159,7 +201,7 @@ These vectors are made up for this example. In your application, use an embeddin -Create a `characters` table from those records: +Create a `frames` table from those records: @@ -173,9 +215,9 @@ Create a `characters` table from those records: -This example uses overwrite mode so you can run it again. It replaces any existing `characters` table in the database you connect to. +This example uses overwrite mode so you can run it again. It replaces any existing `frames` table in the database you connect to. -Add one more character: +Add one more frame: @@ -191,11 +233,11 @@ Add one more character: ## 4\. Search the table {#4-semantic-search} -Find the two vectors closest to the query vector. This example uses a fixed vector; it does not call an embedding model. +Find the two embeddings closest to the query embedding. This example uses a fixed embedding; it does not call an embedding model. - {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 pandas` beforehand\nresult = (\n table.search(query_vector)\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .to_pandas()\n)\nprint(result)\n"} {TsQuickstartVectorSearch1} @@ -205,84 +247,109 @@ Find the two vectors closest to the query vector. This example uses a fixed vect -Merlin and Morgana come back first. Python and Rust display a Polars DataFrame; TypeScript displays an array of results. The `_distance` column measures how far each result is from your query vector, with smaller values indicating a closer match. +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. -## Complete examples {#code} +## 5\. Filter results {#5-curation} -Each example below creates the local database, adds four characters, and prints the two closest matches. Use the dependencies from step 1. - - -Save this as `quickstart.py` and run `python quickstart.py`. If you installed with uv, run `uv run quickstart.py`. +Combine vector search with a metadata filter, such as `stats.motion >= 4`, to curate results instead of just ranking them: - - {PyConnect} - {PyQuickstartData} - {PyQuickstartCreateTable} - {PyQuickstartAddData} - {PyQuickstartVectorSearch1} + + {"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} - - -Save this as `quickstart.mts` and run `node quickstart.mts` from the directory where you installed LanceDB. +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. + +## 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: - - {"import * as lancedb from \"@lancedb/lancedb\";\n\n"} - {TsConnect} - {TsQuickstartData} - {TsQuickstartCreateTable} - {TsQuickstartAddData} - {TsQuickstartVectorSearch1} + + {PyQuickstartAddFeature} + + + {TsQuickstartAddFeature} + + + {RsQuickstartAddFeature} - - -Replace `src/main.rs` with this program, then run `cargo run` from your project directory. The schema and Arrow conversion helpers are included. +Read it back like any other column: - - {"use lancedb::connect;\n\n"} - {RsQuickstartDefineStruct} - {"\n#[tokio::main]\nasync fn main() -> Result<(), Box> {\n"} - {RsConnect} - {RsQuickstartData} - {RsQuickstartCreateTable} - {RsQuickstartAddData} - {RsQuickstartVectorSearch1} - {"\nOk(())\n}\n"} + + {"features = table.search().select([\"frame_id\", \"video_id\", \"quality_score\"]).limit(10).to_pandas()\nprint(features)\n"} + + + {TsQuickstartQueryFeature} + + + {RsQuickstartQueryFeature} - -## Next steps {#next-steps} +See [Adding columns](/management/table#schema-add-new-columns) for more on this form. -You've created a table, added rows, and searched it. Continue with the guides below. +## 7\. Set up computed columns {#7-computed-columns} -### Filter results {#5-curation} +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: -Combine vector search with metadata filters, such as `stats.magic >= 4`. See [SQL filtering](/search/filtering). + + + {PyQuickstartComputedFeature} + + -### Extend your table {#extensions} +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: -#### Add a derived feature {#6-add-a-derived-feature} + + + {PyQuickstartComputedFeatureEnterprise} + + -Add columns calculated from existing fields. See [Adding columns](/management/table#schema-add-new-columns). +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. -#### Computed columns {#computed-columns} +## 8\. Store multimodal data {#8-store-multimodal-data} -Declare a column and choose when to fill or refresh it. See [Computed columns](/feature-engineering/add-computed-column). +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: -#### Store multimodal data {#7-store-multimodal-data} + + + {PyQuickstartMultimodalBytes} + + + {TsQuickstartMultimodalBytes} + + + {RsQuickstartMultimodalBytes} + + -Store images, audio, and other binary data alongside vectors and metadata. See [Multimodal data types](/management/table#multimodal). +See [Multimodal data types](/management/table#multimodal) for larger payloads and the Blob v2 column type, which avoids loading binary data on every scan. -#### Train on your data {#8-train} +## 9\. Train on your data {#9-train} -Read table data into PyTorch for training. See [Data loading](/training/data-loading). +Read table data into PyTorch, projecting and shuffling only the columns a training step needs: + + + + {PyQuickstartTraining} + + + +`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. + +## Where to go next {#next-steps} diff --git a/docs/web/reranking/index.mdx b/docs/web/reranking/index.mdx index 26db30442..1de69a2a8 100644 --- a/docs/web/reranking/index.mdx +++ b/docs/web/reranking/index.mdx @@ -5,10 +5,8 @@ description: "Choose a reranker, apply it to search candidates and evaluate rele icon: "sort-amount-down" keywords: ["re-ranking", "reranker", "rerank"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Reranking is available with OSS and Enterprise. --- import { diff --git a/docs/web/search/explain.mdx b/docs/web/search/explain.mdx index 383745e5b..653eecb52 100644 --- a/docs/web/search/explain.mdx +++ b/docs/web/search/explain.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Query Plans" description: "Inspect query execution, identify expensive work and compare changes." icon: "map" availability: - oss: available + embedded: available enterprise: available - summary: >- - Query plans are available in OSS and Enterprise. --- import { PyQueryPlan, TsQueryPlanBody, TsQueryPlanTail } from '/snippets/search_examples.mdx'; @@ -26,7 +24,7 @@ the query and adds measurements, including execution time and rows processed. Use the first to inspect query structure and the second to investigate work actually performed. Operator names and available measurements can differ -between OSS and Enterprise. SQL provides [EXPLAIN and EXPLAIN ANALYZE](/sql/dql/explain). +between LanceDB Embedded and LanceDB Enterprise. SQL provides [EXPLAIN and EXPLAIN ANALYZE](/sql/dql/explain). @@ -161,7 +159,7 @@ CoalesceBatchesExec: target_batch_size=1024 #### 5\. Data Retrieval {#5-data-retrieval} -- `RemoteTake` is the deployment's operator for this step; a local plan shows Lance's `Take` or a `LanceRead` over the selected row IDs, depending on the library version +- `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 @@ -328,25 +326,26 @@ ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier -### Distributed metrics on remote tables {#distributed-metrics-on-remote-tables} +### 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 local single-node output. Pass a `distributed_metrics` mode when you need to see how work was split across workers: +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 local `analyze_plan`. | Everyday performance checks and comparisons against a local plan. | +| `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. Local -Python queries ignore the distributed mode and return local measurements. +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 remote query +# Show a per-worker breakdown for a query on LanceDB Enterprise plan = ( table.search(query_embed) .where("identifier > 0 AND identifier < 1000000") diff --git a/docs/web/search/filtering.mdx b/docs/web/search/filtering.mdx index 50d37acc0..099aea73c 100644 --- a/docs/web/search/filtering.mdx +++ b/docs/web/search/filtering.mdx @@ -4,10 +4,8 @@ sidebarTitle: Filtering description: "Use predicates to select rows and control when filters apply to search." icon: "filter" availability: - oss: available + embedded: available enterprise: available - summary: >- - Metadata filtering is available in OSS and Enterprise. --- import { PyFilterSearch, TsFilterSearchBody, TsFilterSearchTail } from '/snippets/search_examples.mdx'; diff --git a/docs/web/search/full-text-search.mdx b/docs/web/search/full-text-search.mdx index bc174d5bd..0f9930dc3 100644 --- a/docs/web/search/full-text-search.mdx +++ b/docs/web/search/full-text-search.mdx @@ -4,10 +4,8 @@ sidebarTitle: Full-Text Search (FTS) description: "Find records by words, phrases or partial matches using a full-text index." icon: "book" availability: - oss: available + embedded: available enterprise: available - summary: >- - Full-text search is available in OSS and Enterprise. --- import { @@ -131,7 +129,7 @@ tbl ``` -OSS builds the index before the call returns. Enterprise builds it in the +LanceDB Embedded builds the index before the call returns. Enterprise builds it in the background. Wait for completion with Python’s `table.wait_for_index(["text_idx"])` or TypeScript’s `await tbl.waitForIndex(["text_idx"], 300)` before querying it. Use your actual index name if you chose a different one. @@ -187,7 +185,7 @@ values rather than probabilities. ### Keeping the index up to date {#keeping-the-index-up-to-date} -In OSS, new rows can remain outside the FTS index until you optimize the table. +In LanceDB Embedded, new rows can remain outside the FTS index until you optimize the table. Search includes those rows by scanning them, but that work can increase query latency. Call `optimize()` to update the index: @@ -207,7 +205,7 @@ tbl.optimize(OptimizeAction::All).await?; ``` -Choose an OSS maintenance schedule based on write volume and query latency. +Choose a LanceDB Embedded maintenance schedule based on write volume and query latency. Inspect index coverage with `table.index_stats(...)` and optimize when the unindexed data adds too much work. `.fast_search()` skips unindexed rows, so use it only when omitting recent records is acceptable. @@ -289,7 +287,7 @@ 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/...`. Model files must be installed where indexing and queries run: on your machine -for OSS, or on the Enterprise cluster for a remote table. +for LanceDB Embedded, or on the Enterprise cluster for an Enterprise table. Built-in stop-word removal supports Danish, Dutch, English, Finnish, French, German, Hungarian, Italian, Norwegian, Portuguese, Russian, Spanish, and Swedish. If you use another stemming language, such as Arabic, Greek, Romanian, Tamil, or Turkish, set `remove_stop_words=False` or pass `custom_stop_words`. @@ -748,6 +746,50 @@ const multiMatchBoostingResults = await table.query() ``` +### Search Columns as One Field {#combined-fields-search} + +`MultiMatchQuery` scores each column on its own and keeps the best match. +`CombinedFieldsQuery` treats the columns as one field (BM25F), so with the `AND` +operator a row matches when every term appears in at least one of the columns. +The query below finds `car` in `text` and `merrily` in `text2`, returning rows 1 +and 3. The same query with `MultiMatchQuery` returns no rows, because neither +column contains both words on its own. + +Every column must use the same tokenizer configuration. The two indexes in this +example are built with the same `FTS` settings. Boosts work as they do for +`MultiMatchQuery`: one weight per column, each at least 1. + + +```python Python icon="python" +from lancedb.query import CombinedFieldsQuery, FullTextOperator + +# Every term must appear in at least one of the two columns +combined_results = ( + table.search( + CombinedFieldsQuery("car merrily", ["text", "text2"], operator=FullTextOperator.AND), + ) + .select(["id", "text", "text2", "_score"]) + .limit(100) + .to_arrow().to_pandas() +) + +# Weight matches in text2 twice as much as matches in text +combined_boosting_results = ( + table.search( + CombinedFieldsQuery("car merrily", ["text", "text2"], boosts=[1.0, 2.0]), + ) + .select(["id", "text", "text2", "_score"]) + .limit(100) + .to_arrow().to_pandas() +) +``` + + +The typed `CombinedFieldsQuery` convenience class and this example are specific +to the Python SDK. Rust applications can construct the core query type exposed +by `lancedb::index::scalar`. TypeScript and Java do not yet provide typed +convenience entry points for this query. + ### Boolean Queries {#boolean-queries} LanceDB supports boolean logic in full-text search, allowing you to combine multiple queries using `and` and `or` operators. This is useful when you want to match documents that satisfy multiple conditions (intersection) or at least one of several conditions (union). diff --git a/docs/web/search/hybrid-search.mdx b/docs/web/search/hybrid-search.mdx index c3e453145..6b769b6a8 100644 --- a/docs/web/search/hybrid-search.mdx +++ b/docs/web/search/hybrid-search.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Hybrid Search" description: "Combine vector similarity and keyword matches in a single ranked result set." icon: "search" availability: - oss: available + embedded: available enterprise: available - summary: >- - Hybrid search is available in OSS and Enterprise. --- import { PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; @@ -84,9 +82,9 @@ import { Utf8 } from "apache-arrow"; ### 2\. Connect to LanceDB {#2-connect-to-lancedb} -Choose a local OSS connection or use your Enterprise connection details. +Choose a LanceDB Embedded connection or use your Enterprise connection details. -OSS +Embedded ```python Python icon="python" @@ -389,7 +387,7 @@ which relevant rows reach the candidate set before evaluating how a reranker orders them. Record latency as well as relevance: increasing candidate counts or applying a model-based reranker adds work. -Reranking runs in the application for both OSS and Enterprise connections. +Reranking runs in the application for both Embedded and Enterprise connections. See [Reranking](/reranking) for model-free fusion, model-based rerankers, custom implementations and score interpretation. diff --git a/docs/web/search/index.mdx b/docs/web/search/index.mdx index 9d439b204..86a0b1b17 100644 --- a/docs/web/search/index.mdx +++ b/docs/web/search/index.mdx @@ -4,10 +4,8 @@ sidebarTitle: Overview description: "Choose vector, full-text or hybrid search and return the records your application needs." icon: "list" availability: - oss: available + embedded: available enterprise: available - summary: >- - Vector, full-text and hybrid search are available in OSS and Enterprise. --- import { PyVectorSearch, TsVectorSearchBody, TsVectorSearchTail } from '/snippets/search_examples.mdx'; @@ -68,7 +66,7 @@ and removes it when finished. This query returns the puppy and dog records, ordered by vector distance. It searches the three-row table directly, without an ANN index or an embedding -service. For connection options, see [Connect](/basics/connect). +service. For connection options, see [Connect](/basics/catalog). @@ -106,9 +104,9 @@ in [Data loading](/training/data-loading). The SDK buffers Enterprise query responses before exposing batches. Set a query limit rather than relying on batch iteration alone to bound memory. -Direct Lance dataset access through Python's `table.to_lance()` is an OSS -interface. Use the SDK query builders for reads that need to work with both -OSS and Enterprise. +Direct Lance dataset access through Python's `table.to_lance()` is a LanceDB +Embedded interface. Use the SDK query builders for reads that need to work with +both LanceDB Embedded and LanceDB Enterprise. ## Investigate a slow query {#diagnostics} diff --git a/docs/web/search/realtime-read.mdx b/docs/web/search/realtime-read.mdx new file mode 100644 index 000000000..8f51995d3 --- /dev/null +++ b/docs/web/search/realtime-read.mdx @@ -0,0 +1,74 @@ +--- +title: "Real Time reads" +sidebarTitle: "Real Time 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 + 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). + +## Query a real time table {#query} + +Every query runs against the base table and the fresh tier (unflushed +memtables and SSTables) in parallel, and the two are merged into one result. +Fresh rows supersede base rows with the same primary key, so a row written a +moment ago is already reflected: + + +```python Python icon="python" +# continuing the `frames` table connected and written to in Real Time writes +import numpy as np + +query_vector = np.random.rand(frames.schema.field("embedding").type.list_size).astype("float32") + +frames.search(query_vector, vector_column_name="embedding").limit(10).to_list() +frames.search("gripper closing on a cup", fts_columns="caption").limit(10).to_list() +``` + + +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. + +## Read performance {#read-performance} + +Reads on an RTE table stay close to those on a fully compacted table, even +with the fresh tier at its fullest before compaction. + +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. + +| 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. + + +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 +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) +- [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 3519df553..8c43fd0e6 100644 --- a/docs/web/search/vector-search.mdx +++ b/docs/web/search/vector-search.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Vector Search" description: "Search by vector similarity, choose a distance metric and tune your queries." icon: "arrow-up-right-dots" availability: - oss: available + embedded: available enterprise: available - summary: >- - Vector search is available in OSS and Enterprise. --- import { @@ -131,7 +129,7 @@ Without a vector index, searches use `l2` by default. You can specify `cosine` o When a vector index exists, the search metric must match the metric used to build the index. If you explicitly request a different metric, LanceDB cannot use that -index and falls back to an exhaustive (brute-force) search. On LanceDB Cloud, the +index and falls back to an exhaustive (brute-force) search. On LanceDB Cloud (legacy hosted service), the brute-force KNN safety limit can reject that search on a large table instead of executing it. LanceDB Enterprise doesn't have the limit. @@ -235,7 +233,7 @@ The table below summarizes the behavior of `_distance` in search results based o See [vector indexes](/indexing/vector-index) for index configuration. The following sections cover query-time settings. -### Tuning `approx_mode` +### 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. @@ -623,7 +621,7 @@ tbl.create_index(metric="cosine", vector_column_name="vector") **Indexing matters more for multivector tables than for single-vector ones.** A brute-force scan over a multivector column has to compare every query vector to every document vector in every row, so the cost grows with both the row count and the number of vectors per row. -In LanceDB OSS, the query will just run, so a large unindexed multivector table can stall a process for a long time before returning results. +In LanceDB Embedded, the query will just run, so a large unindexed multivector table can stall a process for a long time before returning results. 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. diff --git a/docs/web/snippets/blob_pylance.mdx b/docs/web/snippets/blob_pylance.mdx new file mode 100644 index 000000000..eb0bd74d6 --- /dev/null +++ b/docs/web/snippets/blob_pylance.mdx @@ -0,0 +1,6 @@ +{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} + +export const PyBlobApiToPandas = "df_lazy = tbl.to_pandas()\n\ndf_bytes = tbl.to_pandas(blob_mode=\"bytes\")\n\ndf_desc = tbl.to_pandas(blob_mode=\"descriptions\")\n\narrow_bytes = tbl.to_arrow(blob_mode=\"bytes\")\n\ndf_typed = tbl.to_pandas(split_blocks=True, self_destruct=True)\n"; + +export const PyQueryToPandasKwargs = "df_lazy = (\n tbl.search().where(\"id = 1\").select([\"id\", \"video\"]).to_pandas(blob_mode=\"lazy\")\n)\n\ndf_bytes = await (\n tbl_async.query()\n .where(\"id = 1\")\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"bytes\")\n)\n\ndf_vec = (\n tbl.search(query_vector)\n .limit(2)\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"bytes\", split_blocks=True, self_destruct=True)\n)\n"; + diff --git a/docs/web/snippets/doc_storage_examples.mdx b/docs/web/snippets/doc_storage_examples.mdx index 47e2da787..f3b6be6a6 100644 --- a/docs/web/snippets/doc_storage_examples.mdx +++ b/docs/web/snippets/doc_storage_examples.mdx @@ -1,4 +1,8 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} +export const PyStorageCompactionTuning = "from lancedb import CompactionOptions\n\ndesired_fragment_bytes = 64 * 1024\naverage_row_bytes = 1024 # Estimate from representative rows.\noptions: CompactionOptions = {\n \"target_rows_per_fragment\": max(1, desired_fragment_bytes // average_row_bytes),\n \"batch_size\": 16,\n \"num_threads\": 1,\n}\ntable.optimize(compaction_options=options)\n"; + export const PyStorageRebuildVectorIndex = "from lancedb.index import IvfFlat\n\ntable.create_index(\n \"vector\",\n config=IvfFlat(distance_type=\"l2\", num_partitions=4),\n replace=True,\n)\n"; +export const RsStorageCompactionTuning = "use lancedb::table::{CompactionOptions, OptimizeAction};\n\nlet desired_fragment_bytes: usize = 64 * 1024;\nlet average_row_bytes: usize = 1024; // Estimate from representative rows.\nlet options = CompactionOptions {\n target_rows_per_fragment: (desired_fragment_bytes / average_row_bytes).max(1),\n batch_size: Some(16),\n num_threads: Some(1),\n ..Default::default()\n};\ntable\n .optimize(OptimizeAction::Compact {\n options,\n remap_options: None,\n })\n .await?;\n"; + diff --git a/docs/web/snippets/function.mdx b/docs/web/snippets/function.mdx index 728810e2a..fb7f907c3 100644 --- a/docs/web/snippets/function.mdx +++ b/docs/web/snippets/function.mdx @@ -2,6 +2,10 @@ export const PyFunctionApply = "from lancedb import col\n\ntable.add_columns({\"doubled\": version(value=col(\"value\"))})\n"; +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 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 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"; diff --git a/docs/web/snippets/integrations.mdx b/docs/web/snippets/integrations.mdx index 67bb654cf..dca2d0c1f 100644 --- a/docs/web/snippets/integrations.mdx +++ b/docs/web/snippets/integrations.mdx @@ -2,7 +2,7 @@ export const PyEmbeddingAwsUsage = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nimport pandas as pd\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\n\nmodel = get_registry().get(\"bedrock-text\").create()\n\nclass TextModel(LanceModel):\n text: str = model.SourceField()\n vector: Vector(model.ndims()) = model.VectorField()\n\ndf = pd.DataFrame({\"text\": [\"hello world\", \"goodbye world\"]})\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"bedrock-demo\"))\ntbl = db.create_table(\"test\", schema=TextModel, mode=\"overwrite\")\n\ntbl.add(df)\nrs = tbl.search(\"hello\").limit(1).to_pandas()\nprint(rs.head())\n"; -export const PyEmbeddingCohereUsage = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import EmbeddingFunctionRegistry\nfrom lancedb.pydantic import LanceModel, Vector\n\ncohere = (\n EmbeddingFunctionRegistry.get_instance()\n .get(\"cohere\")\n .create(name=\"embed-multilingual-v2.0\")\n)\n\nclass TextModel(LanceModel):\n text: str = cohere.SourceField()\n vector: Vector(cohere.ndims()) = cohere.VectorField()\n\ndata = [{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}]\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"cohere-demo\"))\ntbl = db.create_table(\"test\", schema=TextModel, mode=\"overwrite\")\ntbl.add(data)\n"; +export const PyEmbeddingCohereUsage = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import EmbeddingFunctionRegistry\nfrom lancedb.pydantic import LanceModel, Vector\n\ncohere = (\n EmbeddingFunctionRegistry.get_instance()\n .get(\"cohere\")\n .create(name=\"embed-multilingual-v3.0\")\n)\n\nclass TextModel(LanceModel):\n text: str = cohere.SourceField()\n vector: Vector(cohere.ndims()) = cohere.VectorField()\n\ndata = [{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}]\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"cohere-demo\"))\ntbl = db.create_table(\"test\", schema=TextModel, mode=\"overwrite\")\ntbl.add(data)\n"; export const PyEmbeddingColpaliSetup = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nimport pandas as pd\nimport requests\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, MultiVector\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"colpali-demo\"))\nfunc = get_registry().get(\"colpali\").create()\n\nclass Images(LanceModel):\n label: str\n image_uri: str = func.SourceField()\n image_bytes: bytes = func.SourceField()\n vector: MultiVector(func.ndims()) = func.VectorField()\n vec_from_bytes: MultiVector(func.ndims()) = func.VectorField()\n\ntable = db.create_table(\"images\", schema=Images)\nlabels = [\"cat\", \"dog\", \"horse\"]\nuris = [\n \"http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg\",\n \"http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg\",\n \"http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg\",\n]\nimage_bytes = [requests.get(uri).content for uri in uris]\ntable.add(\n pd.DataFrame({\"label\": labels, \"image_uri\": uris, \"image_bytes\": image_bytes})\n)\n"; diff --git a/docs/web/snippets/multimodal.mdx b/docs/web/snippets/multimodal.mdx index f41af6629..19180dfd0 100644 --- a/docs/web/snippets/multimodal.mdx +++ b/docs/web/snippets/multimodal.mdx @@ -1,28 +1,52 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyBlobApiIngest = "import lancedb\n\ndb = lancedb.connect(db_path_factory(\"blob_db\"))\n \n# Create sample data\ndata = [\n {\"id\": 1, \"video\": b\"fake_video_bytes_1\"},\n {\"id\": 2, \"video\": b\"fake_video_bytes_2\"}\n]\n \n# Create the table\ntbl = db.create_table(\"videos\", data=data, schema=schema)\n"; +export const PyBlobApiBytes = "rows = (\n tbl.search().where(\"id = 1\").select([\"id\", \"image\"]).to_list(blob_mode=\"bytes\")\n)\n"; -export const PyBlobApiSchema = "import pyarrow as pa\n\n# Define schema with Blob API metadata for lazy loading\nschema = pa.schema([\n pa.field(\"id\", pa.int64()),\n pa.field(\n \"video\", \n pa.large_binary(), \n metadata={\"lance-encoding:blob\": \"true\"} # Enable Blob API\n ),\n])\n"; +export const PyBlobApiFetch = "rows = tbl.search().select([\"id\"]).with_row_id(True).to_list()\nrow_ids = [row[\"_rowid\"] for row in rows]\npayloads = tbl.fetch_blobs(\"image\", row_ids)\n"; -export const PyBlobApiToPandas = "# Default: blob columns come back lazily\ndf_lazy = tbl.to_pandas()\n\n# Materialize blob bytes eagerly\ndf_bytes = tbl.to_pandas(blob_mode=\"bytes\")\n\n# Return descriptors instead of payloads\ndf_desc = tbl.to_pandas(blob_mode=\"descriptions\")\n\n# Forward extra kwargs to PyArrow's to_pandas\ndf_typed = tbl.to_pandas(split_blocks=True, self_destruct=True)\n"; +export const PyBlobApiFiles = "from PIL import ExifTags\n\nrows = tbl.search().where(\"id = 1\").select([\"label\"]).with_row_id(True).to_list()\nwith tbl.fetch_blob_files(\"image\", [rows[0][\"_rowid\"]])[0] as image_file:\n make = Image.open(image_file).getexif().get(ExifTags.Base.Make)\nprint(rows[0][\"label\"], make)\n"; -export const PyCreateDummyData = "# Create some dummy images\ndef create_dummy_image(color):\n img = Image.new('RGB', (100, 100), color=color)\n buf = io.BytesIO()\n img.save(buf, format='PNG')\n return buf.getvalue()\n\n# Create dataset with metadata, vectors, and image blobs\ndata = [\n {\n \"id\": 1,\n \"filename\": \"red_square.png\",\n \"vector\": np.random.rand(128).astype(np.float32),\n \"image_blob\": create_dummy_image('red'),\n \"label\": \"red\"\n },\n {\n \"id\": 2,\n \"filename\": \"blue_square.png\",\n \"vector\": np.random.rand(128).astype(np.float32),\n \"image_blob\": create_dummy_image('blue'),\n \"label\": \"blue\"\n }\n]\n"; +export const PyBlobApiIngest = "import io\nfrom PIL import Image\n\ndef jpeg_with_make(color, make):\n image = Image.new(\"RGB\", (8, 8), color=color)\n exif = Image.Exif()\n exif[0x010F] = make\n buf = io.BytesIO()\n image.save(buf, format=\"JPEG\", exif=exif)\n return buf.getvalue()\n\ntbl = db.create_table(\n \"photos\",\n data=[\n {\"id\": 1, \"label\": \"red\", \"image\": jpeg_with_make(\"red\", \"TestCam\")},\n {\"id\": 2, \"label\": \"blue\", \"image\": jpeg_with_make(\"blue\", \"OtherCam\")},\n ],\n schema=schema,\n mode=\"overwrite\",\n)\n"; -export const PyDefineSchema = "# Define schema explicitly to ensure image_blob is treated as binary\nschema = pa.schema([\n pa.field(\"id\", pa.int32()),\n pa.field(\"filename\", pa.string()),\n pa.field(\"vector\", pa.list_(pa.float32(), 128)),\n pa.field(\"image_blob\", pa.binary()), # Important: Use pa.binary() for blobs\n pa.field(\"label\", pa.string())\n])\n"; +export const PyBlobApiRanges = "slices = tbl.fetch_blob_ranges(\"image\", [(row_ids[0], 0, 2)])\n\nwith tbl.fetch_blob_files(\"image\", [row_ids[0]])[0] as image_file:\n parts = image_file.read_ranges([(0, 2)])\n"; + +export const PyBlobApiSchema = "import lancedb\nimport pyarrow as pa\n\nschema = pa.schema(\n [\n pa.field(\"id\", pa.int64()),\n pa.field(\"label\", pa.string()),\n lancedb.blob(\"image\"),\n ]\n)\n"; + +export const PyBlobApiSetup = "import lancedb\n\ndb = lancedb.connect(\"./blob_db\")\n"; + +export const PyCreateDummyData = "def create_dummy_image(color):\n img = Image.new(\"RGB\", (100, 100), color=color)\n buf = io.BytesIO()\n img.save(buf, format=\"PNG\")\n return buf.getvalue()\n\ndata = [\n {\n \"id\": 1,\n \"filename\": \"red_square.png\",\n \"vector\": np.random.rand(128).astype(np.float32),\n \"image_blob\": create_dummy_image(\"red\"),\n \"label\": \"red\",\n },\n {\n \"id\": 2,\n \"filename\": \"blue_square.png\",\n \"vector\": np.random.rand(128).astype(np.float32),\n \"image_blob\": create_dummy_image(\"blue\"),\n \"label\": \"blue\",\n },\n]\n"; + +export const PyDefineSchema = "schema = pa.schema(\n [\n pa.field(\"id\", pa.int32()),\n pa.field(\"filename\", pa.string()),\n pa.field(\"vector\", pa.list_(pa.float32(), 128)),\n pa.field(\"image_blob\", pa.binary()),\n pa.field(\"label\", pa.string()),\n ]\n)\n"; export const PyIngestData = "tbl = db.create_table(\"images\", data=data, schema=schema, mode=\"overwrite\")\n"; -export const PyMultimodalImports = "import lancedb\nimport pyarrow as pa\nimport pandas as pd\nimport numpy as np\nimport io\nfrom PIL import Image\n"; +export const PyLegacyBlobApiIngest = "import lancedb\n\ndb = lancedb.connect(\"./blob_db\")\n\n# Create sample data\ndata = [\n {\"id\": 1, \"video\": b\"fake_video_bytes_1\"},\n {\"id\": 2, \"video\": b\"fake_video_bytes_2\"},\n]\n\n# Create the table\ntbl = db.create_table(\"videos\", data=data, schema=schema)\n"; -export const PyProcessResults = "# Convert back to PIL Image\nfor _, row in results.iterrows():\n image_bytes = row['image_blob']\n image = Image.open(io.BytesIO(image_bytes))\n print(f\"Retrieved image: {row['filename']}, Size: {image.size}\")\n # You can now use 'image' with other libraries or display it\n"; +export const PyLegacyBlobApiSchema = "import pyarrow as pa\n\n# Define schema with Blob API metadata for lazy loading\nschema = pa.schema(\n [\n pa.field(\"id\", pa.int64()),\n pa.field(\n \"video\",\n pa.large_binary(),\n metadata={\"lance-encoding:blob\": \"true\"}, # Enable Blob API\n ),\n ]\n)\n"; -export const PyQueryToPandasKwargs = "# Plain scan query: blob_mode is supported end to end\ndf_lazy = (\n tbl.search()\n .where(\"id = 1\")\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"lazy\")\n)\n\n# Same call shape works on async query builders\ndf_bytes = await (\n tbl_async.query()\n .where(\"id = 1\")\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"bytes\")\n)\n\n# Vector / FTS / hybrid queries can't materialize blob columns,\n# so omit them from the projection\ndf_vec = (\n tbl.search(query_vector)\n .limit(10)\n .select([\"id\", \"vector\"])\n .to_pandas(split_blocks=True, self_destruct=True)\n)\n"; +export const PyLegacyBlobApiToPandas = "# Default: blob columns come back lazily\ndf_lazy = tbl.to_pandas()\n\n# Materialize blob bytes eagerly\ndf_bytes = tbl.to_pandas(blob_mode=\"bytes\")\n\n# Return descriptors instead of payloads\ndf_desc = tbl.to_pandas(blob_mode=\"descriptions\")\n\n# Forward extra kwargs to PyArrow's to_pandas\ndf_typed = tbl.to_pandas(split_blocks=True, self_destruct=True)\n"; -export const PySearchData = "# Search for similar images\nquery_vector = np.random.rand(128).astype(np.float32)\nresults = tbl.search(query_vector).limit(1).to_pandas()\n"; +export const PyLegacyQueryToPandasKwargs = "# Plain scan query: blob_mode is supported end to end\ndf_lazy = (\n tbl.search()\n .where(\"id = 1\")\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"lazy\")\n)\n\n# Same call shape works on async query builders\ndf_bytes = await (\n tbl_async.query()\n .where(\"id = 1\")\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"bytes\")\n)\n\n# Vector / FTS / hybrid queries can't materialize blob columns,\n# so omit them from the projection\ndf_vec = (\n tbl.search(query_vector)\n .limit(10)\n .select([\"id\", \"vector\"])\n .to_pandas(split_blocks=True, self_destruct=True)\n)\n"; -export const TsBlobApiIngest = "const blobData = lancedb.makeArrowTable(\n [\n { id: 1, video: Buffer.from(\"fake_video_bytes_1\") },\n { id: 2, video: Buffer.from(\"fake_video_bytes_2\") },\n ],\n { schema: blobSchema },\n);\nconst blobTable = await db.createTable(\"videos\", blobData, {\n mode: \"overwrite\",\n});\n"; +export const PyMultimodalImports = "import io\nimport lancedb\nimport numpy as np\nimport pyarrow as pa\nfrom PIL import Image\n"; -export const TsBlobApiSchema = "const blobSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Int64()),\n new arrow.Field(\n \"video\",\n new arrow.LargeBinary(),\n true,\n new Map([[\"lance-encoding:blob\", \"true\"]]),\n ),\n]);\n"; +export const PyProcessResults = "for _, row in results.iterrows():\n image_bytes = row[\"image_blob\"]\n image = Image.open(io.BytesIO(image_bytes))\n print(f\"Retrieved image: {row['filename']}, Size: {image.size}\")\n"; + +export const PySearchData = "query_vector = np.random.rand(128).astype(np.float32)\nresults = tbl.search(query_vector).limit(1).to_pandas()\n"; + +export const TsBlobApiBytesMode = "const withBytes = await blobTable\n .query()\n .select([\"id\", \"image\"])\n .toArray({ blobMode: \"bytes\" });\nconst firstImage: Uint8Array | null = withBytes[0].image;\n"; + +export const TsBlobApiFetch = "const payloads = await blobTable.fetchBlobs(\"image\", rowIds);\n"; + +export const TsBlobApiFiles = "const rows = await blobTable\n .query()\n .select([\"id\", \"label\"])\n .withRowId()\n .toArray();\nconst rowIds = rows.map((row) => row._rowid as bigint);\n\nconst [image] = await blobTable.fetchBlobFiles(\"image\", [rowIds[0]!]);\nconst header = await image!.readRange(0n, 6n);\nawait image!.close();\n"; + +export const TsBlobApiIngest = "const blobTable = await db.createEmptyTable(\"photos\", blobSchema, {\n mode: \"overwrite\",\n});\n\nawait blobTable.add([\n { id: 1n, label: \"door\", image: Buffer.from(\"inline_image_bytes\") },\n { id: 2n, label: \"window\", image: Buffer.from(\"second_image_bytes\") },\n]);\n"; + +export const TsBlobApiRanges = "const [secondImage] = await blobTable.fetchBlobFiles(\"image\", [rowIds[1]!]);\nconst parts = await secondImage!.readRanges([\n { start: 0n, end: 6n },\n { start: 7n, end: 12n },\n]);\nawait secondImage!.close();\n"; + +export const TsBlobApiSchema = "const blobSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Int64()),\n new arrow.Field(\"label\", new arrow.Utf8()),\n lancedb.blob(\"image\"),\n]);\n"; + +export const TsBlobApiSetup = "const db = await lancedb.connect(\"./blob_db\");\n"; export const TsCreateDummyData = "const createDummyImage = (color: string): Uint8Array => {\n const pngHeader = Uint8Array.from([137, 80, 78, 71, 13, 10, 26, 10]);\n return Buffer.concat([Buffer.from(pngHeader), Buffer.from(color, \"utf8\")]);\n};\n\nconst data = [\n {\n id: 1,\n filename: \"red_square.png\",\n vector: Array.from({ length: 128 }, (_, i) => (i % 16) / 16),\n image_blob: createDummyImage(\"red\"),\n label: \"red\",\n },\n {\n id: 2,\n filename: \"blue_square.png\",\n vector: Array.from({ length: 128 }, (_, i) => ((i + 8) % 16) / 16),\n image_blob: createDummyImage(\"blue\"),\n label: \"blue\",\n },\n];\n"; @@ -30,23 +54,41 @@ export const TsDefineSchema = "const schema = new arrow.Schema([\n new arrow.Fi export const TsIngestData = "const multimodalData = lancedb.makeArrowTable(data, { schema });\nconst tbl = await db.createTable(\"images\", multimodalData, {\n mode: \"overwrite\",\n});\n"; +export const TsLegacyBlobApiIngest = "const legacyBlobData = lancedb.makeArrowTable(\n [\n { id: 1, video: Buffer.from(\"fake_video_bytes_1\") },\n { id: 2, video: Buffer.from(\"fake_video_bytes_2\") },\n ],\n { schema: legacyBlobSchema },\n);\nconst legacyBlobTable = await db.createTable(\n \"legacy_videos\",\n legacyBlobData,\n {\n mode: \"overwrite\",\n },\n);\n"; + +export const TsLegacyBlobApiSchema = "const legacyBlobSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Int64()),\n new arrow.Field(\n \"video\",\n new arrow.LargeBinary(),\n true,\n new Map([[\"lance-encoding:blob\", \"true\"]]),\n ),\n]);\n"; + export const TsMultimodalImports = "import * as arrow from \"apache-arrow\";\nimport { Buffer } from \"node:buffer\";\nimport * as lancedb from \"@lancedb/lancedb\";\n"; export const TsProcessResults = "for (const row of results) {\n const imageBytes = row.image_blob as Uint8Array;\n console.log(\n `Retrieved image: ${row.filename}, Byte length: ${imageBytes.length}`,\n );\n}\n"; export const TsSearchData = "const queryVector = Array.from({ length: 128 }, (_, i) => (i % 16) / 16);\nconst results = await tbl.search(queryVector).limit(1).toArray();\n"; -export const RsBlobApiIngest = "let blob_rows = vec![\n (1_i64, b\"fake_video_bytes_1\".to_vec()),\n (2_i64, b\"fake_video_bytes_2\".to_vec()),\n];\n\nlet blob_schema = Arc::new(blob_schema);\nlet blob_batch = RecordBatch::try_new(\n blob_schema.clone(),\n vec![\n Arc::new(Int64Array::from_iter_values(blob_rows.iter().map(|row| row.0))),\n Arc::new(LargeBinaryArray::from_iter_values(\n blob_rows.iter().map(|row| row.1.as_slice()),\n )),\n ],\n)\n.unwrap();\nlet blob_reader: Box =\n Box::new(RecordBatchIterator::new(vec![Ok(blob_batch)].into_iter(), blob_schema));\nlet blob_table = db\n .create_table(\"videos\", blob_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; +export const RsBlobApiFetch = "let payloads = blob_table.fetch_blobs(\"image\", &row_ids).await.unwrap();\n"; -export const RsBlobApiSchema = "let blob_metadata = HashMap::from([(\n \"lance-encoding:blob\".to_string(),\n \"true\".to_string(),\n)]);\nlet blob_schema = Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\"video\", DataType::LargeBinary, true).with_metadata(blob_metadata),\n]);\n"; +export const RsBlobApiFiles = "let batches = blob_table\n .query()\n .with_row_id()\n .execute()\n .await\n .unwrap()\n .try_collect::>()\n .await\n .unwrap();\nlet row_ids = batches[0]\n .column_by_name(\"_rowid\")\n .unwrap()\n .as_any()\n .downcast_ref::()\n .unwrap()\n .values()\n .to_vec();\n\nlet handles = blob_table\n .fetch_blob_files(\"image\", &row_ids[..1])\n .await\n .unwrap();\nlet header = handles[0].as_ref().unwrap().read_range(0..6).await.unwrap();\nhandles[0].as_ref().unwrap().close().await.unwrap();\n"; + +export const RsBlobApiImports = "use std::sync::Arc;\n\nuse arrow_array::{\n Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, UInt64Array,\n};\nuse arrow_schema::{DataType, Field, Schema};\nuse futures_util::TryStreamExt;\nuse lancedb::blob::{BlobRangeRequest, blob};\nuse lancedb::connect;\nuse lancedb::database::CreateTableMode;\nuse lancedb::query::{ExecutableQuery, QueryBase};\n"; + +export const RsBlobApiIngest = "let blob_table = db\n .create_empty_table(\"photos\", blob_schema)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n\nlet input_schema = Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\"label\", DataType::Utf8, true),\n Field::new(\"image\", DataType::LargeBinary, true),\n]));\nlet input_batch = RecordBatch::try_new(\n input_schema.clone(),\n vec![\n Arc::new(Int64Array::from(vec![1_i64, 2_i64])),\n Arc::new(StringArray::from(vec![Some(\"door\"), Some(\"window\")])),\n Arc::new(LargeBinaryArray::from_iter_values([\n b\"inline_image_bytes\".as_slice(),\n b\"second_image_bytes\".as_slice(),\n ])),\n ],\n)\n.unwrap();\nlet input_reader: Box = Box::new(\n RecordBatchIterator::new(vec![Ok(input_batch)].into_iter(), input_schema),\n);\nblob_table.add(input_reader).execute().await.unwrap();\n"; + +export const RsBlobApiRanges = "let slices = blob_table\n .fetch_blob_ranges(\n \"image\",\n [\n BlobRangeRequest::new(row_ids[0], 0, 6),\n BlobRangeRequest::new(row_ids[1], 0, 6),\n BlobRangeRequest::new(row_ids[1], 7, 5),\n ],\n )\n .await\n .unwrap();\n\nlet second_handles = blob_table\n .fetch_blob_files(\"image\", &row_ids[1..2])\n .await\n .unwrap();\nlet second_image = second_handles[0].as_ref().unwrap();\nlet parts = second_image.read_ranges(&[0..6, 7..12]).await.unwrap();\nsecond_image.close().await.unwrap();\n"; + +export const RsBlobApiSchema = "let blob_schema = Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\"label\", DataType::Utf8, true),\n blob(\"image\", true),\n]));\n"; + +export const RsBlobApiSetup = "let db = connect(\"./blob_db\").execute().await.unwrap();\n"; export const RsCreateDummyData = "let create_dummy_image = |color: u8| -> Vec {\n let mut png_like = vec![137, 80, 78, 71, 13, 10, 26, 10];\n png_like.push(color);\n png_like\n};\n\nlet data = vec![\n (\n 1_i32,\n \"red_square.png\",\n vec![0.1_f32; 128],\n create_dummy_image(1),\n \"red\",\n ),\n (\n 2_i32,\n \"blue_square.png\",\n vec![0.2_f32; 128],\n create_dummy_image(2),\n \"blue\",\n ),\n];\n"; export const RsDefineSchema = "let schema = Schema::new(vec![\n Field::new(\"id\", DataType::Int32, false),\n Field::new(\"filename\", DataType::Utf8, false),\n Field::new(\n \"vector\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 128),\n false,\n ),\n Field::new(\"image_blob\", DataType::Binary, false),\n Field::new(\"label\", DataType::Utf8, false),\n]);\n"; -export const RsIngestData = "let schema = Arc::new(schema);\nlet image_batch = RecordBatch::try_new(\n schema.clone(),\n vec![\n Arc::new(Int32Array::from_iter_values(data.iter().map(|row| row.0))),\n Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.1))),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::(\n data.iter()\n .map(|row| Some(row.2.iter().copied().map(Some).collect::>())),\n 128,\n ),\n ),\n Arc::new(BinaryArray::from_iter_values(\n data.iter().map(|row| row.3.as_slice()),\n )),\n Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.4))),\n ],\n)\n.unwrap();\nlet image_reader: Box =\n Box::new(RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone()));\nlet table = db\n .create_table(\"images\", image_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; +export const RsIngestData = "let schema = Arc::new(schema);\nlet image_batch = RecordBatch::try_new(\n schema.clone(),\n vec![\n Arc::new(Int32Array::from_iter_values(data.iter().map(|row| row.0))),\n Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.1))),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::(\n data.iter()\n .map(|row| Some(row.2.iter().copied().map(Some).collect::>())),\n 128,\n ),\n ),\n Arc::new(BinaryArray::from_iter_values(\n data.iter().map(|row| row.3.as_slice()),\n )),\n Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.4))),\n ],\n)\n.unwrap();\nlet image_reader: Box = Box::new(\n RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone()),\n);\nlet table = db\n .create_table(\"images\", image_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; -export const RsMultimodalImports = "use std::collections::HashMap;\nuse std::sync::Arc;\n\nuse arrow_array::types::Float32Type;\nuse arrow_array::{\n BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch,\n RecordBatchIterator, StringArray,\n};\nuse arrow_schema::{DataType, Field, Schema};\nuse futures_util::TryStreamExt;\nuse lancedb::connect;\nuse lancedb::database::CreateTableMode;\nuse lancedb::query::{ExecutableQuery, QueryBase};\n"; +export const RsLegacyBlobApiIngest = "let legacy_blob_rows = vec![\n (1_i64, b\"fake_video_bytes_1\".to_vec()),\n (2_i64, b\"fake_video_bytes_2\".to_vec()),\n];\n\nlet legacy_blob_schema = Arc::new(legacy_blob_schema);\nlet legacy_blob_batch = RecordBatch::try_new(\n legacy_blob_schema.clone(),\n vec![\n Arc::new(Int64Array::from_iter_values(\n legacy_blob_rows.iter().map(|row| row.0),\n )),\n Arc::new(LargeBinaryArray::from_iter_values(\n legacy_blob_rows.iter().map(|row| row.1.as_slice()),\n )),\n ],\n)\n.unwrap();\nlet legacy_blob_reader: Box = Box::new(\n RecordBatchIterator::new(vec![Ok(legacy_blob_batch)].into_iter(), legacy_blob_schema),\n);\nlet legacy_blob_table = db\n .create_table(\"legacy_videos\", legacy_blob_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; + +export const RsLegacyBlobApiSchema = "let legacy_blob_metadata = HashMap::from([(\n \"lance-encoding:blob\".to_string(),\n \"true\".to_string(),\n)]);\nlet legacy_blob_schema = Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\"video\", DataType::LargeBinary, true).with_metadata(legacy_blob_metadata),\n]);\n"; + +export const RsMultimodalImports = "use std::collections::HashMap;\nuse std::sync::Arc;\n\nuse arrow_array::types::Float32Type;\nuse arrow_array::{\n Array, BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch,\n RecordBatchIterator, StringArray,\n};\nuse arrow_schema::{DataType, Field, Schema};\nuse futures_util::TryStreamExt;\nuse lancedb::connect;\nuse lancedb::database::CreateTableMode;\nuse lancedb::query::{ExecutableQuery, QueryBase};\n"; export const RsProcessResults = "for batch in &results {\n let filenames = batch\n .column_by_name(\"filename\")\n .unwrap()\n .as_any()\n .downcast_ref::()\n .unwrap();\n let images = batch\n .column_by_name(\"image_blob\")\n .unwrap()\n .as_any()\n .downcast_ref::()\n .unwrap();\n\n for row in 0..batch.num_rows() {\n let image_bytes = images.value(row);\n println!(\n \"Retrieved image: {}, Byte length: {}\",\n filenames.value(row),\n image_bytes.len()\n );\n }\n}\n"; diff --git a/docs/web/snippets/quickstart.mdx b/docs/web/snippets/quickstart.mdx index c7cf98e32..cd8976768 100644 --- a/docs/web/snippets/quickstart.mdx +++ b/docs/web/snippets/quickstart.mdx @@ -1,66 +1,66 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyQuickstartAddData = "table.add(\n [\n {\n \"id\": \"4\",\n \"name\": \"Morgana\",\n \"role\": \"Sorceress\",\n \"description\": \"Powerful sorceress of Avalon.\",\n \"stats\": {\"strength\": 2, \"magic\": 5, \"leadership\": 4, \"wisdom\": 4},\n \"vector\": [0.3, 0.9, 0.6, 0.8],\n }\n ]\n)\n"; +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 \"power_score\": \"cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)\"\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 PyQuickstartComputedFeature = "table.add_columns(computed={\"description_length\": \"length(description)\"})\ntable.refresh_column(\"description_length\")\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={\"description_length\": \"length(description)\"})\njob = table.refresh_column_async(\"description_length\")\njob.wait()\n"; +export const PyQuickstartComputedFeatureEnterprise = "table.add_columns(computed={\"caption_length\": \"length(caption)\"})\njob = table.refresh_column_async(\"caption_length\")\njob.wait()\n"; -export const PyQuickstartCreateTable = "table = db.create_table(\"characters\", data=data, mode=\"overwrite\")\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 \"characters\",\n data=data,\n mode=\"overwrite\",\n)\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.magic >= 4\")\n .select([\"name\", \"role\", \"description\", \"_distance\"])\n .limit(2)\n .to_polars()\n)\nprint(curated)\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 PyQuickstartData = "data = [\n {\n \"id\": \"1\",\n \"name\": \"King Arthur\",\n \"role\": \"King\",\n \"description\": \"Leader of Camelot and wielder of Excalibur.\",\n \"stats\": {\"strength\": 4, \"magic\": 1, \"leadership\": 5, \"wisdom\": 4},\n \"vector\": [0.7, 0.1, 0.9, 0.7],\n },\n {\n \"id\": \"2\",\n \"name\": \"Merlin\",\n \"role\": \"Wizard\",\n \"description\": \"Advisor and prophet with deep magical knowledge.\",\n \"stats\": {\"strength\": 2, \"magic\": 5, \"leadership\": 4, \"wisdom\": 5},\n \"vector\": [0.2, 0.9, 0.4, 0.9],\n },\n {\n \"id\": \"3\",\n \"name\": \"Sir Lancelot\",\n \"role\": \"Knight\",\n \"description\": \"Legendary knight known for courage and combat skill.\",\n \"stats\": {\"strength\": 5, \"magic\": 1, \"leadership\": 3, \"wisdom\": 3},\n \"vector\": [0.9, 0.1, 0.5, 0.4],\n },\n]\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 PyQuickstartMultimodalBytes = "from pathlib import Path\n\nimage_bytes = Path(\"data/sir-lancelot.jpg\").read_bytes()\n\nmultimodal_table = db.create_table(\n \"character_images\",\n data=[\n {\n \"id\": \"lancelot\",\n \"description\": \"Portrait of Sir Lancelot\",\n \"image\": image_bytes,\n \"vector\": [0.9, 0.1, 0.5, 0.4],\n }\n ],\n mode=\"overwrite\",\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([\"name\", \"role\", \"power_score\"]).to_polars()\nprint(features)\n"; +export const PyQuickstartQueryFeature = "features = table.search().select([\"frame_id\", \"video_id\", \"quality_score\"]).to_polars()\nprint(features)\n"; -export const PyQuickstartTraining = "import torch\nfrom lancedb.permutation import Permutation\n\ntable.add_columns(\n {\n \"magic\": \"cast(stats.magic as float)\",\n \"strength\": \"cast(stats.strength as float)\",\n }\n)\ndataset = Permutation.identity(table).select_columns([\"magic\", \"strength\"])\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, shuffle=True)\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 PyQuickstartVectorSearch1 = "# Search for examples similar to a \"wise magical advisor\"\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([\"name\", \"role\", \"description\", \"_distance\"])\n .limit(2)\n .to_polars()\n)\nprint(result)\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 examples similar to a \"wise magical advisor\"\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([\"name\", \"role\", \"description\", \"_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 = 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 TsQuickstartAddData = "await table.add([\n {\n id: \"4\",\n name: \"Morgana\",\n role: \"Sorceress\",\n description: \"Powerful sorceress of Avalon.\",\n stats: { strength: 2, magic: 5, leadership: 4, wisdom: 4 },\n vector: [0.3, 0.9, 0.6, 0.8],\n },\n]);\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: \"power_score\",\n valueSql:\n \"cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)\",\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(\"characters\", data, { mode: \"overwrite\" });\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.magic >= 4\")\n .select([\"name\", \"role\", \"description\", \"_distance\"])\n .limit(2)\n .toArray();\nconsole.table(curated);\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 id: \"1\",\n name: \"King Arthur\",\n role: \"King\",\n description: \"Leader of Camelot and wielder of Excalibur.\",\n stats: { strength: 4, magic: 1, leadership: 5, wisdom: 4 },\n vector: [0.7, 0.1, 0.9, 0.7],\n },\n {\n id: \"2\",\n name: \"Merlin\",\n role: \"Wizard\",\n description: \"Advisor and prophet with deep magical knowledge.\",\n stats: { strength: 2, magic: 5, leadership: 4, wisdom: 5 },\n vector: [0.2, 0.9, 0.4, 0.9],\n },\n {\n id: \"3\",\n name: \"Sir Lancelot\",\n role: \"Knight\",\n description: \"Legendary knight known for courage and combat skill.\",\n stats: { strength: 5, magic: 1, leadership: 3, wisdom: 3 },\n vector: [0.9, 0.1, 0.5, 0.4],\n },\n];\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/sir-lancelot.jpg\");\nconst imageSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Utf8()),\n new arrow.Field(\"description\", new arrow.Utf8()),\n new arrow.Field(\"image\", new arrow.Binary()),\n new arrow.Field(\n \"vector\",\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 id: \"lancelot\",\n description: \"Portrait of Sir Lancelot\",\n image: imageBytes,\n vector: [0.9, 0.1, 0.5, 0.4],\n },\n ],\n { schema: imageSchema },\n);\nconst multimodalTable = await db.createTable(\n \"character_images\",\n imageData,\n { mode: \"overwrite\" },\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([\"name\", \"role\", \"power_score\"])\n .toArray();\nconsole.table(features);\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 examples similar to a \"wise magical advisor\"\nconst queryVector = [0.2, 0.8, 0.4, 0.9];\n\nconst result = await table\n .search(queryVector)\n .select([\"name\", \"role\", \"description\", \"_distance\"])\n .limit(2)\n .toArray();\nconsole.table(result);\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![Character {\n id: \"4\".to_string(),\n name: \"Morgana\".to_string(),\n role: \"Sorceress\".to_string(),\n description: \"Powerful sorceress of Avalon.\".to_string(),\n stats: Stats {\n strength: 2,\n magic: 5,\n leadership: 4,\n wisdom: 4,\n },\n vector: [0.3, 0.9, 0.6, 0.8],\n}];\ntable\n .add(characters_to_reader(schema.clone(), &more_data))\n .execute()\n .await\n .unwrap();\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 \"power_score\".to_string(),\n \"cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)\"\n .to_string(),\n )]),\n None,\n )\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 = characters_schema();\nlet table = db\n .create_table(\"characters\", characters_to_reader(schema.clone(), &data))\n .mode(CreateTableMode::Overwrite)\n .execute()\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.magic >= 4\")\n .select(Select::Columns(vec![\n \"name\".to_string(),\n \"role\".to_string(),\n \"description\".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 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 Character {\n id: \"1\".to_string(),\n name: \"King Arthur\".to_string(),\n role: \"King\".to_string(),\n description: \"Leader of Camelot and wielder of Excalibur.\".to_string(),\n stats: Stats {\n strength: 4,\n magic: 1,\n leadership: 5,\n wisdom: 4,\n },\n vector: [0.7, 0.1, 0.9, 0.7],\n },\n Character {\n id: \"2\".to_string(),\n name: \"Merlin\".to_string(),\n role: \"Wizard\".to_string(),\n description: \"Advisor and prophet with deep magical knowledge.\".to_string(),\n stats: Stats {\n strength: 2,\n magic: 5,\n leadership: 4,\n wisdom: 5,\n },\n vector: [0.2, 0.9, 0.4, 0.9],\n },\n Character {\n id: \"3\".to_string(),\n name: \"Sir Lancelot\".to_string(),\n role: \"Knight\".to_string(),\n description: \"Legendary knight known for courage and combat skill.\".to_string(),\n stats: Stats {\n strength: 5,\n magic: 1,\n leadership: 3,\n wisdom: 3,\n },\n vector: [0.9, 0.1, 0.5, 0.4],\n },\n];\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 strength: i8,\n magic: i8,\n leadership: i8,\n wisdom: i8,\n}\n\n#[derive(Debug, Clone)]\nstruct Character {\n id: String,\n name: String,\n role: String,\n description: String,\n stats: Stats,\n vector: [f32; 4],\n}\n\nfn characters_schema() -> Arc {\n Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::LargeUtf8, false),\n Field::new(\"name\", DataType::LargeUtf8, false),\n Field::new(\"role\", DataType::LargeUtf8, false),\n Field::new(\"description\", DataType::LargeUtf8, false),\n Field::new(\n \"stats\",\n DataType::Struct(Fields::from(vec![\n Arc::new(Field::new(\"strength\", DataType::Int8, false)),\n Arc::new(Field::new(\"magic\", DataType::Int8, false)),\n Arc::new(Field::new(\"leadership\", DataType::Int8, false)),\n Arc::new(Field::new(\"wisdom\", DataType::Int8, false)),\n ])),\n false,\n ),\n Field::new(\n \"vector\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 4),\n false,\n ),\n ]))\n}\n\nfn characters_to_reader(\n schema: Arc,\n rows: &[Character],\n) -> Box {\n let ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.id.as_str()));\n let names = LargeStringArray::from_iter_values(rows.iter().map(|row| row.name.as_str()));\n let roles = LargeStringArray::from_iter_values(rows.iter().map(|row| row.role.as_str()));\n let descriptions =\n LargeStringArray::from_iter_values(rows.iter().map(|row| row.description.as_str()));\n\n let strength = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.strength));\n let magic = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.magic));\n let leadership = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.leadership));\n let wisdom = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.wisdom));\n let stats_fields: Vec = vec![\n Arc::new(Field::new(\"strength\", DataType::Int8, false)),\n Arc::new(Field::new(\"magic\", DataType::Int8, false)),\n Arc::new(Field::new(\"leadership\", DataType::Int8, false)),\n Arc::new(Field::new(\"wisdom\", DataType::Int8, false)),\n ];\n let stats = StructArray::new(\n stats_fields.into(),\n vec![\n Arc::new(strength),\n Arc::new(magic),\n Arc::new(leadership),\n Arc::new(wisdom),\n ],\n None,\n );\n\n let vectors = FixedSizeListArray::from_iter_primitive::(\n rows.iter()\n .map(|row| Some(row.vector.iter().copied().map(Some).collect::>())),\n 4,\n );\n\n let batch = RecordBatch::try_new(\n schema.clone(),\n vec![\n Arc::new(ids),\n Arc::new(names),\n Arc::new(roles),\n Arc::new(descriptions),\n Arc::new(stats),\n Arc::new(vectors),\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(\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 RsQuickstartMultimodalBytes = "use lancedb::arrow::arrow_array::BinaryArray;\n\nlet image_bytes = std::fs::read(\"data/sir-lancelot.jpg\").unwrap();\n\nlet image_schema = Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::LargeUtf8, false),\n Field::new(\"description\", DataType::LargeUtf8, false),\n Field::new(\"image\", DataType::Binary, false),\n Field::new(\n \"vector\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 4),\n false,\n ),\n]));\nlet image_vectors = [[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([\"lancelot\"])),\n Arc::new(LargeStringArray::from_iter_values([\n \"Portrait of Sir Lancelot\",\n ])),\n Arc::new(BinaryArray::from_iter_values([image_bytes.as_slice()])),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::(\n image_vectors\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(\"character_images\", image_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\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 \"name\".to_string(),\n \"role\".to_string(),\n \"description\".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 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 \"name\".to_string(),\n \"role\".to_string(),\n \"power_score\".to_string(),\n ]))\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{features:?}\");\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 examples similar to a \"wise magical advisor\"\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 \"name\".to_string(),\n \"role\".to_string(),\n \"description\".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 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/vscode_extension.mdx b/docs/web/snippets/vscode_extension.mdx new file mode 100644 index 000000000..df5618c38 --- /dev/null +++ b/docs/web/snippets/vscode_extension.mdx @@ -0,0 +1,4 @@ +{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} + +export const TsVscodeExtension = "import * as vscode from \"vscode\";\nimport {\n type Chunk,\n chunkMarkdown,\n indexChunks,\n openDatabase,\n searchChunks,\n} from \"./search\";\n\nexport async function activate(context: vscode.ExtensionContext) {\n // One index per workspace. `storageUri` is undefined when no folder is open.\n const storage = context.storageUri ?? context.globalStorageUri;\n\n // Transformers.js downloads the embedding model on first use. Keep it in\n // global storage so every workspace shares one copy and it survives\n // extension updates. Use `import()`: LanceDB loads the ES module build, and\n // `require()` would return a separate copy whose settings LanceDB never sees.\n const { env } = await import(\"@huggingface/transformers\");\n env.cacheDir = vscode.Uri.joinPath(context.globalStorageUri, \"models\").fsPath;\n\n context.subscriptions.push(\n vscode.commands.registerCommand(\"lancedbSearch.index\", async () => {\n const files = await vscode.workspace.findFiles(\n \"**/*.md\",\n \"**/node_modules/**\",\n );\n const chunks: Chunk[] = [];\n for (const file of files) {\n const bytes = await vscode.workspace.fs.readFile(file);\n // Store the file's URI, not a path relative to its folder: in a\n // multi-root workspace `findFiles` searches every folder, and only the\n // URI says which one a result came from.\n chunks.push(\n ...chunkMarkdown(file.toString(), new TextDecoder().decode(bytes)),\n );\n }\n if (chunks.length === 0) {\n vscode.window.showWarningMessage(\"No Markdown files to index.\");\n return 0;\n }\n\n await vscode.window.withProgress(\n {\n location: vscode.ProgressLocation.Notification,\n title: `Indexing ${files.length} Markdown files`,\n },\n async () => {\n await vscode.workspace.fs.createDirectory(storage);\n await indexChunks(await openDatabase(storage.fsPath), chunks);\n },\n );\n vscode.window.showInformationMessage(\n `Indexed ${chunks.length} paragraphs from ${files.length} files.`,\n );\n return chunks.length;\n }),\n\n // Called with a query (for example from a test or another extension), the\n // command returns the matching rows instead of showing a picker.\n vscode.commands.registerCommand(\n \"lancedbSearch.search\",\n async (query?: string) => {\n const text =\n query ??\n (await vscode.window.showInputBox({\n prompt: \"Search Markdown by meaning\",\n }));\n if (!text) {\n return [];\n }\n const results = await searchChunks(\n await openDatabase(storage.fsPath),\n text,\n );\n if (query !== undefined) {\n return results;\n }\n\n const picked = await vscode.window.showQuickPick(\n results.map((row) => {\n const uri = vscode.Uri.parse(row.path);\n return {\n label: `${vscode.workspace.asRelativePath(uri)}:${row.line + 1}`,\n description: `distance ${row._distance.toFixed(3)}`,\n detail: row.text,\n uri,\n line: row.line,\n };\n }),\n { placeHolder: text, matchOnDetail: true },\n );\n if (picked) {\n const editor = await vscode.window.showTextDocument(picked.uri);\n const start = new vscode.Position(picked.line, 0);\n editor.selection = new vscode.Selection(start, start);\n editor.revealRange(\n new vscode.Range(start, start),\n vscode.TextEditorRevealType.InCenter,\n );\n }\n return results;\n },\n ),\n );\n}\n\nexport function deactivate() {}\n"; + diff --git a/docs/web/snippets/vscode_search.mdx b/docs/web/snippets/vscode_search.mdx new file mode 100644 index 000000000..4d2423e7f --- /dev/null +++ b/docs/web/snippets/vscode_search.mdx @@ -0,0 +1,12 @@ +{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} + +export const TsVscodeChunk = "export type Chunk = { path: string; line: number; text: string };\n\n// Split a Markdown file into paragraphs, keeping the line each one starts on\n// so a search result can jump straight to it.\nexport function chunkMarkdown(filePath: string, content: string): Chunk[] {\n const lines = content.split(/\\r?\\n/);\n const chunks: Chunk[] = [];\n let start = 0;\n for (let i = 0; i <= lines.length; i++) {\n if (i === lines.length || lines[i].trim() === \"\") {\n const text = lines.slice(start, i).join(\"\\n\").trim();\n if (text) {\n chunks.push({ path: filePath, line: start, text });\n }\n start = i + 1;\n }\n }\n return chunks;\n}\n"; + +export const TsVscodeConnect = "// Pass an absolute directory, such as `context.storageUri.fsPath`. A relative\n// path resolves against the extension host's working directory, which is not\n// your workspace and may be read-only (on macOS it is usually `/`).\nexport async function openDatabase(storageDir: string) {\n return lancedb.connect(path.join(storageDir, \"lancedb\"));\n}\n"; + +export const TsVscodeImports = "import * as path from \"node:path\";\nimport * as lancedb from \"@lancedb/lancedb\";\nimport \"@lancedb/lancedb/embedding/transformers\";\nimport { Int32, Utf8 } from \"apache-arrow\";\n"; + +export const TsVscodeIndex = "export async function indexChunks(db: lancedb.Connection, chunks: Chunk[]) {\n // Runs all-MiniLM-L6-v2 locally through Transformers.js: no API key needed.\n const embedder = (await lancedb.embedding\n .getRegistry()\n .get(\"huggingface\")\n ?.create()) as lancedb.embedding.EmbeddingFunction;\n\n const schema = lancedb.embedding.LanceSchema({\n path: new Utf8(),\n line: new Int32(),\n text: embedder.sourceField(new Utf8()),\n vector: embedder.vectorField(),\n });\n\n // LanceDB fills in the `vector` column from `text` as the rows are written.\n return db.createTable(\"chunks\", chunks, { schema, mode: \"overwrite\" });\n}\n"; + +export const TsVscodeSearch = "export async function searchChunks(\n db: lancedb.Connection,\n query: string,\n limit = 5,\n) {\n // The table stores its embedding function in its metadata, so a text query\n // is embedded with the same model that embedded the rows.\n const table = await db.openTable(\"chunks\");\n return table\n .search(query)\n .select([\"path\", \"line\", \"text\", \"_distance\"])\n .limit(limit)\n .toArray();\n}\n"; + diff --git a/docs/web/sql/data-types.mdx b/docs/web/sql/data-types.mdx index 863212385..c5f362a6b 100644 --- a/docs/web/sql/data-types.mdx +++ b/docs/web/sql/data-types.mdx @@ -3,11 +3,12 @@ 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", "blob", "json"] +keywords: ["sql types", "arrow", "cast", "pseudo-columns", "vector", "json"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - There is no SQL type layer over Lance storage. The table provider hands DataFusion the dataset's Arrow schema directly, so a column is the same object to the query engine as it is to the format. @@ -61,7 +62,7 @@ describes the full mapping. ## Types SQL has no name for {#no-name} -Three column kinds you will meet that no SQL type name covers. +Some column kinds have no SQL type name. ### Vectors {#vectors} @@ -94,17 +95,6 @@ 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). -### Blobs {#blobs} - -A blob column is read either as its binary contents or as a **description**: a -pointer plus metadata, without fetching the bytes. That choice changes the -column's Arrow type, and therefore the schema your query sees. - - -The default reads blob columns as descriptions and other binary columns as -binary. A query selecting a blob column and expecting bytes gets a struct. - - ### bfloat16 {#bfloat16} Sixteen-bit floats in the bfloat16 layout, stored as `fixed_size_binary(2)`. diff --git a/docs/web/sql/ddl/database.mdx b/docs/web/sql/ddl/database.mdx new file mode 100644 index 000000000..6f4ab557f --- /dev/null +++ b/docs/web/sql/ddl/database.mdx @@ -0,0 +1,50 @@ +--- +title: "Database" +sidebarTitle: "Database" +description: "ATTACH DATABASE: bind a database to a storage location." +icon: database +keywords: ["attach database", "database", "sql", "ddl"] +availability: + embedded: unavailable + enterprise: available +--- + +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. + +## ATTACH DATABASE {#attach} + +```sql +ATTACH DATABASE analytics WITH (location = 'analytics') +ATTACH DATABASE IF NOT EXISTS analytics WITH (location = '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. + + +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. + + +`IF NOT EXISTS` makes the statement a no-op rather than an error when the +database is already attached. + + +A quoted name reaches characters a bare identifier cannot, such as +`` ATTACH DATABASE "team/search" WITH (location = 'team-search') ``. + + +## What to read next {#next} + + + + CREATE SCHEMA inside an attached database. + + + Creating tables once a database and namespace exist. + + diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index caf4c4cd5..1593c2d7b 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -17,6 +17,15 @@ 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 +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 `fixed_size_list`. `BIGINT` is refused. A parameter accepts nulls @@ -51,6 +60,20 @@ version is unaffected. the function is baked into an image before the version becomes usable. +## Call it {#call} + +Once registered, a function is callable by name in any query, the same as a +built-in scalar function: + +```sql +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 +committing to [a computed column](/sql/ddl/table#computed-column) that fills +from it. + ## SHOW FUNCTIONS {#show} ```sql diff --git a/docs/web/sql/ddl/grant.mdx b/docs/web/sql/ddl/grant.mdx new file mode 100644 index 000000000..85da7832a --- /dev/null +++ b/docs/web/sql/ddl/grant.mdx @@ -0,0 +1,77 @@ +--- +title: "Grant" +sidebarTitle: "Grant" +description: "GRANT and REVOKE: privileges on Secrets and Functions." +icon: user-lock +keywords: ["grant", "revoke", "privileges", "authorization", "sql", "ownership"] +--- + +Enterprise [SQL runs in LanceDB Enterprise.](/sql) + +```sql +GRANT [, ...] ON { SECRET | FUNCTION } TO [, ...] +GRANT [, ...] ON SCHEMA TO [, ...] +REVOKE [, ...] ON ... FROM [, ...] +``` + +```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 +``` + +## Privileges {#privileges} + +| Privilege | Allows | +| --- | --- | +| `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` | + + +`OWNERSHIP` cannot be revoked, only granted to someone else, which transfers +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. + +## 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. + +## 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. + +## What to read next {#next} + + + + The full privilege model, and how creation privileges resolve upward. + + + Creating the schemas these privileges apply to. + + diff --git a/docs/web/sql/ddl/index.mdx b/docs/web/sql/ddl/index.mdx index fb84e881c..dd900ee52 100644 --- a/docs/web/sql/ddl/index.mdx +++ b/docs/web/sql/ddl/index.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Index" description: "CREATE INDEX and DROP INDEX: one column, with the algorithm chosen by USING." icon: bolt keywords: ["create index", "drop index", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ## CREATE INDEX {#create} ```sql diff --git a/docs/web/sql/ddl/job.mdx b/docs/web/sql/ddl/job.mdx index 323dc1b1e..1b66e1e29 100644 --- a/docs/web/sql/ddl/job.mdx +++ b/docs/web/sql/ddl/job.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Job" description: "SHOW JOBS, 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"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - 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. @@ -32,7 +33,7 @@ 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) reports +Why rows failed. Reach for this when a [refresh](/sql/dml/refresh-column) reports fewer filled rows than you expected. **Errors and limits** diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index a8dfb8fbe..25fcab76e 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Materialized View" description: "CREATE MATERIALIZED VIEW and SHOW MATERIALIZED VIEWS; refreshing is a REFRESH statement." icon: table keywords: ["materialized view", "create materialized view", "show materialized views", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A materialized view stores a query's result as rows, kept current by a refresh. It is the counterpart to a [view](/sql/ddl/view), which stores only the query. @@ -28,6 +29,29 @@ 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 [Materialized views](/management/materialized-view#create). +{/* +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): + +```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 +WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 5) +``` + +`auto_refresh_enabled` and `auto_refresh_interval_seconds` work the same way +here as for a [computed column](/sql/ddl/table#automatic-refresh-options): +the interval is a minimum pacing after the last successful refresh, and +automatic execution needs the same server-side switch enabled. Omitting +`WITH` leaves automatic refresh at the server's default. +*/} + ## SHOW MATERIALIZED VIEWS {#show} ```sql @@ -45,9 +69,37 @@ on a `db://` connection. REFRESH MATERIALIZED VIEW chunks ``` -See [REFRESH](/sql/dml/refresh#refresh-materialized-view) for the full syntax, +See [REFRESH MATERIALIZED VIEW](/sql/dml/refresh-materialized-view) for the full syntax, and compatibility notes for older server versions. +{/* +Draft for automatic materialized-view refresh. Enable this section when the +server feature is released; see the note on "CREATE MATERIALIZED VIEW" above. + +## ALTER MATERIALIZED VIEW {#alter} + +```sql +ALTER MATERIALIZED VIEW frames_captioned SET auto_refresh_enabled = true; +ALTER MATERIALIZED VIEW frames_captioned SET auto_refresh_interval_seconds = 300; +ALTER MATERIALIZED VIEW frames_captioned SET auto_refresh_enabled = false; +``` + +The whole view toggles together; there is no per-output granularity the way +a multi-output Function column has one setting per output. SET takes effect +immediately and does not itself run a refresh: + +- **Disabling** prevents new automatic refreshes. An inflight one may still + finish, and `REFRESH MATERIALIZED VIEW` keeps working manually. +- **Re-enabling catches up the entire backlog in one pass**, the same as a + computed column's [automatic refresh](/sql/ddl/table#automatic-refresh-options): + the next scheduler tick picks up every source change accumulated since the + view was disabled, immediately, with no further write needed to trigger it. + +A materialized view's *initial* population, at `CREATE` or when the server +runs it, happens regardless of `auto_refresh_enabled`; only refreshes after +that are gated by the setting. +*/} + ## Dropping one {#drop} A materialized view **is** a table, so it is dropped with @@ -55,9 +107,8 @@ A materialized view **is** a table, so it is dropped with stored rows, unlike dropping a [view](/sql/ddl/view#drop). -**Enterprise job type:** `mat_view_refresh` for a refresh, or `sql` on a -deployment that rebuilds views through SQL. Dropping one runs the same job as -dropping any table, `drop_table` or `drop_object`. +**Enterprise job type for a refresh:** `sql`. Dropping, by contrast, runs the +same job as dropping any table, `drop_table` or `drop_object`. ## What to read next {#next} @@ -66,7 +117,7 @@ dropping any table, `drop_table` or `drop_object`. Creating one from the SDK. - - How a refresh works, locally and in LanceDB Enterprise. + + How a refresh works, in LanceDB Enterprise. diff --git a/docs/web/sql/ddl/namespace.mdx b/docs/web/sql/ddl/namespace.mdx index 472f3c1ad..dd50031ac 100644 --- a/docs/web/sql/ddl/namespace.mdx +++ b/docs/web/sql/ddl/namespace.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Namespace" description: "CREATE SCHEMA and DROP SCHEMA: the SQL spelling of namespace DDL." icon: folder-tree keywords: ["namespace", "schema", "create schema", "drop schema", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A [namespace](/management/namespace) is addressed in SQL as a `SCHEMA`, the standard's name for the same concept. @@ -46,6 +47,9 @@ default) states that requirement rather than changing it. ## What to read next {#next} + + Attaching the database a namespace lives in. + The SDK equivalent, and how a namespace fits the catalog hierarchy. diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index ecb522fe6..b1a5e8f1e 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Table" description: "CREATE, DESCRIBE, ALTER, CLONE and DROP TABLE." icon: table keywords: ["create table", "alter table", "drop table", "describe", "clone", "ddl"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ## CREATE TABLE {#create} ```sql @@ -16,6 +17,7 @@ CREATE TABLE recent AS SELECT * FROM documents WHERE created_at > now() - INTERV ``` 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`. @@ -49,7 +51,60 @@ 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: declaring one on a billion-row table costs what declaring one on an empty table -costs. [`REFRESH COLUMN`](/sql/dml/refresh) fills it. +costs. [`REFRESH COLUMN`](/sql/dml/refresh-column) fills it. + +{/* +Draft for automatic computed-column refresh. Enable this section when the +server feature is released. + +### Automatic refresh options {#automatic-refresh-options} + +```sql +ALTER TABLE t ADD COLUMN doubled AS value * 2 +WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300); + +ALTER TABLE t ALTER COLUMN doubled SET auto_refresh_enabled = false; +ALTER TABLE t ALTER COLUMN doubled SET auto_refresh_interval_seconds = 600; +ALTER TABLE t ALTER COLUMN doubled SET auto_refresh_enabled = true; +``` + +Automatic refresh is enabled by default. An explicitly configured interval is +stored in each computed output's field metadata; when omitted, the server +determines when to refresh. The interval must be a positive integer +and is minimum pacing after a successful refresh of that output; unchanged +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: + +```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); +ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_enabled = false; +``` + +Declaration settings initialize every output in the group; later SET commands +change one output. SET takes effect immediately and does not itself read or +write any row: + +- **Disabling** prevents new automatic submissions. Inflight jobs may still + finish, explicit `REFRESH COLUMN` keeps working, and rows written while + disabled commit with no computed value -- they do not queue anywhere + separate. +- **Re-enabling catches up the entire backlog in one pass.** The next + scheduler tick processes every row left unfilled since the column was + disabled, immediately, with no further write required to trigger it: a + column disabled for an hour and re-enabled fills everything that + accumulated during that hour, not just rows written after the moment it + is re-enabled. + +Column SUSPEND/RESUME syntax is not supported; `SET auto_refresh_enabled` is +the only toggle. The current setting is in the column's own field metadata, +`computed_column.auto_refresh_enabled`, readable from `DESCRIBE` or the +SDK's `table.schema` without submitting a job to ask. +*/} {/* Draft for the Functions release. @@ -81,12 +136,14 @@ ALTER TABLE t ADD COLUMN (label, score) AS classify(text) WITH (version = 'fv_1' ```sql ALTER TABLE t ADD COLUMN c AS f(x) FILTER (WHERE keep) WITH (version = 'fv_1') -ALTER TABLE t ADD COLUMN c AS f(x) WITH (num_workers = '2') +REFRESH COLUMN c ON t WITH (num_workers = 2) ``` -`WITH` on a plain computed column accepts only `version`. Resource options such -as `num_workers` apply to function columns, where there are workers to size. +Declaration `WITH` accepts `auto_refresh_enabled` and +`auto_refresh_interval_seconds`. Function bindings also accept `version` and +`branch`. Worker resource options such as `num_workers` belong on +`REFRESH COLUMN ... WITH (...)`. */} @@ -102,18 +159,20 @@ duplicates impossible. It tells the planner what to assume. The column must be declared `NOT NULL`. ```sql -ALTER TABLE t SET MEMWAL -ALTER TABLE t SET MEMWAL WITH (sharding = 'bucket', column = 'id', buckets = 4) -ALTER TABLE t SET MEMWAL WITH (maintained_indexes = '') -ALTER TABLE t UNSET MEMWAL +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 ``` -A write-ahead log makes small frequent writes cheap by batching them out of the +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 commit path. `sharding` and `buckets` spread the log so concurrent writers do not contend on one place; `bucket` sharding names its `column`, which must be the table's unenforced primary key, and inserts into the table then need a scalar index on that key. `maintained_indexes` chooses which indexes are kept -current against WAL rows. A table with a computed column cannot take a +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. diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index ec923063b..c6c1f7ecb 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -4,10 +4,11 @@ sidebarTitle: "View" description: "CREATE VIEW and DROP VIEW: a saved query, evaluated when read." icon: eye keywords: ["create view", "drop view", "sql", "catalog"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A view stores a **query**, not rows. Reading it runs the query against current data, so a view is never stale, and never faster than the query it wraps. It is the counterpart to a [materialized view](/sql/ddl/materialized-view), which diff --git a/docs/web/sql/dml/delete.mdx b/docs/web/sql/dml/delete.mdx index 429271de3..29b8f65d9 100644 --- a/docs/web/sql/dml/delete.mdx +++ b/docs/web/sql/dml/delete.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Delete" description: "DELETE FROM ... WHERE: rows are marked, not erased." icon: trash keywords: ["delete", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ```sql DELETE FROM documents WHERE created_at < TIMESTAMP '2025-01-01 00:00:00' ``` diff --git a/docs/web/sql/dml/insert.mdx b/docs/web/sql/dml/insert.mdx index 44007c6a3..71a7d1182 100644 --- a/docs/web/sql/dml/insert.mdx +++ b/docs/web/sql/dml/insert.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Insert" description: "INSERT INTO, including INSERT ... SELECT to move rows server-side." icon: plus keywords: ["insert", "insert into", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ```sql INSERT INTO documents (id, title) VALUES (1, 'Merlin'), (2, 'Arthur') diff --git a/docs/web/sql/dml/refresh.mdx b/docs/web/sql/dml/refresh-column.mdx similarity index 63% rename from docs/web/sql/dml/refresh.mdx rename to docs/web/sql/dml/refresh-column.mdx index d454069a9..db5d26475 100644 --- a/docs/web/sql/dml/refresh.mdx +++ b/docs/web/sql/dml/refresh-column.mdx @@ -1,19 +1,18 @@ --- -title: "REFRESH" -sidebarTitle: "REFRESH" -description: "Filling computed columns and bringing materialized views up to date." +title: "REFRESH COLUMN" +sidebarTitle: "REFRESH COLUMN" +description: "Filling a computed column: idempotent, scoped, and resumable." icon: arrows-rotate -keywords: ["refresh column", "refresh materialized view", "backfill", "cascade"] +keywords: ["refresh column", "backfill", "computed column"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - -LanceDB extensions with no DataFusion equivalent. They are what makes +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. -## REFRESH COLUMN {#refresh-column} - ```sql REFRESH COLUMN ON [TABLE] [WHERE ] @@ -33,7 +32,7 @@ can recompute values the failed run had already written. `WHERE` scopes the refresh, which is how you fill a slice and check it before committing to the whole table. -### Options {#refresh-column-options} +## Options {#options} | Option | Meaning | | --- | --- | @@ -62,39 +61,22 @@ memory and GPU options there. */} -## REFRESH MATERIALIZED VIEW {#refresh-materialized-view} - -```sql -REFRESH MATERIALIZED VIEW -``` - -```sql -REFRESH MATERIALIZED VIEW chunks -``` - -A refresh updates the view's stored result. Refresh views in dependency order, -starting with their source views. - - -Some older server versions accepted `WITH (full = true)` and `CASCADE`. -Those options are not accepted by the SQL implementation described here. -Use the basic statement above; do not assume that the options accepted by a -local SDK's `refresh()` method are also SQL options. - - ## Watching a refresh {#watching} -Both statements submit work that outlives the call. Track it with +A refresh submits work that outlives the call. Track it with [`SHOW JOBS`](/sql/ddl/job#show), and diagnose failures with [`SHOW ERRORS`](/sql/ddl/job#errors). ## See also {#see-also} - + The same operation from the SDKs, and what a refresh guarantees. Declaring the columns this fills. + + Bringing a view's stored result up to date, instead of a column. + diff --git a/docs/web/sql/dml/refresh-materialized-view.mdx b/docs/web/sql/dml/refresh-materialized-view.mdx new file mode 100644 index 000000000..8e1886f23 --- /dev/null +++ b/docs/web/sql/dml/refresh-materialized-view.mdx @@ -0,0 +1,50 @@ +--- +title: "REFRESH MATERIALIZED VIEW" +sidebarTitle: "REFRESH MATERIALIZED VIEW" +description: "Bringing a materialized view's stored result up to date." +icon: arrows-rotate +keywords: ["refresh materialized view", "cascade"] +availability: + embedded: unavailable + enterprise: available +--- + +A LanceDB extension with no DataFusion equivalent. + +```sql +REFRESH MATERIALIZED VIEW +``` + +```sql +REFRESH MATERIALIZED VIEW chunks +``` + +A refresh updates the view's stored result. Refresh views in dependency order, +starting with their source views. + + +Some older server versions accepted `WITH (full = true)` and `CASCADE`. +Those options are not accepted by the SQL implementation described here. +Use the basic statement above; do not assume that the options accepted by a +local SDK's `refresh()` method are also SQL options. + + +## Watching a refresh {#watching} + +A refresh submits work that outlives the call. Track it with +[`SHOW JOBS`](/sql/ddl/job#show), and diagnose failures with +[`SHOW ERRORS`](/sql/ddl/job#errors). + +## See also {#see-also} + + + + Creating the view this refreshes. + + + The same operation from the SDKs, and automatic refresh. + + + Filling a computed column, instead of a view. + + diff --git a/docs/web/sql/dml/update.mdx b/docs/web/sql/dml/update.mdx index b527d1ec0..68512e155 100644 --- a/docs/web/sql/dml/update.mdx +++ b/docs/web/sql/dml/update.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Update" description: "UPDATE ... SET ... WHERE, and why it does not recompute derived columns." icon: pen keywords: ["update", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ```sql UPDATE documents SET title = upper(title) WHERE category = 'film' ``` diff --git a/docs/web/sql/dql/aggregation.mdx b/docs/web/sql/dql/aggregation.mdx index fe02dc17a..cc41397b4 100644 --- a/docs/web/sql/dql/aggregation.mdx +++ b/docs/web/sql/dql/aggregation.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Aggregation" description: "GROUP BY, HAVING, and the aggregate function set." icon: layer-group keywords: ["group by", "having", "count", "sum", "avg", "aggregate", "approximate"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - Use SQL aggregates to summarize records, either across a whole table or within groups. Common examples include counts by category, totals and averages. diff --git a/docs/web/sql/dql/changes.mdx b/docs/web/sql/dql/changes.mdx new file mode 100644 index 000000000..012c06ff8 --- /dev/null +++ b/docs/web/sql/dql/changes.mdx @@ -0,0 +1,76 @@ +--- +title: "Changes since a version" +sidebarTitle: "Changes" +description: "CHANGES: read the rows appended to a table since an earlier version." +icon: clock-rotate-left +keywords: ["changes", "append", "incremental", "cdc", "version"] +availability: + embedded: unavailable + enterprise: available +--- + +`CHANGES` reads the rows appended to a table since an earlier +[version](/management/table#versioning), without rescanning rows that were +already there: + +```sql +SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 42) +``` + +This returns the rows appended after version 42, up to the table's current +version at the time the query runs. + +## Strictly append-only {#strict} + +The clause is named for what it requires, not just what it does: every +change to the table between the starting version and the current one must +be an append. If any of them inserted with changes other than a pure append +-- an update, a delete, a merge -- the query is refused rather than silently +returning an incomplete or wrong result. Re-run it with a later starting +version that is itself after the non-append write, or read the table in full +instead of incrementally. + +`INFORMATION => APPEND_ONLY` is the only supported value: it names what kind +of history the clause is willing to read, not a choice among several. `AT +(VERSION => ...)` takes a positive integer; there is no `AT (TIMESTAMP => +...)` form for this clause, unlike other version qualifiers. + +## Where the clause can go {#placement} + +It attaches to a table in `FROM`, including inside a subquery, a CTE, a join, +a set operation, or `EXPLAIN`: + +```sql +WITH recent AS ( + SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 42) +) +SELECT count(*) FROM recent + +SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 10) a +JOIN events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 20) b + ON a.id = b.id +``` + +Each occurrence of a table keeps its own starting version, even when the same +table is referenced more than once in one statement. + +## Unsupported forms {#refused} + +| | | +| --- | --- | +| `CHANGES (INFORMATION => DEFAULT)` | only `APPEND_ONLY` is supported | +| `AT (TIMESTAMP => ...)` | only `AT (VERSION => ...)` is supported | +| `AT (VERSION => 0)` | the starting version must be positive | +| `... END (VERSION => ...)` | not supported; the current version is always the end | +| `CHANGES ... TABLESAMPLE (...)` | cannot be combined on the same table reference | + +## What to read next {#next} + + + + CREATE, ALTER, CLONE and versioning basics. + + + The rest of the query grammar this clause attaches to. + + diff --git a/docs/web/sql/dql/dedupe.mdx b/docs/web/sql/dql/dedupe.mdx new file mode 100644 index 000000000..c82e72c13 --- /dev/null +++ b/docs/web/sql/dql/dedupe.mdx @@ -0,0 +1,99 @@ +--- +title: "DEDUPE" +sidebarTitle: "DEDUPE" +description: "The dedupe() table function: one representative row per near-duplicate group, scanned over the index." +icon: layer-group +keywords: ["dedupe", "vector_dedup", "sql", "deduplication", "near-duplicate", "table function"] +availability: + embedded: unavailable + enterprise: available +--- + +`dedupe` scans a vector column's [index](/indexing/vector-index) partitions +for rows closer than a distance threshold, resolves the overlapping pairs it +finds into duplicate groups, and returns one representative row per group -- +without a full pairwise scan or a shuffle. See +[`duplicate_pairs`](/sql/dql/duplicate-pairs) to inspect the pairs themselves +before committing to this resolution. + +```sql +SELECT * FROM dedupe(
, , + distance_threshold => + [, resolution => 'connected_components' | 'direct_representative'] + [, selection => 'all' | 'first' | 'random', count => , seed => ] +) +``` + +```sql +SELECT * FROM dedupe('frames', 'vec', distance_threshold => 0.02) +``` + + +Earlier releases spelled this `vector_dedup`; that name is rejected on +current deployments. + + +## Input {#input} + +| Argument | Type | Required | Meaning | +| --- | --- | --- | --- | +| table name | string literal | yes | the table to scan | +| 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. + +## Output {#output} + +One row per duplicate group, **in the table's own schema** -- every column of +`
`, including a BlobV2 column, comes through unchanged on the +representative row Lance selected for that group. Unlike +[`duplicate_pairs`](/sql/dql/duplicate-pairs#output), there is no fixed +`dedupe`-specific schema to document: the output schema is the source +table's schema. + +Because the result is already shaped like the table, it composes directly +into a new table or a materialized view: + +```sql +CREATE MATERIALIZED VIEW frames_deduped AS +SELECT * FROM dedupe('frames', 'vec', distance_threshold => 0.02) +``` + +## Resolution {#resolution} + +`resolution` chooses how overlapping pairs group together: + +| `resolution` | | +| --- | --- | +| `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} + +`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) +``` + +## What to read next {#next} + + + + Inspect the close pairs themselves instead of the resolved groups. + + + When to reach for this instead of exact-key deduplication. + + diff --git a/docs/web/sql/dql/duplicate-pairs.mdx b/docs/web/sql/dql/duplicate-pairs.mdx new file mode 100644 index 000000000..e8651a28c --- /dev/null +++ b/docs/web/sql/dql/duplicate-pairs.mdx @@ -0,0 +1,97 @@ +--- +title: "DUPLICATE_PAIRS" +sidebarTitle: "DUPLICATE_PAIRS" +description: "The duplicate_pairs() table function: every close pair in a vector column, scanned over the index." +icon: clone +keywords: ["duplicate_pairs", "vector_duplicate_pairs", "sql", "deduplication", "near-duplicate", "table function"] +availability: + embedded: unavailable + enterprise: available +--- + +`duplicate_pairs` scans a vector column's [index](/indexing/vector-index) +partitions for every pair of rows closer than a distance threshold, without a +full pairwise scan or a shuffle. It returns one row per close pair, not one +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 +SELECT * FROM duplicate_pairs('frames', 'vec', distance_threshold => 0.02) +``` + + +Earlier releases spelled this `vector_duplicate_pairs`; that name is rejected +on current deployments. + + +## Input {#input} + +| Argument | Type | Required | Meaning | +| --- | --- | --- | --- | +| table name | string literal | yes | the table to scan | +| vector column | string literal | yes | the indexed vector column to compare | +| `distance_threshold` | float | yes | maximum distance for a pair to count as close | +| `id_column` | column name | no | project this column's value instead of the internal row ID -- see [Application-level identifiers](#id-column) | +| `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'` | + +`resolution` is refused on `duplicate_pairs`: a pair has no notion of a group, +only [`dedupe`](/sql/dql/dedupe#input) accepts it. + +## Output {#output} + +One row per close pair found, in a fixed schema independent of the source +table: + +| Column | Type | Meaning | +| --- | --- | --- | +| `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 | + +### 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`. + +```sql +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 +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) +``` + +## What to read next {#next} + + + + Resolve these same pairs into one representative row per group. + + + When to reach for this instead of exact-key deduplication. + + diff --git a/docs/web/sql/dql/explain.mdx b/docs/web/sql/dql/explain.mdx index 1fc4dc191..151a861bc 100644 --- a/docs/web/sql/dql/explain.mdx +++ b/docs/web/sql/dql/explain.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Explain" description: "EXPLAIN, EXPLAIN ANALYZE and EXPLAIN VERBOSE: reading and measuring a plan from SQL." icon: map keywords: ["explain", "explain analyze", "explain verbose", "query plan"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ```sql EXPLAIN SELECT * FROM documents WHERE identifier < 1000 EXPLAIN ANALYZE SELECT * FROM documents WHERE identifier < 1000 diff --git a/docs/web/sql/dql/fts.mdx b/docs/web/sql/dql/fts.mdx index f6d5bc696..3dc6d3a3e 100644 --- a/docs/web/sql/dql/fts.mdx +++ b/docs/web/sql/dql/fts.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Full-Text Search" description: "The fts() table function: match, fuzzy, phrase, boolean, boost and multi-match queries from SQL." icon: magnifying-glass keywords: ["fts", "sql", "full text search", "fuzzy", "phrase", "boolean", "boost", "multi-match"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - Full-text search is a **table function**, `fts(table, query)`, rather than a predicate: it produces a relevance score alongside the matching rows, and a `WHERE` clause has nowhere to put one. The two string-literal arguments are diff --git a/docs/web/sql/dql/join.mdx b/docs/web/sql/dql/join.mdx index 5ccf49f50..ecc81ec31 100644 --- a/docs/web/sql/dql/join.mdx +++ b/docs/web/sql/dql/join.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Joins" description: "Combining rows from more than one table, including across namespaces." icon: link keywords: ["join", "inner", "left", "outer", "cross", "namespace"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - Use SQL joins to combine rows from two or more tables. ## The join types {#types} @@ -70,3 +71,29 @@ Avoid selecting blob or vector columns you do not need on either side of a join. The join multiplies rows before projection is applied in some plans, so a wide 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. diff --git a/docs/web/sql/dql/sampling.mdx b/docs/web/sql/dql/sampling.mdx index 03e518f1b..954247142 100644 --- a/docs/web/sql/dql/sampling.mdx +++ b/docs/web/sql/dql/sampling.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Sampling" description: "TABLESAMPLE: draw a random subset of a table, by rows or by fragments." icon: dice keywords: ["tablesample", "sampling", "bernoulli", "system", "repeatable", "random"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - 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. diff --git a/docs/web/sql/dql/select.mdx b/docs/web/sql/dql/select.mdx index cfc02c9c4..621061204 100644 --- a/docs/web/sql/dql/select.mdx +++ b/docs/web/sql/dql/select.mdx @@ -4,10 +4,11 @@ sidebarTitle: "SELECT" description: "Projection, filtering, ordering, and composing queries out of other queries." icon: table-columns keywords: ["select", "where", "order by", "limit", "cte", "union", "distinct"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ```sql [WITH cte AS (...)] SELECT [ALL | DISTINCT] select_expr [, ...] diff --git a/docs/web/sql/dql/subqueries.mdx b/docs/web/sql/dql/subqueries.mdx index 48887da72..3c5b5d11d 100644 --- a/docs/web/sql/dql/subqueries.mdx +++ b/docs/web/sql/dql/subqueries.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Subqueries" description: "Queries inside queries: scalar, IN, EXISTS, correlated, and derived tables." icon: code-branch keywords: ["subquery", "exists", "in", "correlated", "derived table", "lateral"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A subquery is allowed anywhere an expression or a relation is. ## As a relation {#derived} diff --git a/docs/web/sql/dql/window.mdx b/docs/web/sql/dql/window.mdx index 14b052861..e90f601c6 100644 --- a/docs/web/sql/dql/window.mdx +++ b/docs/web/sql/dql/window.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Window Functions" description: "Compute over a set of rows related to the current one, without collapsing them." icon: chart-simple keywords: ["window", "over", "partition by", "row_number", "rank", "lag", "lead"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - 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. diff --git a/docs/web/sql/functions.mdx b/docs/web/sql/functions.mdx index 9f7b8985b..9f6a25229 100644 --- a/docs/web/sql/functions.mdx +++ b/docs/web/sql/functions.mdx @@ -4,10 +4,11 @@ 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 --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - 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. @@ -77,6 +78,29 @@ 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 diff --git a/docs/web/sql/index.mdx b/docs/web/sql/index.mdx index 5793b5235..74561fca3 100644 --- a/docs/web/sql/index.mdx +++ b/docs/web/sql/index.mdx @@ -32,7 +32,7 @@ for batch in reader: SQL results arrive as Arrow record batches. Iterating over the reader avoids collecting the entire result in application memory. See -[Queries](/basics/query) for result handling. +[Read and manage results](/basics/sql#results) for more. ## Usage {#usage} @@ -47,6 +47,7 @@ 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` | | [Table](/sql/ddl/table) | `CREATE`, `DESCRIBE`, `ALTER`, `CLONE`, `DROP TABLE` | | [View](/sql/ddl/view) | `CREATE VIEW`, `DROP VIEW` | @@ -67,7 +68,8 @@ Draft for the Functions release. Add this row to the table above, after Index: | [Update](/sql/dml/update) | `UPDATE ... SET` | | [Delete](/sql/dml/delete) | `DELETE FROM` | | [Copy](/sql/dml/copy) | `COPY` (refused by recent deployment versions) | -| [Refresh](/sql/dml/refresh) | filling computed columns and materialized views | +| [Refresh column](/sql/dml/refresh-column) | filling a computed column | +| [Refresh materialized view](/sql/dml/refresh-materialized-view) | bringing a view's stored result up to date | ### DQL {#dql} @@ -80,6 +82,7 @@ Draft for the Functions release. Add this row to the table above, after Index: | [Aggregation](/sql/dql/aggregation) | `GROUP BY`, `HAVING`, the aggregate set | | [Window functions](/sql/dql/window) | `OVER`, framing, ranking and offset functions | | [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 | | [Explain](/sql/dql/explain) | `EXPLAIN`, `EXPLAIN ANALYZE`, `EXPLAIN VERBOSE` | diff --git a/docs/web/sql/operators.mdx b/docs/web/sql/operators.mdx index 3e27e6bb2..156fab3b0 100644 --- a/docs/web/sql/operators.mdx +++ b/docs/web/sql/operators.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Operators" description: "Comparison, logical and arithmetic operators, literals, and precedence." icon: plus-minus keywords: ["operators", "literals", "precedence", "null", "cast", "interval"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - LanceDB uses DataFusion's SQL operators. This page describes comparison, logical and arithmetic operators, literal values, type conversions and operator precedence. diff --git a/docs/web/sql/prepared-statements.mdx b/docs/web/sql/prepared-statements.mdx index 2b94b9c9a..cc0b1257e 100644 --- a/docs/web/sql/prepared-statements.mdx +++ b/docs/web/sql/prepared-statements.mdx @@ -4,10 +4,11 @@ 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 --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - 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. @@ -50,6 +51,13 @@ 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 diff --git a/docs/web/sql/scalar-functions.mdx b/docs/web/sql/scalar-functions.mdx index f44c935c4..1af20bb96 100644 --- a/docs/web/sql/scalar-functions.mdx +++ b/docs/web/sql/scalar-functions.mdx @@ -4,10 +4,11 @@ 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 --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - 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 @@ -98,6 +99,21 @@ functions supported by your deployment and inspect SQL 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 @@ -146,6 +162,44 @@ semantics and the simple tokenizer. 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 | diff --git a/docs/web/static/assets/images/enterprise/architecture.png b/docs/web/static/assets/images/enterprise/architecture.png deleted file mode 100644 index aa00854da..000000000 Binary files a/docs/web/static/assets/images/enterprise/architecture.png and /dev/null differ diff --git a/docs/web/static/assets/images/overview/lancedb-architecture.svg b/docs/web/static/assets/images/overview/lancedb-architecture.svg deleted file mode 100644 index 8fe3ff3c9..000000000 --- a/docs/web/static/assets/images/overview/lancedb-architecture.svg +++ /dev/null @@ -1,60 +0,0 @@ - - LanceDB OSS and Enterprise architecture - OSS runs the application and embedded library in one process with local disk or object storage. Enterprise separates query serving, read execution and caching, and indexing and background workers. The control plane governs the service. Enterprise persists tables in object storage. Both offerings use the Lance format, without automatically sharing storage. - - - - - - - - LanceDB OSS - Embedded library - - Application + - LanceDB library - Queries - Indexing - Maintenance - - - Local disk or object storage - - - LanceDB Enterprise - Distributed multimodal - lakehouse - - Applications + - LanceDB SDK - - - Query serving - - - - Read - execution - + caching - - Indexing + - background - work - - - - Durable object storage - - Control plane - Manages the service - - - Shared foundation: Lance format - diff --git a/docs/web/static/assets/images/overview/lancedb-distributed.png b/docs/web/static/assets/images/overview/lancedb-distributed.png new file mode 100644 index 000000000..893e884d6 Binary files /dev/null and b/docs/web/static/assets/images/overview/lancedb-distributed.png differ diff --git a/docs/web/static/assets/images/overview/lancedb-embedded.png b/docs/web/static/assets/images/overview/lancedb-embedded.png new file mode 100644 index 000000000..5aa36011b Binary files /dev/null and b/docs/web/static/assets/images/overview/lancedb-embedded.png differ diff --git a/docs/web/static/assets/images/overview/lancedb-suite.svg b/docs/web/static/assets/images/overview/lancedb-suite.svg index 0f860935d..676ba76cc 100644 --- a/docs/web/static/assets/images/overview/lancedb-suite.svg +++ b/docs/web/static/assets/images/overview/lancedb-suite.svg @@ -1,6 +1,6 @@ LanceDB suite - LanceDB OSS supports search. LanceDB Enterprise is a multimodal lakehouse for curation, feature engineering, search and retrieval, and training. Both are built on the Lance open lakehouse format for multimodal AI. + 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. @@ -54,7 +54,7 @@ - LanceDB OSS + LanceDB Embedded Search @@ -72,11 +72,11 @@ LanceDB Enterprise - Multimodal Lakehouse - Curation - Feature - Engineering - Search & - Retrieval + Search + Data exploration + & curation + Feature + engineering Training diff --git a/docs/web/static/assets/images/overview/training-data-lifecycle.svg b/docs/web/static/assets/images/overview/training-data-lifecycle.svg deleted file mode 100644 index 4998ee2e3..000000000 --- a/docs/web/static/assets/images/overview/training-data-lifecycle.svg +++ /dev/null @@ -1,49 +0,0 @@ - - Training data lifecycle - Four pillars of the LanceDB training data lifecycle: Curation, Feature Engineering, Search and Retrieval, and Training. - - - - - - - - - - - - - - - - - - - - - - - - - Curation - - - - - - Feature - Engineering - - - - - - Search & - Retrieval - - - - - - Training - diff --git a/docs/web/static/assets/logo/lance-logo-gray.png b/docs/web/static/assets/logo/lance-logo-gray.png new file mode 100644 index 000000000..79252d495 Binary files /dev/null and b/docs/web/static/assets/logo/lance-logo-gray.png differ diff --git a/docs/web/static/assets/logo/lance-logo-gray.svg b/docs/web/static/assets/logo/lance-logo-gray.svg deleted file mode 100644 index 764b68db7..000000000 --- a/docs/web/static/assets/logo/lance-logo-gray.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/docs/web/static/assets/logo/light-lancedb-logo.svg b/docs/web/static/assets/logo/light-lancedb-logo.svg index b0746745e..99e50467d 100644 --- a/docs/web/static/assets/logo/light-lancedb-logo.svg +++ b/docs/web/static/assets/logo/light-lancedb-logo.svg @@ -1,14 +1,3 @@ - - - - - - - - - - - - - - \ No newline at end of file + + + diff --git a/docs/web/tables/branching.mdx b/docs/web/tables/branching.mdx index 1e088c791..baf46b265 100644 --- a/docs/web/tables/branching.mdx +++ b/docs/web/tables/branching.mdx @@ -4,12 +4,8 @@ sidebarTitle: "Branch" description: "Fork isolated, writable lines of table history in LanceDB. Run experiments, backfills, and index rebuilds without disturbing production reads on main." icon: "code-branch" availability: - oss: available + embedded: available enterprise: available - summary: >- - Branches work in the embedded library and in LanceDB Enterprise. Comparing a - branch with `main` and promoting its new columns onto `main` is available - only in LanceDB Enterprise. --- import { PyConnect, @@ -63,18 +59,18 @@ scoped to that branch. The [comparison table](#branches-vs-tags-vs-versions) at the end of this page lays out when to reach for each. -Branches are supported on local and namespace-backed tables in LanceDB OSS, as -well as on LanceDB Enterprise (remote) tables. +Branches are supported on local and namespace-backed tables in LanceDB Embedded, +as well as on LanceDB Enterprise tables. ## Connect to a table {#connect-to-a-table} The branch API is identical no matter how you connect: only the connection -itself differs between OSS and Enterprise. Establish a connection (`db`) and open +itself differs between LanceDB Embedded and LanceDB Enterprise. Establish a connection (`db`) and open a `table` (see [Ingesting data](/ingestion)), then use the same branch calls in every example that follows. -### LanceDB OSS {#lancedb-oss} +### LanceDB Embedded {#lancedb-oss} Point LanceDB at a local directory (or an object-storage URI) to use it as an embedded library. @@ -99,7 +95,7 @@ embedded library. Enterprise -Branching on LanceDB Enterprise works the same way as on OSS, apart from the differences +Branching on LanceDB Enterprise works the same way as on LanceDB Embedded, apart from the differences noted below, but you connect to your Enterprise deployment with a `db://` URI, an API key, and your region and endpoint. Replace the placeholders below, including `us-east-1` if your @@ -282,7 +278,7 @@ inspects what a branch has changed relative to `main`, and `cherry_pick` place, without reissuing the branch's writes. -`diff` and `cherry_pick` work on Enterprise (remote) tables only. On a local +`diff` and `cherry_pick` work on LanceDB Enterprise tables only. On an Embedded table they fail as not supported: Python raises `NotImplementedError`, and TypeScript and Rust return an error. A cherry-pick promotes added columns; use the [upsert](#upsert-selected-branch-rows-into-main) or rerun patterns above for diff --git a/docs/web/tables/consistency.mdx b/docs/web/tables/consistency.mdx index 388655ff8..78aedb23f 100644 --- a/docs/web/tables/consistency.mdx +++ b/docs/web/tables/consistency.mdx @@ -4,11 +4,8 @@ sidebarTitle: "Consistency" description: "Understand when readers see changes and choose the freshness your application needs." icon: "water" availability: - oss: available + embedded: available enterprise: available - summary: >- - Configure read freshness in OSS and Enterprise. OSS checks for table updates; - Enterprise uses the connection setting to tighten its configured freshness bound. --- import { PyReadConsistency } from '/snippets/read_consistency.mdx'; @@ -26,11 +23,12 @@ for the experiment. ## Visibility of writes {#visibility} -In **OSS**, a table handle sees its own committed writes. By default, it does +In **LanceDB Embedded**, a table handle sees its own committed writes. By default, it does 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 **Enterprise**, readers use the service's configured freshness policy. +In **LanceDB Distributed** (provided by 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. @@ -40,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 | OSS | Enterprise | +| Setting | Embedded | Distributed | | --- | --- | --- | | **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 OSS table handle. On Enterprise it +`checkout_latest()` explicitly refreshes an Embedded table handle. On Distributed 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). @@ -80,7 +78,7 @@ a write completing and a reader seeing it. ## Learn more {#next} -- [Connect](/basics/connect): configure your client. +- [Connect](/basics/catalog): configure your client. - [Table versioning](/management/table#versioning): read and restore retained versions. - [Guarantees](/basics/guarantees): understand commit and failure boundaries. diff --git a/docs/web/tables/realtime-engine.mdx b/docs/web/tables/realtime-engine.mdx new file mode 100644 index 000000000..b3ca31346 --- /dev/null +++ b/docs/web/tables/realtime-engine.mdx @@ -0,0 +1,42 @@ +--- +title: "Real Time engine (RTE)" +sidebarTitle: "Real Time Engine" +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"] +availability: + embedded: unavailable + enterprise: available +--- + +## What is the real time engine? {#what-is-rte} + +Every write to a LanceDB table is normally a commit to the underlying Lance +dataset. That is ideal for bulk loads, but a stream of small upserts becomes a +stream of small commits, and each write is only visible once its commit lands. + +The real time engine (RTE) puts an LSM-style write tier in front of the table. +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} + +- **[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. + +## 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) diff --git a/docs/web/tools/cli.mdx b/docs/web/tools/cli.mdx new file mode 100644 index 000000000..97b058bd9 --- /dev/null +++ b/docs/web/tools/cli.mdx @@ -0,0 +1,217 @@ +--- +title: "LanceDB CLI" +sidebarTitle: "Command line" +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"] +--- + +Use the `lancedb` command-line client to open an interactive SQL shell, run a +statement, or execute a SQL file. SQL requires a running deployment with an +[Arrow Flight SQL endpoint](/basics/sql#sql-is-remote). + +## Install + +With Rust and Git installed, build the CLI from the LanceDB repository: + +```sh +git clone https://github.com/lancedb/lancedb.git +cd lancedb +cargo install --locked --path rust/lancedb/cli +``` + +Check the available options: + +```sh +lancedb --help +``` + +## Connect to a deployment + +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 +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 +endpoints for your deployment; they may use different hosts or ports. + +For API-key authentication, set the credential in your environment: + +```sh +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 +lancedb profile set production +lancedb +``` + + +Running `lancedb` opens the SQL shell when the default profile has a Flight SQL +endpoint. If no endpoint is configured, it prints usage and connection setup +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 +lancedb --profile local +``` + +This profile uses Flight SQL on port `10025` and HTTP on port `10024`. + +## Run SQL + +Execute a statement and exit: + +```sh +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 +SELECT COUNT(*) FROM documents; +SELECT id, text FROM documents LIMIT 10; +``` + +Run the file with: + +```sh +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. + +### Choose an output format + +For query results, `--format` accepts the following values: + +| Format | Output | +| --- | --- | +| `table` | A display table, the default | +| `csv` | Comma-separated values with column headers | +| `json` | A JSON array of rows | +| `ndjson` | One JSON row per line | + +```sh +lancedb --profile production --command 'SELECT id FROM documents' --format csv +``` + +## Use the SQL shell + +End SQL statements with a semicolon. Enter `\?` to see the shell's commands. + +| Command | Purpose | +| --- | --- | +| `\dt` | List tables | +| `\d documents` | Show a table's columns and indexes | +| `\di` | List indexes | +| `\dj` | List jobs | +| `\c analytics` | Connect to another database | +| `\e` | Edit the query buffer in an external editor | +| `\watch 2` | Repeat the last query or listing every two seconds | +| `\q` | Exit the shell | + +Add `+` to `\dt`, `\d`, or `\di` for more detail. Use Ctrl+C to cancel the +current input or stop watching a query, and Ctrl+D to exit. + +Large interactive results use a pager. Set `NO_PAGER=1` to disable paging. + +### Inspect jobs with SQL + +```sh +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. + +## Manage profiles + +Profiles are stored in `~/.lancedb/config.toml`. The CLI reuses existing +Enterprise profiles and cached OAuth sessions. + +```sh +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 +`--sql-server-url` override the selected profile. + +Put each command's flags after that command. For example, use +`lancedb auth login --profile production` or `lancedb profile edit production +--database staging`. + +## Authenticate with OAuth + +To use OAuth, configure an `oidc` table in the selected profile with your +identity provider's settings. For example, add the following to +`~/.lancedb/config.toml` for a device-code login: + +```toml +[profiles.production.oidc] +flow = "device_code" +issuer_url = "https://identity.example.com" +client_id = "YOUR_CLIENT_ID" +scopes = ["openid", "offline_access"] +``` + +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 +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 +production` to clear the profile's cached session. + +See [authentication](/enterprise/authentication) for identity provider setup and +available authentication methods. + +## Configure TLS + +To trust a private certificate authority, pass its PEM certificate: + +```sh +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 +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/data-loading.mdx b/docs/web/training/data-loading.mdx index 89e546257..47a3a6703 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -1,38 +1,13 @@ --- -title: "Loading Data for Model Training" -sidebarTitle: "Data Loading & Shuffles" -description: "Stream, shuffle, transform, and resume model training data with LanceDB." +title: "PyTorch Data Loader" +sidebarTitle: "PyTorch Data Loader" +description: "Stream, shuffle, transform, and resume model training data with StreamingDataset." icon: boxes-stacked availability: - oss: available + embedded: available enterprise: available - summary: >- - Streaming, shuffling and resuming training data work with local, - object-storage and deployment tables in the Python SDK. --- -LanceDB provides an excellent data backend for training machine learning models. For basic use cases, a `Table` can be fed directly into a data loader. For a more complete solution, a `StreamingDataset` adds prefetching, elastic determinism, resumability, multithreaded transformations, and more. - -## Basic Data Loading - -Most model training frameworks feed data into a model by sequencing through successive batches, a process -often referred to as **data loading**. The simplest way to perform data loading is to read a LanceDB table in batches, -in the order its rows are stored, through an identity `Permutation`. A table itself is not iterable. - - -```py Python icon=Python -import lancedb -from lancedb.permutation import Permutation - -db = lancedb.connect("file://some/db/path") -table = db.open_table("some_table") - -for batch in Permutation.identity(table).with_format("arrow").iter(batch_size=1024): - print(batch.to_pydict()) -``` - - -## Advanced Data Loading Advanced data loading scenarios can be handled by the `StreamingDataset`. This object allows you to apply preprocessing before training, pipelined reads, and more. Use this when the training data does not fit in memory, or when you need deterministic global batches across cluster sizes. @@ -56,30 +31,15 @@ for batch in dataloader: ``` -The `StreamingDataset` wraps a LanceDB `Table` and yields plain Python dictionaries by default. Whether iterating directly or through a PyTorch `DataLoader`, only one iterator can be simultaneously active on a `StreamingDataset` instance. +The `StreamingDataset` wraps a LanceDB `Table` and yields plain Python dictionaries by default. Whether iterating directly or through a PyTorch `DataLoader`, only one iterator can be simultaneously active on a `StreamingDataset` instance. -`StreamingDataset` is built on the `permutation` API and works with both LanceDB OSS and LanceDB Enterprise. The underlying table data can live on local disk or object storage. +`StreamingDataset` is built on the [`Permutation`](/training/permutation) API and works with both LanceDB Embedded and LanceDB Enterprise. The underlying table data can live on local disk or object storage. -To understand the wide range of scenarios handled by `StreamingDataset`, consider a model trained with stochastic gradient descent (SGD) and distributed data parallelism (DDP). In this example, we need to load batches onto multiple GPUs -across multiple servers. After each batch is processed, the GPUs exchange weights and the next batch is loaded. We -fix the following terminology: +## Filtering {#filtering} -- **World size** - The number of GPUs being loaded simultaneously. For example, if we have $2$ servers with $4$ - GPUs each, the world size is $8$. -- **Rank** - The identifier of an individual GPU. It is an integer in the range `[0, world_size)`. - Each rank is allocated a disjoint portion of the source data. -- **Batch size** - The number of rows processed by one GPU in a single training step. For example, $128$. -- **Global batch size** - The total number of rows processed across all GPUs in a training step (sometimes called a "minibatch" in machine learning literature). For - example, if we have $8$ GPUs with batch size $128$, the global batch size is $1024$. - - -Other concepts, such as read batch size and `num_workers`, are introduced in the relevant sections below. - -### Filtering - -The `StreamingDataset` object allows you to train models on only the subset of rows that satisfy a user-defined filter, specified using the `filter` parameter. This can be useful for removing large rows, badly-sourced data, and a wide range of other applications. +The `StreamingDataset` object allows you to train models on only the subset of rows that satisfy a user-defined filter, specified using the `filter` parameter. This can be useful for removing large rows, badly-sourced data, and a wide range of other applications. You can also use the `columns` parameter to load only a subset of columns. @@ -93,7 +53,7 @@ ds = StreamingDataset( ``` -### Shuffling Rows +## Shuffling Rows {#shuffling-rows} In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles at one of two granularities, selected by the `shuffle_clump_size` parameter. @@ -102,21 +62,20 @@ In model training, model quality can be hurt by unintentionally learning pattern with the same inputs remain reproducible. Set `shuffle_seed = None` to generate a random seed upon pipeline initialization. -#### Row-Level Shuffle {#one-phase-shuffle} +### Row-Level Shuffle {#one-phase-shuffle} By default, `shuffle_clump_size` is `None` and rows are shuffled individually: the rows of the source dataset are shuffled according to a pseudorandom permutation, then fed in batches to the accelerator. This gives the best possible randomness, but can exhibit low throughput. - - -```py Python icon=Python + +```py Python icon=Python # 1-phase shuffled read: rows shuffled individually. -for epoch in range(num_epochs): - ds = StreamingDataset( - table, - shuffle_seed=42, - epoch=epoch, # changes the permutation each epoch - ) - for sample in ds: +for epoch in range(num_epochs): + ds = StreamingDataset( + table, + shuffle_seed=42, + epoch=epoch, # changes the permutation each epoch + ) + for sample in ds: train_step(sample) #Evaluation: deterministic sequential order, no shuffle. @@ -124,11 +83,9 @@ eval_ds = StreamingDataset(table, shuffle=False) for sample in eval_ds: eval_step(sample) ``` - - -#### Clumped Shuffle {#two-phase-shuffle} +### Clumped Shuffle {#two-phase-shuffle} Setting `shuffle_clump_size` to an integer shuffles contiguous groups ("clumps") of that many rows instead of single rows. Each clump keeps its rows in storage order and moves as a unit, so storage I/O consists mostly of contiguous reads rather than single-row fetches. Larger clumps improve I/O locality, which matters most on object storage, at the cost of randomness. @@ -153,57 +110,7 @@ for sample in eval_ds: ``` -### Parallelism & 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. - -If using `shuffle=False`, data is allocated to splits naively in ordered contiguous blocks of equal size. With `shuffle=True` -(the default), the rows of the source dataset are shuffled and distributed among splits such that each split receives the same -number of rows; with `shuffle_clump_size` set, they are shuffled in clumps of that many contiguous rows. - -The number of splits defaults to `world_size` if `num_splits` is omitted during initialization. This is not recommended, as a later run using a different world size will then construct a different layout and structure of global batches. - -To get **elastic determinism**, choose a fixed `num_splits` that is compatible with every topology you plan to use. -For example, a run with `num_splits=8` and $4$ GPUs assigns $2$ splits to each rank. The ranks pull from their splits in -round-robin order, producing the same global batches as a run with $8$ GPUs and the same `num_splits`, `shuffle_seed`, -and `epoch`. - -The following constraints apply: - -- `num_splits` must be divisible by `world_size`. -- With DataLoader worker processes, `num_splits` must be divisible by `world_size * num_workers`. -- For the same samples to form each global training step across topologies, `global_batch_size` must be a multiple of - `num_splits`. -- The filtered row count must be at least `num_splits`. If it is not evenly divisible by `num_splits`, up to - `num_splits - 1` surplus rows are dropped so that every split has the same length. - -For example, to switch between $8$ and $6$ GPUs, use a common multiple such as $24$ for `num_splits`. Highly composite values can support many layouts; for example, `num_splits = 48` is compatible with $10$ distinct possible GPU counts. Remember to include `num_workers` when checking divisibility. - - -```py Python icon=Python -import torch.distributed as dist - -dist.init_process_group("nccl") -rank = dist.get_rank() -world_size = dist.get_world_size() - -# num_splits=48 is divisible by many integers, -# so this dataset works unchanged as you add or remove GPUs. -ds = StreamingDataset( - table, - num_splits=48, - shuffle_seed=42, - epoch=current_epoch, - rank=rank, - world_size=world_size, -) - -for sample in ds: - train_step(sample) -``` - - -### Fetching +## Fetching {#fetching} Traditional datasets have often been designed to yield a single sample at a time upon iteration. However, in modern use cases, accessing data on object storage one row at a time introduces too much per-call overhead. Thus, `StreamingDataset` fetches data in read batches, whose size is controlled by the `read_batch_size` parameter (defaults = `64`). @@ -220,13 +127,12 @@ ds = StreamingDataset( ``` -### Transforming +## Transforming {#transforming} -Many model training workloads require performing a transformation to the data after it is loaded from object storage and before it is passed to the GPU. For example, we may need to decode images, tokenize text, or normalize vectors. A transformation function can be provided using the `transform` parameter. +Many model training workloads require performing a transformation to the data after it is loaded from object storage and before it is passed to the GPU. For example, we may need to decode images, tokenize text, or normalize vectors. A transformation function can be provided using the `transform` parameter. A transformation function must receive a PyArrow `RecordBatch` and return an iterable. For example, the default transform function returns a list of Python dictionaries. Furthermore, the input expected by PyTorch must match the collation function used in the PyTorch data loader. PyTorch's default collation function accepts a Python dictionary and several other types, and is thus compatible with the default `StreamingDataset` transform function. If your custom transform function returns something different (for example, Arrow record batches), you may need to provide a compatible PyTorch collation function. - ```py Python icon=Python import pyarrow as pa @@ -245,9 +151,50 @@ ds = StreamingDataset(table, shuffle_seed=42, transform=normalize) `StreamingDataset` manages expensive transforms through a -`ThreadPoolExecutor` whose worker count equals the number of available CPUs. Furthermore, transformations are applied to batches (instead of individual samples) to amortize per-batch overhead. +`ThreadPoolExecutor` whose worker count equals the number of available CPUs (`transform_parallelism`). Furthermore, transformations are applied to batches (instead of individual samples) to amortize per-batch overhead. -##### DataLoader Workers +Heavier per-sample work belongs in the same function, such as decoding +video. Store each clip in a Blob v2 column (`lancedb.blob("video")`). A scan +returns small descriptors instead of the video bytes, so reading other +columns never pulls video in. `fetch_blob_files` opens the clips for a batch +of rows as file handles, and `torchcodec`'s `VideoDecoder` decodes just the +frames you ask for. `ExtractFrames` samples 8 evenly spaced frames from each +clip: + + +```py Python icon=Python +import functools +from torchcodec.decoders import VideoDecoder + +class ExtractFrames: + def __init__(self, uri: str, name: str, num_frames: int = 8) -> None: + self.uri, self.name, self.num_frames = uri, name, num_frames + + @functools.cached_property + def table(self) -> lancedb.table.Table: + return lancedb.connect(self.uri).open_table(self.name) + + def __call__(self, rb: pa.RecordBatch) -> list[dict[str, torch.Tensor]]: + samples = [] + for blob in self.table.fetch_blob_files("video", rb["_rowid"]): + decoder = VideoDecoder(blob) + idx = torch.linspace(0, len(decoder) - 1, self.num_frames).long() + samples.append({"frames": decoder.get_frames_at(idx.tolist()).data}) + return samples + +# `clips` is the table "clips" in the database at `uri`, with a Blob v2 column "video" +train = StreamingDataset(clips, columns=["_rowid"], transform=ExtractFrames(uri, "clips")) +``` + + +Real data has bad rows, such as a truncated frame. Raise inside the +transform and set `on_transform_error="skip"` (or `"warn"` to log each +failure). `StreamingDataset` re-runs the failing batch one row at a time, +drops only the rows that raise, and counts them in `dataset.rows_skipped`. +When the bad rows match a SQL predicate, prefer `filter=` instead: it runs +before the splits are built, so every split keeps the same length. + +### DataLoader Workers {#dataloader-workers} The thread-based transformation model that `StreamingDataset` uses by default is only effective when the transform function releases the GIL. This is true for many Python scientific libraries, including NumPy, PyArrow, and @@ -259,6 +206,7 @@ loading in the rank's main process, and add workers only after confirming an una workers, `num_splits` must be divisible by `world_size * num_workers`. Use the `forkserver` or `spawn` multiprocessing context because LanceDB uses internal threads. + ```py Python icon=Python dataloader = torch.utils.data.DataLoader( dataset, @@ -268,12 +216,87 @@ dataloader = torch.utils.data.DataLoader( persistent_workers=True, ) ``` + -By default, `StreamingDataset` serializes enough table state to reopen the table in each worker. For custom connection -setup, pass a picklable `connection_factory` callable that accepts a table name and returns an open table. This avoids -serializing connection credentials into worker state. +By default, `StreamingDataset` serializes enough table state to reopen the +table in each worker. Remote LanceDB Enterprise tables (`db://...`) work the +same way: workers reopen the table from the pickled connection state. +Replace the URI, API key, region and endpoint below with your deployment +details. In application code, load credentials from environment variables +or a secrets manager: -### Observability + +```py Python icon=Python +import lancedb +import torch +from lancedb.util import tbl_to_tensor + +db = lancedb.connect( + "db://my-database", + api_key="your-api-key", + region="us-east-1", + host_override="https://your-endpoint", +) +table = db.open_table("my_table") + +dataloader = torch.utils.data.DataLoader( + table, + batch_size=512, + num_workers=4, + multiprocessing_context="forkserver", + collate_fn=tbl_to_tensor, +) +``` + + + +This sends the connection state, including the API key, to each worker. Use a connection factory if credentials should be loaded inside the worker or your `client_config` contains a non-serializable `header_provider`. + + +#### Providing a custom connection factory {#providing-a-custom-connection-factory} + +For custom connection setup, pass a picklable `connection_factory` callable +that accepts a table name and returns an open table. This avoids +serializing connection credentials into worker state: it loads the API key +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 +export LANCEDB_API_KEY="your-api-key" +``` + + +```py Python icon=Python +import os +import lancedb +import torch +from lancedb.permutation import Permutation + +def open_table(name: str): + db = lancedb.connect( + "db://my-database", + api_key=os.environ["LANCEDB_API_KEY"], + region="us-east-1", + host_override="https://your-endpoint", + ) + return db.open_table(name) + +table = open_table("my_table") +permutation = ( + Permutation.identity(table) + .with_connection_factory(open_table) +) +dataloader = torch.utils.data.DataLoader( + permutation, + batch_size=512, + num_workers=4, + multiprocessing_context="forkserver", +) +``` + + +## 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 @@ -320,161 +343,13 @@ are cumulative across iterations of the same dataset instance; because work runs can exceed wall-clock time. The queue depths report rows currently waiting in the pipeline, and the progress counters reflect the latest iterator snapshot. -### Checkpointing -`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. +## Next steps {#next} -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 - -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 - -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) -``` - - -## Permutations - -In specific use cases, you may need the flexibility to shuffle, split, and select data without using the full `StreamingDataset` object. In these cases, use `Permutation`, the lower-level functionality on which `StreamingDataset` -is built. A `Permutation` defines a customizable row ordering, and supports map-style access through `__getitem__()` -and batched access through `__getitems__()`. - -##### Version Pinning - -A `Permutation` is pinned to the version of its base table at the time it was constructed, and every read (including future reads -from a `StreamingDataset` that wraps it, and every DataLoader worker after it starts) resolves against that pinned -version. This makes iteration deterministic across compactions and worker restarts: the permutation only addresses rows -that existed when it was built, and rows appended to the base table afterwards are not visible through the existing -permutation. - -To include newly appended rows, build a new `Permutation` (and any `StreamingDataset` that depends on it) -against the updated table. Permutations written before this behavior shipped continue to -read as they did before. + + + The lower-level row ordering StreamingDataset is built on. + + + Multi-GPU sharding, elastic determinism, and checkpointing. + + diff --git a/docs/web/training/distributed-training.mdx b/docs/web/training/distributed-training.mdx new file mode 100644 index 000000000..549539591 --- /dev/null +++ b/docs/web/training/distributed-training.mdx @@ -0,0 +1,216 @@ +--- +title: "Distributed Training" +sidebarTitle: "Distributed Training" +description: "Shard StreamingDataset across ranks and workers, with elastic determinism and checkpointing." +icon: server +availability: + embedded: available + enterprise: available +--- + +To understand the wide range of scenarios handled by [`StreamingDataset`](/training/data-loading) across a +distributed job, consider a model trained with stochastic gradient descent (SGD) and distributed data parallelism +(DDP). In this example, we need to load batches onto multiple GPUs across multiple servers. After each batch is +processed, the GPUs exchange weights and the next batch is loaded. We fix the following terminology: + +- **World size** - The number of GPUs being loaded simultaneously. For example, if we have $2$ servers with $4$ + GPUs each, the world size is $8$. +- **Rank** - The identifier of an individual GPU. It is an integer in the range `[0, world_size)`. + Each rank is allocated a disjoint portion of the source data. +- **Batch size** - The number of rows processed by one GPU in a single training step. For example, $128$. +- **Global batch size** - The total number of rows processed across all GPUs in a training step (sometimes called a "minibatch" in machine learning literature). For + example, if we have $8$ GPUs with batch size $128$, the global batch size is $1024$. + +Other concepts, such as read batch size and `num_workers`, are introduced in [PyTorch Data Loader](/training/data-loading). + +## Parallelism & Elasticity {#parallelism-&-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. + +If using `shuffle=False`, data is allocated to splits naively in ordered contiguous blocks of equal size. With `shuffle=True` +(the default), the rows of the source dataset are shuffled and distributed among splits such that each split receives the same +number of rows; with `shuffle_clump_size` set, they are shuffled in clumps of that many contiguous rows. + +The number of splits defaults to `world_size` if `num_splits` is omitted during initialization. This is not recommended, as a later run using a different world size will then construct a different layout and structure of global batches. + +To get **elastic determinism**, choose a fixed `num_splits` that is compatible with every topology you plan to use. +For example, a run with `num_splits=8` and $4$ GPUs assigns $2$ splits to each rank. The ranks pull from their splits in +round-robin order, producing the same global batches as a run with $8$ GPUs and the same `num_splits`, `shuffle_seed`, +and `epoch`. + +The following constraints apply: + +- `num_splits` must be divisible by `world_size`. +- With DataLoader worker processes, `num_splits` must be divisible by `world_size * num_workers`. +- For the same samples to form each global training step across topologies, `global_batch_size` must be a multiple of + `num_splits`. +- The filtered row count must be at least `num_splits`. If it is not evenly divisible by `num_splits`, up to + `num_splits - 1` surplus rows are dropped so that every split has the same length. + +For example, to switch between $8$ and $6$ GPUs, use a common multiple such as $24$ for `num_splits`. Highly composite values can support many layouts; for example, `num_splits = 48` is compatible with $10$ distinct possible GPU counts. Remember to include `num_workers` when checking divisibility. + + +```py Python icon=Python +import torch.distributed as dist + +dist.init_process_group("nccl") +rank = dist.get_rank() +world_size = dist.get_world_size() + +# num_splits=48 is divisible by many integers, +# so this dataset works unchanged as you add or remove GPUs. +ds = StreamingDataset( + table, + num_splits=48, + shuffle_seed=42, + epoch=current_epoch, + rank=rank, + world_size=world_size, +) + +for sample in ds: + train_step(sample) +``` + + +## Checkpointing {#checkpointing} + +`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) +``` + diff --git a/docs/web/training/object-detection.mdx b/docs/web/training/object-detection.mdx index 620409728..6e9213a57 100644 --- a/docs/web/training/object-detection.mdx +++ b/docs/web/training/object-detection.mdx @@ -7,7 +7,7 @@ icon: car This example walks through fine-tuning an autonomous vehicle (AV) perception model on targeted failure-mode slices of [BDD100K](https://www.bdd100k.com/) (riders, nighttime pedestrians, and distant pedestrians) using LanceDB as a single multimodal table from raw JPEG bytes through to the PyTorch training loop. -The full pipeline lives in the [lancedb/training](https://github.com/lancedb/training/tree/main/object-detection) repository. This page focuses on the parts most relevant to training: defining curated splits as materialized views, loading them through the [`Permutation`](/training/data-loading) API, and pinning checkpoints to an exact data version. +The full pipeline lives in the [lancedb/training](https://github.com/lancedb/training/tree/main/object-detection) repository. This page focuses on the parts most relevant to training: defining curated splits as materialized views, loading them through the [`Permutation`](/training/permutation) API, and pinning checkpoints to an exact data version. ## What you get {#what-you-get} @@ -155,7 +155,7 @@ with gconn.local_ray_context(): ## 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/data-loading) 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. +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 diff --git a/docs/web/training/permutation.mdx b/docs/web/training/permutation.mdx new file mode 100644 index 000000000..751056541 --- /dev/null +++ b/docs/web/training/permutation.mdx @@ -0,0 +1,123 @@ +--- +title: "Permutation" +sidebarTitle: "Permutation" +description: "The low-level, customizable row ordering that StreamingDataset is built on." +icon: shuffle +availability: + embedded: available + enterprise: available +--- + +Most model training frameworks feed data into a model by sequencing through successive batches, a process +often referred to as **data loading**. The simplest way to perform data loading is to read a LanceDB table in batches, +in the order its rows are stored, through an identity `Permutation`. A table itself is not iterable. + + +```py Python icon=Python +import lancedb +from lancedb.permutation import Permutation + +db = lancedb.connect("file://some/db/path") +table = db.open_table("some_table") + +for batch in Permutation.identity(table).with_format("arrow").iter(batch_size=1024): + print(batch.to_pydict()) +``` + + +In specific use cases, you may need the flexibility to shuffle, split, and select data without using the full +[`StreamingDataset`](/training/data-loading) object. In these cases, use `Permutation`, the lower-level +functionality `StreamingDataset` is built on. A `Permutation` defines a customizable row ordering, and supports +map-style access through `__getitem__()` and batched access through `__getitems__()`. + +## Version Pinning {#version-pinning} + +A `Permutation` is pinned to the version of its base table at the time it was constructed, and every read (including future reads +from a `StreamingDataset` that wraps it, and every DataLoader worker after it starts) resolves against that pinned +version. This makes iteration deterministic across compactions and worker restarts: the permutation only addresses rows +that existed when it was built, and rows appended to the base table afterwards are not visible through the existing +permutation. + +To include newly appended rows, build a new `Permutation` (and any `StreamingDataset` that depends on it) +against the updated table. Permutations written before this behavior shipped continue to +read as they did before. + +## Output formats {#output-formats} + +By default, a `Table` data loader emits Arrow data. `collate_fn` is PyTorch's batching hook: PyTorch calls it to +turn the fetched items into one batch. PyTorch's default collate function only knows how to combine tensors, NumPy +arrays, numbers, dicts, and lists, so it does not accept Arrow data directly. When using a `Table` directly, pass +LanceDB's `lancedb.util.tbl_to_tensor` helper as PyTorch's `collate_fn`; it converts numeric Arrow columns into a +column-major `torch.Tensor` with shape `(columns, rows)`. + +`Permutation` works differently: its default output is a list of Python dicts, which PyTorch's default collate function +can batch into a dict of tensors. This is usually more convenient when you are getting started. However, there is a +significant performance penalty converting from Arrow, Lance's internal representation, to this default format. If you +want the default PyTorch dict-of-tensors behavior, use a `Permutation` as-is; if you want direct Arrow-to-tensor +conversion, either pass `lancedb.util.tbl_to_tensor` as `collate_fn` with a direct `Table` or configure a `Permutation` +with one of the transform formats described below. + +To address this, the `Permutation` class provides a set of builtin transform functions that can be applied to map +the Arrow data in different ways. The `arrow` and `polars` formats will always avoid data copies. However, `numpy`, +`pandas`, and `torch_col` formats will also avoid data copies in most cases. The `python`, `python_col`, and +`torch` formats will all require at least one full copy of the data and are the slowest options. + +### Using the torch column format with a torch data loader {#using-the-torch-column-format-with-a-torch-data-loader} + +The `torch_col` format is the most efficient way to convert from Arrow to a `torch.Tensor`. It will convert the +entire Arrow batch to a _column-major_ `torch.Tensor`. In other words, given C columns and R rows, the resulting +Tensor will have shape `(C, R)`. However, this format generates an error if you are using a +`torch.utils.data.DataLoader` with the default collation function: + +```text +TypeError: stack(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor +``` + +This error occurs because the default collation function does not currently expect a single two-dimensional tensor. +It expects a list of tensors which it will then stack. This is what is output by the `torch` format but that format +requires a data copy. To avoid this error, and avoid data copies, you will need to provide a custom collation function +in addition to specifying the `torch_col` format. + +```py 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. + +## Selecting columns {#selecting-columns} + +By default, the `Table` class will return all columns in the table when used as input to PyTorch. If you only need +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 +import pyarrow as pa +import torch +from lancedb.permutation import Permutation + +db = lancedb.connect("memory://") +prompts = db.create_table( + "prompts", + pa.table( + { + "id": range(4), + "prompt": ["north", "south", "east", "west"], + "embedding": [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6], [0.7, 0.8]], + } + ), +) + +permutation = Permutation.identity(prompts).select_columns(["id", "prompt"]) +dataloader = torch.utils.data.DataLoader( + permutation, batch_size=1024, shuffle=True +) + +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/torch.mdx b/docs/web/training/torch.mdx deleted file mode 100644 index 53d33e39c..000000000 --- a/docs/web/training/torch.mdx +++ /dev/null @@ -1,227 +0,0 @@ ---- -title: "PyTorch Integration" -sidebarTitle: "PyTorch" -description: Learn how to use LanceDB with PyTorch for training and inference. -icon: fire -availability: - oss: available - enterprise: available - summary: >- - The PyTorch integration works with local, object-storage and deployment - tables in the Python SDK. ---- - -Use LanceDB tables as input to a PyTorch `DataLoader`. Select the columns you -need, choose a batch format, and read data in parallel for training or inference. - -## Quickstart {#quickstart} - -The `Table` class in LanceDB implements a contract for a PyTorch -[Dataset](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.Dataset). - This means you can simply use a LanceDB table in a PyTorch dataloader directly. - -```py Python icon=Python -import lancedb -import torch -import pyarrow as pa -from lancedb.util import tbl_to_tensor - -mem_db = lancedb.connect("memory://") -table = mem_db.create_table("test_table", pa.table({"a": range(1000)})) - -# Any LanceDB table can be used as a PyTorch Dataset -dataloader = torch.utils.data.DataLoader( - table, batch_size=1024, shuffle=True, collate_fn=tbl_to_tensor -) - -for batch in dataloader: - print(batch) -``` - -Although the `Table` class in LanceDB implements the `torch.utils.data.Dataset` interface, you may find that using -a table [Permutation](/training/data-loading) is more flexible. - -```py Python icon=Python -from lancedb.permutation import Permutation - -permutation = Permutation.identity(table) -dataloader = torch.utils.data.DataLoader(permutation) -``` - -## Output Formats {#output-formats} - -By default, a `Table` data loader will emit Arrow data. `collate_fn` is PyTorch's batching hook: PyTorch calls it to -turn the fetched items into one batch. PyTorch's default collate function only knows how to combine tensors, NumPy -arrays, numbers, dicts, and lists, so it does not accept Arrow data directly. When using a `Table` directly, pass -LanceDB's `lancedb.util.tbl_to_tensor` helper as PyTorch's `collate_fn`; it converts numeric Arrow columns into a -column-major `torch.Tensor` with shape `(columns, rows)`. - -`Permutation` works differently: its default output is a list of Python dicts, which PyTorch's default collate function -can batch into a dict of tensors. This is usually more convenient when you are getting started. However, there is a -significant performance penalty converting from Arrow, Lance's internal representation, to this default format. If you -want the default PyTorch dict-of-tensors behavior, use a `Permutation` as-is; if you want direct Arrow-to-tensor -conversion, either pass `lancedb.util.tbl_to_tensor` as `collate_fn` with a direct `Table` or configure a `Permutation` -with one of the transform formats described below. - -To address this, the `Permutation` class provides a set of builtin transform functions that can be applied to map -the Arrow data in different ways. The `arrow` and `polars` formats will always avoid data copies. However, `numpy`, -`pandas`, and `torch_col` formats will also avoid data copies in most cases. The `python`, `python_col`, and -`torch` formats will all require at least one full copy of the data and are the slowest options. - -### Using the torch column format with a torch data loader {#using-the-torch-column-format-with-a-torch-data-loader} - -The `torch_col` format is the most efficient way to convert from Arrow to a `torch.Tensor`. It will convert the -entire Arrow batch to a _column-major_ `torch.Tensor`. In other words, given C columns and R rows, the resulting -Tensor will have shape `(C, R)`. However, this format generates an error if you are using a -`torch.utils.data.DataLoader` with the default collation function: - -```text -TypeError: stack(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor -``` - -This error occurs because the default collation function does not currently expect a single two-dimensional tensor. -It expects a list of tensors which it will then stack. This is what is output by the `torch` format but that format -requires a data copy. To avoid this error, and avoid data copies, you will need to provide a custom collation function -in addition to specifying the `torch_col` format. - -```py 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. - -## Selecting columns {#selecting-columns} - -By default, the `Table` class will return all columns in the table when used as input to PyTorch. If you only need -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 -import pyarrow as pa -import torch -from lancedb.permutation import Permutation - -db = lancedb.connect("memory://") -prompts = db.create_table( - "prompts", - pa.table( - { - "id": range(4), - "prompt": ["north", "south", "east", "west"], - "embedding": [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6], [0.7, 0.8]], - } - ), -) - -permutation = Permutation.identity(prompts).select_columns(["id", "prompt"]) -dataloader = torch.utils.data.DataLoader( - permutation, batch_size=1024, shuffle=True -) - -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. - -## Using multiple DataLoader workers {#using-multiple-dataloader-workers} - -Set `num_workers > 0` to read from LanceDB in multiple PyTorch worker processes. `Permutation` objects and tables in LanceDB Enterprise are picklable, so each worker reopens the table after it starts. A local table is not, so wrap it in a `Permutation`, as below, to read it from several workers. - -Prefer the `forkserver` start method when using multiple workers. LanceDB uses internal threads, so the default `fork` method is unsafe; `forkserver` avoids that while being cheaper to start than `spawn`, and became the default on Linux and other supported POSIX platforms in Python -3.14. macOS and Windows default to `spawn`. See -[Python's start-method documentation](https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods). See [the performance guide](/search#performance) for more multiprocessing guidance. - - -`forkserver` is only available on POSIX systems (Linux and macOS). On Windows, use `spawn`, the only available start method. - - -```py Python icon=Python -import torch -from lancedb.permutation import Permutation - -permutation = Permutation.identity(table) -dataloader = torch.utils.data.DataLoader( - permutation, - batch_size=1024, - shuffle=True, - num_workers=4, - multiprocessing_context="forkserver", - persistent_workers=True, -) -``` - -### Remote tables in DataLoader workers {#remote-tables-in-dataloader-workers} - -Remote LanceDB Enterprise tables (`db://...`) work the same way: workers reopen the table from the pickled connection state. Replace the URI, API key, region and endpoint below with your deployment details. In application code, load credentials from environment variables or a secrets manager. - -```py Python icon=Python -import lancedb -import torch -from lancedb.util import tbl_to_tensor - -db = lancedb.connect( - "db://my-database", - api_key="your-api-key", - region="us-east-1", - host_override="https://your-endpoint", -) -table = db.open_table("my_table") - -dataloader = torch.utils.data.DataLoader( - table, - batch_size=512, - num_workers=4, - multiprocessing_context="forkserver", - collate_fn=tbl_to_tensor, -) -``` - - -This sends the connection state, including the API key, to each worker. Use a connection factory if credentials should be loaded inside the worker or your `client_config` contains a non-serializable `header_provider`. - - -### Providing a custom connection factory {#providing-a-custom-connection-factory} - -`Permutation.with_connection_factory` lets each worker reopen the base table with custom logic. The factory takes the table name, returns a LanceDB table, and must be picklable. - -This example loads the API key inside each worker. 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 -export LANCEDB_API_KEY="your-api-key" -``` - -```py Python icon=Python -import os -import lancedb -import torch -from lancedb.permutation import Permutation - -def open_table(name: str): - db = lancedb.connect( - "db://my-database", - api_key=os.environ["LANCEDB_API_KEY"], - region="us-east-1", - host_override="https://your-endpoint", - ) - return db.open_table(name) - -table = open_table("my_table") -permutation = ( - Permutation.identity(table) - .with_connection_factory(open_table) -) -dataloader = torch.utils.data.DataLoader( - permutation, - batch_size=512, - num_workers=4, - multiprocessing_context="forkserver", -) -``` diff --git a/docs/web/training/why-lancedb.mdx b/docs/web/training/why-lancedb.mdx deleted file mode 100644 index af10d4edc..000000000 --- a/docs/web/training/why-lancedb.mdx +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: "Why LanceDB for Training" -sidebarTitle: "Why LanceDB" -description: "Use LanceDB as the multimodal data layer for model training, fine-tuning, curation, and feature engineering workflows." -icon: fire ---- - -LanceDB is built for AI teams that need a practical data layer between raw multimodal datasets and model training. -Instead of moving data through separate systems for curation, feature engineering, search, manifests, and training, -you can keep the whole workflow attached to one versioned LanceDB table. - -That table can hold images, video, audio, text, annotations, metadata, embeddings, tokenized fields, model outputs, -quality signals, and training-ready tensors. As the dataset evolves, LanceDB lets you add new columns, filter rows, -pin versions, and read batches without rewriting the original data. - -![Training data lifecycle: Curation, Feature Engineering, Search and Retrieval, Training](/static/assets/images/overview/training-data-lifecycle.svg) - -The LanceDB multimodal lakehouse connects curation, feature engineering, retrieval, and training data access -through Lance tables. Data loaders read these tables into training frameworks, which run the model training. - -## A connected data lifecycle {#a-connected-data-lifecycle} - -Training pipelines usually need more than a pile of files. They need curation, derived features, reproducible splits, -fast random access, and a clean path into frameworks such as PyTorch. LanceDB keeps these pieces connected through -the same table model, whether you organize a workflow as one table or several related tables. - - - - Use filters, vector search, full-text search, and retrieval workflows to find the examples that matter: hard negatives, - long-tail failure modes, duplicate clusters, low-quality samples, or targeted fine-tuning slices. - - - Add embeddings, detections, OCR output, labels, token IDs, hidden states, deduplication flags, or quality scores as - new columns. Lance's columnar layout and schema evolution avoid rewriting large raw media columns when you add features. - - - Build filtered splits and materialized views from the table instead of exporting CSV manifests. Data versions and tags - make it possible to tie a checkpoint back to the exact rows and features used for training. - - - Use fast random access and column projection to read only the columns a training step needs. LanceDB tables can be read - from local storage or object storage, and integrate with data loading patterns such as PyTorch datasets. - - - -## Lance as the foundation {#lance-as-the-foundation} - -LanceDB is built on [Lance](https://lance.org/), an open-source lakehouse format designed for multimodal AI data. -The table below highlights the Lance features that enable the multimodal lakehouse on top. - -| Capability | Why it matters for training | -|---|---| -| **Multimodal columns** | Store raw bytes, annotations, metadata, embeddings, and features together. | -| **Fast random access** | Support shuffled and sampled reads without reshuffling the dataset on disk. | -| **Column projection** | Read only images, tokens, labels, embeddings, or hidden states needed by a given run. | -| **Schema evolution** | Add new feature columns without rewriting existing media columns. | -| **Versioning** | Reproduce experiments against the same table snapshot, even as the dataset evolves. | -| **Search and filtering** | Find and materialize useful training slices directly from the table. | - -## Search inside training workflows {#search-inside-training-workflows} - -Search is not limited to QA systems, agents, or production retrieval apps. It is also a practical way to inspect, -curate, and improve training data: - -- Find visually similar examples when debugging model failures. -- Retrieve hard negatives or near-duplicates for contrastive training. -- Combine vector search, full-text search, and metadata filters to build targeted fine-tuning slices. -- Reuse the same table for both offline curation and production retrieval. - -In LanceDB, retrieval and training workflows can operate over the same multimodal tables instead of forcing teams to -manage separate data systems for each stage. - -## Projects using LanceDB for training workflows {#projects-using-lancedb-for-training-workflows} - - - - A platform for reproducible world-model research built on a LanceDB data layer, reporting faster data loading on Push-T workloads. - - - A joint-embedding predictive world model from pixels, trained on the stable-worldmodel platform and its LanceDB data layer. - - - A drop-in LanceDB backend for Hugging Face LeRobot datasets with faster loading across robotics datasets. - - - -In the world-model ecosystem, [stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) reports -3-4x faster data loading on Push-T versus HDF5 / MP4 at a fraction of the disk footprint. Across these projects, -LanceDB and Lance provide the multimodal data layer that keeps raw observations, annotations, features, and training -access patterns in one format instead of scattering them across task-specific stores. - -## Next steps {#next-steps} - - - - Learn how to use LanceDB permutations to select rows, project columns, split datasets, and shuffle training reads. - - - Use LanceDB tables and permutations with `torch.utils.data.DataLoader`. - - - Fine-tune an AV perception model on curated failure-mode slices backed by one LanceDB table. - - - Fine-tune a VLM on TextVQA using LanceDB and Geneva to cache expensive training features. - - diff --git a/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx b/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx index d7d033f1e..19d1ec7c9 100644 --- a/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx +++ b/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx @@ -6,7 +6,7 @@ description: "Use LanceDB as the retrieval layer for NVIDIA RAG Blueprint with a ## What this tutorial shows {#what-this-tutorial-shows} -If you are using [NVIDIA RAG Blueprints](https://build.nvidia.com/blueprints) and want to evaluate LanceDB in that stack, this tutorial gives you a concrete starting point. It shows how to use LanceDB as the retrieval layer for a Docker-based NVIDIA RAG deployment with a small, script-driven reference integration where LanceDB OSS is embedded directly in the NVIDIA containers, the collection is prepared ahead of time, and the RAG server retrieves from it for search and generation. The example is intentionally retrieval-only, but it also includes hybrid search and reranker selection so you can see how LanceDB fits into a realistic NVIDIA retrieval workflow. +If you are using [NVIDIA RAG Blueprints](https://build.nvidia.com/blueprints) and want to evaluate LanceDB in that stack, this tutorial gives you a concrete starting point. It shows how to use LanceDB as the retrieval layer for a Docker-based NVIDIA RAG deployment with a small, script-driven reference integration where LanceDB Embedded runs directly in the NVIDIA containers, the collection is prepared ahead of time, and the RAG server retrieves from it for search and generation. The example is intentionally retrieval-only, but it also includes hybrid search and reranker selection so you can see how LanceDB fits into a realistic NVIDIA retrieval workflow. The runnable example for this tutorial lives in the @@ -31,7 +31,7 @@ yet teach NVIDIA's ingestor how to write new documents into LanceDB automaticall ## Deployment model {#deployment-model} -This reference integration uses **LanceDB OSS as an embedded retrieval library**, not as a separate +This reference integration uses **LanceDB Embedded as an embedded retrieval library**, not as a separate database service. In practice, `APP_VECTORSTORE_NAME` is set to `lancedb`, `APP_VECTORSTORE_URL` points to a local filesystem path inside the NVIDIA containers, the LanceDB collection is prepared ahead of time, and the NVIDIA RAG server loads the LanceDB adapter to retrieve directly from that diff --git a/docs/web/tutorials/feature-engineering/feature-engineering-101.mdx b/docs/web/tutorials/feature-engineering/feature-engineering-101.mdx index 7f6110162..31f847473 100644 --- a/docs/web/tutorials/feature-engineering/feature-engineering-101.mdx +++ b/docs/web/tutorials/feature-engineering/feature-engineering-101.mdx @@ -5,7 +5,6 @@ description: "Add derived feature columns to an existing table." --- Adds new derived features to a table, the pattern documented under -[data evolution](/feature-engineering/data-evolution) and [computed columns](/feature-engineering/add-computed-column). diff --git a/docs/web/tutorials/feature-engineering/materialized-views.mdx b/docs/web/tutorials/feature-engineering/materialized-views.mdx index 5e1a77bd4..32641a2d1 100644 --- a/docs/web/tutorials/feature-engineering/materialized-views.mdx +++ b/docs/web/tutorials/feature-engineering/materialized-views.mdx @@ -6,7 +6,7 @@ description: "Persist query results as physical tables and keep them current." Creates [materialized views](/management/materialized-view): query results persisted as physical tables, brought up to date by a -[refresh](/feature-engineering/materialized-views). +[refresh](/feature-engineering/refresh-materialized-view). This example is a runnable notebook in the diff --git a/java/README.md b/java/README.md index 1c20fdda0..fd163b9f1 100644 --- a/java/README.md +++ b/java/README.md @@ -2,9 +2,9 @@ ## Configuration and Initialization -### LanceDB Cloud +### LanceDB Cloud (legacy) -For LanceDB Cloud, use the simplified builder API: +For LanceDB Cloud, the legacy hosted service, use the simplified builder API: ```java import com.lancedb.LanceDbNamespaceClientBuilder; @@ -19,7 +19,7 @@ LanceNamespace namespaceClient = LanceDbNamespaceClientBuilder.newBuilder() ### LanceDB Enterprise -For Enterprise deployments, use your custom endpoint: +For LanceDB Enterprise deployments, use your custom endpoint: ```java LanceNamespace namespaceClient = LanceDbNamespaceClientBuilder.newBuilder() diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 83b27fefd..c89980194 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.9 + 0.41.0-beta.17 ../pom.xml diff --git a/java/lancedb-core/src/main/java/com/lancedb/LanceDbNamespaceClientBuilder.java b/java/lancedb-core/src/main/java/com/lancedb/LanceDbNamespaceClientBuilder.java index da70b15d2..303e10822 100644 --- a/java/lancedb-core/src/main/java/com/lancedb/LanceDbNamespaceClientBuilder.java +++ b/java/lancedb-core/src/main/java/com/lancedb/LanceDbNamespaceClientBuilder.java @@ -22,7 +22,7 @@ import java.util.Optional; /** * Util class to help construct a {@link LanceNamespace} for LanceDB. * - *

For LanceDB Cloud, use the simplified builder API: + *

For LanceDB Cloud (legacy hosted service), use the simplified builder API: * *

{@code
  * import org.lance.namespace.LanceNamespace;
diff --git a/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java b/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java
index 2b40ef798..ee5bcfc7b 100644
--- a/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java
+++ b/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java
@@ -27,7 +27,7 @@ import java.io.IOException;
 import java.io.UncheckedIOException;
 
 /**
- * Minimal HTTP client for LanceDB Cloud and Enterprise routes that the Lance Namespace
+ * Minimal HTTP client for LanceDB Enterprise routes that the Lance Namespace
  * specification does not cover.
  *
  * 

Most table operations reach LanceDB through {@link org.lance.namespace.LanceNamespace}, which diff --git a/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableRTE.java b/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableRTE.java index b0a61233c..606f31076 100644 --- a/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableRTE.java +++ b/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableRTE.java @@ -22,7 +22,7 @@ import java.util.Optional; import java.util.OptionalLong; /** - * The RTE write path for one LanceDB Cloud or Enterprise table. + * The RTE write path for one LanceDB Enterprise table. * *

Installing an {@link RTEWriteSpec} routes {@code mergeInsert} upserts through Lance's RTE — an * LSM-style append — instead of the standard merge path. Rows land in an in-memory memtable, freeze diff --git a/java/pom.xml b/java/pom.xml index 4dd145b31..2bccd2510 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.9 + 0.41.0-beta.17 pom ${project.artifactId} LanceDB Java SDK Parent POM @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 14.0.0-beta.21 + 15.0.0-beta.6 2.18.11 false 2.30.0 diff --git a/nodejs/.npmignore b/nodejs/.npmignore index 41f6643a6..128c0d36d 100644 --- a/nodejs/.npmignore +++ b/nodejs/.npmignore @@ -15,6 +15,7 @@ renovate.json src lancedb examples +scripts nodejs-artifacts Cargo.toml biome.json diff --git a/nodejs/CONTRIBUTING.md b/nodejs/CONTRIBUTING.md index 2faa8cd37..2125cc8aa 100644 --- a/nodejs/CONTRIBUTING.md +++ b/nodejs/CONTRIBUTING.md @@ -50,6 +50,19 @@ pnpm install pnpm build ``` +Local SQL computed columns and materialized-view creation/refresh are experimental +and disabled in published packages. To opt in when building from this directory: + +```shell +pnpm build:debug --features experimental-functions +pnpm tsc +pnpm test --runInBand table.test.ts materialized_view.test.ts +``` + +Rebuild without `--features experimental-functions` to test the default package. +The tests detect the compiled feature; remote operations, metadata protections, +and ordinary eager `addColumns` transforms remain available in both builds. + Lint: ```shell diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 3ef5438de..3ed65c704 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.9" +version = "0.41.0-beta.17" publish = false license.workspace = true description.workspace = true @@ -23,7 +23,7 @@ env_logger.workspace = true futures.workspace = true lancedb.workspace = true lance-namespace.workspace = true -napi = { version = "3.8.3", default-features = false, features = [ +napi = { version = "3.15.0", default-features = false, features = [ "napi9", "async", "chrono_date", @@ -31,7 +31,7 @@ napi = { version = "3.8.3", default-features = false, features = [ ] } chrono.workspace = true serde_json.workspace = true -napi-derive = "3.5.2" +napi-derive = "3.6.13" # Prevent dynamic linking of lzma, which comes from datafusion lzma-sys = { version = "0.1", features = ["static"] } log.workspace = true @@ -48,3 +48,4 @@ napi-build = "2.3.1" default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/goosefs", "lancedb/metrics-otel"] fp16kernels = ["lancedb/fp16kernels"] remote = ["lancedb/remote"] +experimental-functions = ["lancedb/experimental-functions"] diff --git a/nodejs/__test__/catalog.test.ts b/nodejs/__test__/catalog.test.ts index f8b14ca6f..3d647695c 100644 --- a/nodejs/__test__/catalog.test.ts +++ b/nodejs/__test__/catalog.test.ts @@ -86,7 +86,10 @@ describe("remote catalog", () => { value: "team/search", }); expect(names.pageToken()).toBe("next"); - await catalog.dropDatabase("team/search", { ignoreMissing: true }); + await catalog.dropDatabase("team/search", { + ignoreMissing: true, + cascade: true, + }); expect(requests[0].url).toBe("/v1/namespace/team%2Fsearch/create"); expect(requests[0].body).toEqual({ mode: "ExistOk" }); expect(requests[5].url).toBe( @@ -94,7 +97,7 @@ describe("remote catalog", () => { ); expect(requests[6].body).toEqual({ mode: "Skip", - behavior: "Restrict", + behavior: "Cascade", }); for (const [i, request] of requests.entries()) { expect(request.headers["x-lancedb-database"]).toBe( diff --git a/nodejs/__test__/connection.test.ts b/nodejs/__test__/connection.test.ts index 895c2a7c5..73f99803a 100644 --- a/nodejs/__test__/connection.test.ts +++ b/nodejs/__test__/connection.test.ts @@ -5,15 +5,15 @@ import { mkdirSync, readdirSync } from "fs"; import { join } from "path"; import { Field, Float64, Schema } from "apache-arrow"; import * as tmp from "tmp"; -import { - Connection, - ListTablesResponse, - Table, - connect, - connectNamespace, -} from "../lancedb"; +import { Connection, Table, connect, connectNamespace } from "../lancedb"; import { LocalTable } from "../lancedb/table"; +async function collectNames(items: AsyncIterable): Promise { + const names: string[] = []; + for await (const name of items) names.push(name); + return names; +} + describe("when connecting", () => { let tmpDir: tmp.DirResult; beforeEach(() => { @@ -36,6 +36,87 @@ describe("when connecting", () => { }); }); +describe.each([ + [ + "URI overload", + (uri: string, options: { storageOptions?: Record }) => + connect(uri, options), + ], + [ + "object overload", + async ( + uri: string, + options: { storageOptions?: Record }, + ) => { + const input = { uri, ...options }; + if (Object.isFrozen(options)) { + Object.freeze(input); + } + const db = await connect(input); + expect(input).toEqual({ uri, ...options }); + expect(input.storageOptions).toBe(options.storageOptions); + return db; + }, + ], + [ + "namespace", + (uri: string, options: { storageOptions?: Record }) => + connectNamespace("dir", { root: uri }, options), + ], +])("%s connection options", (_name, open) => { + let tmpDir: tmp.DirResult; + beforeEach(() => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + afterEach(() => tmpDir.removeCallback()); + + it("should accept frozen options without storage options", async () => { + const options = Object.freeze({}); + const db = await open(tmpDir.name, options); + try { + await db.createTable("frozen", [{ id: 1 }]); + await expect(db.tableNames()).resolves.toContain("frozen"); + expect(options).toEqual({}); + } finally { + await db.close(); + } + }); + + it("should accept frozen options with storage options", async () => { + const storageOptions = Object.freeze({ + newTableDataStorageVersion: "stable", + }); + const options = Object.freeze({ storageOptions }); + const db = await open(tmpDir.name, options); + try { + const table = await db.createTable("frozen", [{ id: 1 }]); + await expect(table.countRows()).resolves.toBe(1); + expect(options.storageOptions).toBe(storageOptions); + expect(storageOptions).toEqual({ newTableDataStorageVersion: "stable" }); + } finally { + await db.close(); + } + }); + + it("should preserve reused options and their storage options", async () => { + const storageOptions = { newTableDataStorageVersion: "stable" }; + const options = { storageOptions }; + for (let i = 0; i < 2; i++) { + const db = await open(tmpDir.name, options); + try { + const table = await db.createTable(`reused_${i}`, [{ id: i }]); + await expect(table.countRows()).resolves.toBe(1); + expect(options.storageOptions).toBe(storageOptions); + expect(storageOptions).toEqual({ + newTableDataStorageVersion: "stable", + }); + } finally { + await db.close(); + } + } + }); +}); + describe("given a connection", () => { let tmpDir: tmp.DirResult; let db: Connection; @@ -54,7 +135,7 @@ describe("given a connection", () => { await db.close(); expect(db.isOpen()).toBe(false); await expect(db.tableNames()).rejects.toThrow("Connection is closed"); - await expect(db.listTables()).rejects.toThrow("Connection is closed"); + expect(() => db.listTables()).toThrow("Connection is closed"); await expect(db.renameTable("a", "b")).rejects.toThrow( "Connection is closed", ); @@ -117,6 +198,80 @@ describe("given a connection", () => { await expect(tbl.countRows()).resolves.toBe(1); }); + describe.each([undefined, []])("root namespace %p", (namespacePath) => { + it("should preserve createTable options after the namespace", async () => { + await db.createTable("test", [{ id: 1 }, { id: 2 }]); + + const table = await db.createTable("test", [{ id: 3 }], namespacePath, { + mode: "overwrite", + }); + + const rows = await table.query().toArray(); + expect(rows.map((row) => row.id)).toEqual([3]); + }); + + it("should preserve createEmptyTable overwrite after the namespace", async () => { + await db.createTable("test", [{ id: 1 }]); + const schema = new Schema([new Field("id", new Float64(), true)]); + + const table = await db.createEmptyTable("test", schema, namespacePath, { + mode: "overwrite", + }); + + await expect(table.countRows()).resolves.toBe(0); + }); + + it("should preserve createEmptyTable existOk after the namespace", async () => { + await db.createTable("test", [{ id: 1 }]); + const schema = new Schema([new Field("id", new Float64(), true)]); + + const table = await db.createEmptyTable("test", schema, namespacePath, { + existOk: true, + }); + + await expect(table.countRows()).resolves.toBe(1); + }); + + it("should preserve tableNames options after the namespace", async () => { + for (const name of ["a", "b", "c"]) { + await db.createTable(name, [{ id: 1 }]); + } + + await expect( + db.tableNames(namespacePath, { limit: 1, startAfter: "a" }), + ).resolves.toEqual(["b"]); + }); + + it("should preserve listTables options after the namespace", async () => { + for (const name of ["a", "b", "c"]) { + await db.createTable(name, [{ id: 1 }]); + } + + const first = db.listTables(namespacePath, { pageLimit: 1 }); + expect(await first.next()).toEqual({ done: false, value: "a" }); + expect(first.pageToken()).toBeDefined(); + + const second = db.listTables(namespacePath, { + pageLimit: 1, + pageToken: first.pageToken(), + }); + expect(await second.next()).toEqual({ done: false, value: "b" }); + }); + }); + it("should keep the existing table when mode is exist_ok", async () => { + const created = await db.createTable("test", [{ id: 1 }, { id: 2 }], { + mode: "exist_ok", + }); + await expect(created.countRows()).resolves.toBe(2); + + const reopened = await db.createTable("test", [{ id: 9 }], { + mode: "exist_ok", + }); + await expect(reopened.countRows()).resolves.toBe(2); + const rows = (await reopened.query().toArray()) as { id: number }[]; + expect(rows.map((row) => row.id).sort()).toEqual([1, 2]); + }); + it("should respect limit and page token when listing tables", async () => { const db = await connect(tmpDir.name); @@ -144,19 +299,18 @@ describe("given a connection", () => { await db.createTable("a", [{ id: 1 }]); await db.createTable("c", [{ id: 1 }]); - const all = await db.listTables(); - expect(all.tables).toEqual(["a", "b", "c"]); - expect(all.pageToken).toBeUndefined(); + expect(await collectNames(db.listTables())).toEqual(["a", "b", "c"]); - const first = await db.listTables({ limit: 1 }); - expect(first.tables).toEqual(["a"]); - expect(first.pageToken).toBeDefined(); + const first = db.listTables([], { pageLimit: 1 }); + expect(first.numPageResults()).toBe(0); + expect(await first.next()).toEqual({ done: false, value: "a" }); + expect(first.pageToken()).toBeDefined(); - const second = await db.listTables({ - limit: 1, - pageToken: first.pageToken, + const second = db.listTables([], { + pageLimit: 1, + pageToken: first.pageToken(), }); - expect(second.tables).toEqual(["b"]); + expect(await second.next()).toEqual({ done: false, value: "b" }); }); it("should visit every table exactly once when walking pages", async () => { @@ -167,18 +321,71 @@ describe("given a connection", () => { await db.createTable(name, [{ id: 1 }]); } - const seen: string[] = []; - let pageToken: string | undefined = undefined; - do { - const page: ListTablesResponse = await db.listTables({ - limit: 2, - pageToken, - }); - seen.push(...page.tables); - pageToken = page.pageToken; - } while (pageToken); + expect(await collectNames(db.listTables([], { pageLimit: 2 }))).toEqual( + created, + ); + }); - expect(seen).toEqual(created); + it.each([2 ** 32, 2 ** 32 + 1, Number.MAX_SAFE_INTEGER])( + "should not wrap a large table listing limit %s", + async (limit) => { + await db.createTable("a", [{ id: 1 }]); + await db.createTable("b", [{ id: 2 }]); + for (const names of [ + db.tableNames({ limit }), + db.tableNames([], { limit }), + ]) { + await expect(names).resolves.toEqual(["a", "b"]); + } + for (const namespacePath of [undefined, []]) { + expect(() => + db.listTables(namespacePath, { pageLimit: limit }), + ).toThrow(/limit/); + } + }, + ); + + it.each([ + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + Number.MAX_SAFE_INTEGER + 1, + ])("should reject an invalid table listing limit %s", async (limit) => { + await expect(db.tableNames({ limit })).rejects.toThrow(/limit/); + await expect(db.tableNames([], { limit })).rejects.toThrow(/limit/); + for (const namespacePath of [undefined, []]) { + expect(() => db.listTables(namespacePath, { pageLimit: limit })).toThrow( + /limit/, + ); + } + }); + + it("should preserve zero, small and unsigned-32-bit table listing limits", async () => { + await db.createTable("a", [{ id: 1 }]); + await db.createTable("b", [{ id: 2 }]); + for (const [limit, names] of [ + [0, []], + [1, ["a"]], + [2 ** 32 - 1, ["a", "b"]], + ] as const) { + await expect(db.tableNames({ limit })).resolves.toEqual(names); + } + await expect(db.tableNames()).resolves.toEqual(["a", "b"]); + for (const namespacePath of [undefined, []]) { + for (const pageLimit of [1, 2 ** 31 - 1]) { + expect( + await collectNames(db.listTables(namespacePath, { pageLimit })), + ).toEqual(["a", "b"]); + } + for (const pageLimit of [0, 2 ** 31, 2 ** 32 - 1]) { + expect(() => db.listTables(namespacePath, { pageLimit })).toThrow( + /limit/, + ); + } + } + expect(await collectNames(db.listTables())).toEqual(["a", "b"]); }); it("should list all names and use a default page size of 100", async () => { @@ -191,20 +398,17 @@ describe("given a connection", () => { } await expect(db.tableNames()).resolves.toEqual(names); await expect(db.tableNames({ limit: 0 })).resolves.toEqual([]); - const first = await db.listTables(); - expect(first.tables).toEqual(names.slice(0, 100)); - expect(first.pageToken).toBeDefined(); - const second = await db.listTables({ pageToken: first.pageToken }); - expect(second.tables).toEqual(names.slice(100)); - expect(second.pageToken).toBeUndefined(); - await expect(db.listTables({ limit: 200 })).resolves.toEqual({ - tables: names, - pageToken: undefined, - }); - await expect(db.listTables({ limit: 0 })).resolves.toEqual({ - tables: [], - pageToken: undefined, - }); + const first = db.listTables(); + const firstPage: string[] = []; + for (let i = 0; i < 100; i++) firstPage.push((await first.next()).value!); + expect(firstPage).toEqual(names.slice(0, 100)); + expect(first.pageToken()).toBeDefined(); + expect(first.numPageResults()).toBe(0); + expect(await collectNames(first)).toEqual(names.slice(100)); + expect(await collectNames(db.listTables([], { pageLimit: 200 }))).toEqual( + names, + ); + expect(() => db.listTables([], { pageLimit: 0 })).toThrow(/limit/); }); it("should list tables in a namespace", async () => { @@ -215,12 +419,8 @@ describe("given a connection", () => { await db.createNamespace(["child"]); await db.createTable("nested", [{ id: 1 }], ["child"]); - await expect(db.listTables(["child"])).resolves.toEqual( - expect.objectContaining({ tables: ["nested"] }), - ); - await expect(db.listTables()).resolves.toEqual( - expect.objectContaining({ tables: [] }), - ); + expect(await collectNames(db.listTables(["child"]))).toEqual(["nested"]); + expect(await collectNames(db.listTables())).toEqual([]); }); it("should create tables in v2 mode", async () => { @@ -293,6 +493,69 @@ describe("given a connection", () => { }); }); + describe.each(["createTable", "createEmptyTable"] as const)( + "%s storage options", + (method) => { + const schema = new Schema([new Field("id", new Float64(), true)]); + + it("should accept frozen creation options without storage options", async () => { + const options = Object.freeze({ + dataStorageVersion: "stable", + enableV2ManifestPaths: true, + }); + const table = + method === "createTable" + ? await db.createTable("frozen_options", [{ id: 1 }], options) + : await db.createEmptyTable("frozen_options", schema, options); + expect(await (table as LocalTable).usesV2ManifestPaths()).toBe(true); + expect(options).not.toHaveProperty("storageOptions"); + }); + + it("should accept frozen storage options and preserve override precedence", async () => { + const storageOptions = Object.freeze({ + newTableDataStorageVersion: "legacy", + newTableEnableV2ManifestPaths: "false", + }); + const options = Object.freeze({ + storageOptions, + dataStorageVersion: "stable", + enableV2ManifestPaths: true, + }); + const table = + method === "createTable" + ? await db.createTable("frozen_storage", [{ id: 1 }], options) + : await db.createEmptyTable("frozen_storage", schema, options); + expect(await (table as LocalTable).usesV2ManifestPaths()).toBe(true); + expect(options.storageOptions).toBe(storageOptions); + expect(storageOptions).toEqual({ + newTableDataStorageVersion: "legacy", + newTableEnableV2ManifestPaths: "false", + }); + }); + + it("should not retain a previous override when reusing storage options", async () => { + const storageOptions = { newTableEnableV2ManifestPaths: "false" }; + const create = async (name: string, enableV2ManifestPaths?: boolean) => + method === "createTable" + ? db.createTable(name, [{ id: 1 }], { + storageOptions, + enableV2ManifestPaths, + }) + : db.createEmptyTable(name, schema, { + storageOptions, + enableV2ManifestPaths, + }); + const first = await create("override", true); + expect(await (first as LocalTable).usesV2ManifestPaths()).toBe(true); + const second = await create("without_override"); + expect(await (second as LocalTable).usesV2ManifestPaths()).toBe(false); + expect(storageOptions).toEqual({ + newTableEnableV2ManifestPaths: "false", + }); + }); + }, + ); + it("should be able to migrate tables to the V2 manifest paths", async () => { const db = await connect(tmpDir.name); const table = (await db.createEmptyTable( @@ -451,22 +714,35 @@ describe("namespaces", () => { it("should list namespaces created at the root", async () => { await db.createNamespace(["alpha"]); await db.createNamespace(["beta"]); - const list = await db.listNamespaces(); - expect(list.namespaces).toEqual(expect.arrayContaining(["alpha", "beta"])); + const list = await collectNames(db.listNamespaces()); + expect(list).toEqual(expect.arrayContaining(["alpha", "beta"])); }); it("should list child namespaces under a parent", async () => { await db.createNamespace(["parent"]); await db.createNamespace(["parent", "child"]); - const list = await db.listNamespaces(["parent"]); - expect(list.namespaces).toContain("child"); + const list = await collectNames(db.listNamespaces(["parent"])); + expect(list).toContain("child"); + }); + + it("should resume a namespace listing from its page token", async () => { + await db.createNamespace(["alpha"]); + await db.createNamespace(["beta"]); + const first = db.listNamespaces([], { pageLimit: 1 }); + expect(first.numPageResults()).toBe(0); + expect((await first.next()).value).toBe("alpha"); + const second = db.listNamespaces([], { + pageLimit: 1, + pageToken: first.pageToken(), + }); + expect(await collectNames(second)).toEqual(["beta"]); }); it("should drop a namespace", async () => { await db.createNamespace(["ephemeral"]); await db.dropNamespace(["ephemeral"]); - const list = await db.listNamespaces(); - expect(list.namespaces).not.toContain("ephemeral"); + const list = await collectNames(db.listNamespaces()); + expect(list).not.toContain("ephemeral"); }); it("should raise an error on any namespace op after close", async () => { @@ -474,7 +750,7 @@ describe("namespaces", () => { await expect(db.describeNamespace(["foo"])).rejects.toThrow( "Connection is closed", ); - await expect(db.listNamespaces()).rejects.toThrow("Connection is closed"); + expect(() => db.listNamespaces()).toThrow("Connection is closed"); await expect(db.createNamespace(["foo"])).rejects.toThrow( "Connection is closed", ); diff --git a/nodejs/__test__/experimental_functions.test.ts b/nodejs/__test__/experimental_functions.test.ts new file mode 100644 index 000000000..fdadb092f --- /dev/null +++ b/nodejs/__test__/experimental_functions.test.ts @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { connect } from "../lancedb"; +import { experimentalFunctionsEnabled } from "../lancedb/native"; + +const defaultBuildTest = experimentalFunctionsEnabled() ? it.skip : it; + +defaultBuildTest( + "rejects local Functions before mutating the database", + async () => { + const directory = await mkdtemp(join(tmpdir(), "lancedb-experimental-")); + try { + const db = await connect(directory); + const table = await db.createTable("source", [{ x: 1 }, { x: 2 }]); + const version = await table.version(); + const operations = [ + () => + table.addColumns({ + computed: [{ name: "doubled", valueSql: "x * 2" }], + }), + () => table.refreshColumn("x"), + () => table.refreshColumnAsync("x"), + () => db.createMaterializedView("blocked", "source"), + () => + db.createMaterializedView("blocked", "source", { withNoData: true }), + ]; + for (const operation of operations) { + await expect(operation()).rejects.toThrow("experimental-functions"); + } + expect(await table.version()).toBe(version); + expect(await db.tableNames()).toEqual(["source"]); + await table.addColumns([{ name: "eager", valueSql: "x * 2" }]); + expect((await table.query().toArray()).map((row) => row.eager)).toEqual([ + 2, 4, + ]); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }, +); diff --git a/nodejs/__test__/expr.test.ts b/nodejs/__test__/expr.test.ts new file mode 100644 index 000000000..492929c04 --- /dev/null +++ b/nodejs/__test__/expr.test.ts @@ -0,0 +1,346 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import * as http from "http"; +import type { AddressInfo } from "net"; +import * as tmp from "tmp"; + +import { type Table, connect } from "../lancedb"; +import { + Table as ArrowTable, + Field, + Int64, + Schema, + Utf8, + tableToIPC, +} from "../lancedb/arrow"; +import { Expr, col, func, lit, litBool, litInt } from "../lancedb/expr"; + +describe("expr", () => { + describe("col", () => { + it("returns an Expr instance", () => { + const e = col("age"); + expect(e).toBeInstanceOf(Expr); + }); + + it("preserves camelCase in toSql()", () => { + expect(col("firstName").toSql()).toBe("`firstName`"); + }); + + it("preserves snake_case without quotes", () => { + expect(col("first_name").toSql()).toBe("first_name"); + }); + + it("Quotes identifiers with spaces", () => { + expect(col("first name").toSql()).toBe("`first name`"); + }); + + it("Quotes identifiers with leading digits", () => { + expect(col("2fast").toSql()).toBe("`2fast`"); + }); + + it("Quotes unicode identifiers", () => { + expect(col("名前").toSql()).toBe("`名前`"); + }); + }); + + describe("lit", () => { + it("creates a string literal", () => { + expect(lit("hello").toSql()).toBe("'hello'"); + }); + + it("creates an integer literal", () => { + expect(lit(42).toSql()).toBe("42"); + }); + + it("creates a float literal", () => { + expect(lit(3.14).toSql()).toBe("3.14"); + }); + }); + + describe("numeric literals", () => { + it.each([Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER])( + "preserves the safe integer boundary %s", + (value) => { + expect(lit(value).toSql()).toBe(String(value)); + expect(litInt(value).toSql()).toBe(String(value)); + }, + ); + + it.each([1e20, -1e20])("preserves the large number %s", (value) => { + expect(Number(lit(value).toSql())).toBe(value); + expect(col("price").gt(value).toSql()).toBe( + col("price").gt(lit(value)).toSql(), + ); + }); + + it.each([1.5, 1e20, -1e20, Number.NaN, Number.POSITIVE_INFINITY])( + "rejects %s as an explicit integer literal", + (value) => expect(() => litInt(value)).toThrow(RangeError), + ); + }); + + describe("Expr operators", () => { + it("eq", () => { + expect(col("x").eq(lit(1)).toSql()).toBe("(x = 1)"); + }); + + it("ne", () => { + expect(col("x").ne(lit(1)).toSql()).toBe("(x <> 1)"); + }); + + it("lt", () => { + expect(col("age").lt(lit(18)).toSql()).toBe("(age < 18)"); + }); + + it("lte", () => { + expect(col("age").lte(lit(18)).toSql()).toBe("(age <= 18)"); + }); + + it("gt", () => { + expect(col("age").gt(lit(18)).toSql()).toBe("(age > 18)"); + }); + + it("gte", () => { + expect(col("age").gte(lit(18)).toSql()).toBe("(age >= 18)"); + }); + + it("and", () => { + const e = col("age") + .gt(lit(18)) + .and(col("status").eq(lit("active"))); + expect(e.toSql()).toBe("((age > 18) AND (`status` = 'active'))"); + }); + + it("or", () => { + const e = col("a") + .eq(lit(1)) + .or(col("b").eq(lit(2))); + expect(e.toSql()).toBe("((a = 1) OR (b = 2))"); + }); + + it("not", () => { + const e = col("active").eq(litBool(true)).not(); + expect(e.toSql()).toBe("NOT (active = true)"); + }); + + it("add", () => { + expect(col("x").add(lit(1)).toSql()).toBe("(x + 1)"); + }); + + it("sub", () => { + expect(col("x").sub(lit(1)).toSql()).toBe("(x - 1)"); + }); + + it("mul", () => { + expect(col("price").mul(lit(1.1)).toSql()).toBe("(price * 1.1)"); + }); + + it("div", () => { + expect(col("total").div(lit(2)).toSql()).toBe("(total / 2)"); + }); + }); + + describe("Expr string methods", () => { + it("lower", () => { + expect(col("name").lower().toSql()).toBe("lower(`name`)"); + }); + + it("upper", () => { + expect(col("name").upper().toSql()).toBe("upper(`name`)"); + }); + + it("contains", () => { + expect(col("text").contains(lit("hello")).toSql()).toBe( + "contains(`text`, 'hello')", + ); + }); + }); + + describe("membership and casts", () => { + it("accepts scalar list members", () => { + expect(col("age").isIn([18, 21]).toSql()).toBe("age IN (18, 21)"); + }); + it("casts to an Arrow type", () => { + expect(col("age").cast("Int64").toSql()).toBe("arrow_cast(age, 'Int64')"); + }); + it("rejects an invalid Arrow type", () => { + expect(() => col("age").cast("invalid")).toThrow("Invalid data type"); + }); + }); + + describe("func", () => { + it("lower", () => { + expect(func("lower", col("name")).toSql()).toBe("lower(`name`)"); + }); + }); + + describe("camelCase integration", () => { + let db: Awaited>; + let table: Table; + let tmpDir: tmp.DirResult; + + beforeAll(async () => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + db = await connect(tmpDir.name); + table = await db.createTable("test", [ + { id: 1, firstName: "Alice", lastName: "Smith" }, + { id: 2, firstName: "Bob", lastName: "Jones" }, + { id: 3, firstName: "Charlie", lastName: "Brown" }, + ]); + }); + + afterAll(() => { + table.close(); + db.close(); + tmpDir.removeCallback(); + }); + + it("filters on camelCase column", async () => { + const results = await table + .query() + .where(col("firstName").eq(lit("Alice"))) + .toArray(); + expect(results.length).toBe(1); + expect(results[0].firstName).toBe("Alice"); + }); + + it("filters on multiple camelCase columns", async () => { + const results = await table + .query() + .where( + col("firstName") + .eq(lit("Bob")) + .and(col("lastName").eq(lit("Jones"))), + ) + .toArray(); + expect(results.length).toBe(1); + expect(results[0].firstName).toBe("Bob"); + }); + + it("preserves an unsafe integer filter threshold", async () => { + const prices = await db.createTable("prices", [ + { price: 9.5e18 }, + { price: 1.1e20 }, + ]); + try { + const results = await prices + .query() + .where(col("price").gt(1e20)) + .toArray(); + expect(results.map((row) => row.price)).toEqual([1.1e20]); + } finally { + prices.close(); + } + }); + + it("filters with gt on camelCase column", async () => { + const results = await table + .query() + .where(col("id").gt(lit(1))) + .toArray(); + expect(results.length).toBe(2); + }); + + it.each([ + ["backslash", "\\"], + ["quote", "'"], + ["backslash quote", "\\'"], + ["OR true payload", "\\') OR true --"], + ["line comment payload", "\\' -- OR true"], + ["block comment payload", "\\') /* OR true */ --"], + ])("filters the exact %s value", async (label, value) => { + const escaped = await db.createTable( + `escaped_${label.replaceAll(" ", "_")}`, + [ + { id: 1, tenant: value }, + { id: 2, tenant: "different tenant" }, + ], + ); + try { + const results = await escaped + .query() + .where(col("tenant").eq(lit(value))) + .toArray(); + expect(results).toHaveLength(1); + expect(results[0].id).toBe(1); + expect(results[0].tenant).toBe(value); + } finally { + escaped.close(); + } + }); + }); + + it("sends a quoted expression value to remote as one literal", async () => { + const value = "\\') OR true --"; + const schema = new Schema([ + new Field("id", new Int64(), false), + new Field("tenant", new Utf8(), false), + ]); + const response = Buffer.from(tableToIPC(new ArrowTable(schema), "stream")); + let remoteFilter: unknown; + + const server = http.createServer((req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "tenants", + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: false }, + { name: "tenant", type: { type: "string" }, nullable: false }, + ], + }, + }), + ); + return; + } + if (path.endsWith("/query/")) { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + remoteFilter = JSON.parse(body).filter; + res + .writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + }) + .end(response); + }); + return; + } + res.writeHead(404).end(); + }); + + await new Promise((resolve) => + server.listen(0, "127.0.0.1", resolve), + ); + const address = server.address() as AddressInfo; + + try { + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${address.port}`, + }); + try { + const remoteTable = await db.openTable("tenants"); + await remoteTable + .query() + .where(col("tenant").eq(lit(value))) + .toArrow(); + } finally { + db.close(); + } + } finally { + await new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + } + + expect(remoteFilter).toBe("(tenant = '\\'') OR true --')"); + }); +}); diff --git a/nodejs/__test__/fixtures/transformers_tokenizer.cjs b/nodejs/__test__/fixtures/transformers_tokenizer.cjs new file mode 100644 index 000000000..bf30cc229 --- /dev/null +++ b/nodejs/__test__/fixtures/transformers_tokenizer.cjs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +const assert = require("node:assert/strict"); +const { + TransformersEmbeddingFunction, +} = require("../../dist/embedding/transformers"); +const { getRegistry } = require("../../dist/embedding/registry"); + +async function main() { + const transformers = await import("@huggingface/transformers"); + // Never fetch a real model, including if a loader mock stops intercepting. + transformers.env.allowRemoteModels = false; + transformers.env.allowLocalModels = false; + const modelCalls = []; + const tokenizerCalls = []; + const testCase = Number(process.argv[2]); + const defaults = "Xenova/all-MiniLM-L6-v2"; + const cases = [ + [{}, defaults, defaults], + [{ model: "test/model" }, "test/model", "test/model"], + [ + { model: "test/model", tokenizer: "test/tokenizer" }, + "test/model", + "test/tokenizer", + ], + [ + { model: "test/model", tokenizer: "$var:tokenizer" }, + "test/model", + "test/tokenizer", + ], + [ + { model: "test/model", tokenizer: "test/tokenizer" }, + "test/model", + "test/tokenizer", + ], + ]; + assert.ok( + Number.isInteger(testCase) && testCase >= 0 && testCase < cases.length, + ); + transformers.AutoModel.from_pretrained = async (...args) => { + modelCalls.push(args); + return {}; + }; + transformers.AutoTokenizer.from_pretrained = async (...args) => { + tokenizerCalls.push(args); + if (testCase === 4) throw new Error("missing tokenizer"); + return {}; + }; + getRegistry().setVar("tokenizer", "test/tokenizer"); + const [options, model, tokenizer] = cases[testCase]; + const fn = new TransformersEmbeddingFunction(options); + if (testCase === 4) { + await assert.rejects(fn.init(), /error loading tokenizer test\/tokenizer/); + } else { + await fn.init(); + } + assert.deepEqual(modelCalls, [[model, { dtype: "fp32" }]]); + assert.deepEqual(tokenizerCalls, [[tokenizer]]); + assert.deepEqual(fn.toJSON(), options); +} + +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/nodejs/__test__/materialized_view.test.ts b/nodejs/__test__/materialized_view.test.ts index 3e47a00e9..0840395fe 100644 --- a/nodejs/__test__/materialized_view.test.ts +++ b/nodejs/__test__/materialized_view.test.ts @@ -6,10 +6,13 @@ import * as tmp from "tmp"; import { Connection, connect } from "../lancedb"; import { DEFINITION_META_KEY, + MaterializedView, definitionFromMetadata, } from "../lancedb/materialized_view"; +import { experimentalFunctionsEnabled } from "../lancedb/native"; describe("materialized views", () => { + const experimentalTest = experimentalFunctionsEnabled() ? it : it.skip; let tmpDir: tmp.DirResult; let db: Connection; @@ -69,7 +72,7 @@ describe("materialized views", () => { ); }); - it("creates, refreshes and queries a view", async () => { + experimentalTest("creates, refreshes and queries a view", async () => { const view = await db.createMaterializedView("adults", "people", { select: ["name", ["shout", "upper(name)"]], where: "age >= 18", @@ -81,7 +84,7 @@ describe("materialized views", () => { expect(rows.map((r) => r.shout).sort()).toEqual(["ADA", "GRACE"]); }); - it("round-trips the definition", async () => { + experimentalTest("round-trips the definition", async () => { await db.createMaterializedView("adults", "people", { where: "age >= 18", }); @@ -92,23 +95,36 @@ describe("materialized views", () => { ); }); - it("fully refreshes after an append", async () => { - const view = await db.createMaterializedView("copy", "people", { - withNoData: true, - }); - await view.refresh(); + experimentalTest.each([false, true])( + "fully refreshes after an append (full=%s)", + async (full) => { + const view = await db.createMaterializedView("copy", "people", { + withNoData: true, + }); + await view.refresh(); - const people = await db.openTable("people"); - await people.add([{ name: "alan", age: 41 }]); - const result = await view.refresh(); - expect(result.mode).toBe("rebuild"); - expect(Number(result.rowsWritten)).toBe(4); - expect(await view.table().countRows()).toBe(4); + const people = await db.openTable("people"); + await people.add([{ name: "alan", age: 41 }]); + const result = await view.refresh({ full }); + expect(result.mode).toBe("rebuild"); + expect(Number(result.rowsWritten)).toBe(4); + expect(await view.table().countRows()).toBe(4); - expect((await view.refresh()).mode).toBe("rebuild"); + expect((await view.refresh()).mode).toBe("rebuild"); + }, + ); + + it("forwards a forced refresh and preserves absent remote metrics", async () => { + const view = new MaterializedView(await db.openTable("people")); + const remoteResult = { version: 42 }; + const refresh = jest + .spyOn(view.table(), "refreshMaterializedView") + .mockResolvedValue(remoteResult); + expect(await view.refresh({ full: true })).toEqual(remoteResult); + expect(refresh).toHaveBeenCalledWith(undefined, true); }); - it("lists views and rejects non-views", async () => { + experimentalTest("lists views and rejects non-views", async () => { await db.createMaterializedView("adults", "people", { where: "age >= 18", }); @@ -124,16 +140,20 @@ describe("materialized views", () => { expect(await collect(db.listMaterializedViews())).toEqual([]); }); - it("returns a job when dropping a view asynchronously", async () => { - await db.createMaterializedView("adults", "people"); + experimentalTest( + "returns a job when dropping a view asynchronously", + async () => { + await db.createMaterializedView("adults", "people"); - const job = await db.dropMaterializedViewAsync("adults"); - expect(job.id).toBeNull(); - await job.wait(); - expect(await collect(db.listMaterializedViews())).toEqual([]); - }); + const job = await db.dropMaterializedViewAsync("adults"); + expect(job.id).toBeNull(); + expect(job.jobType).toBeNull(); + await job.wait(); + expect(await collect(db.listMaterializedViews())).toEqual([]); + }, + ); - it("rejects an invalid expression at create time", async () => { + experimentalTest("rejects an invalid expression at create time", async () => { await expect( db.createMaterializedView("bad", "people", { select: [["x", "missing + 1"]], @@ -148,16 +168,21 @@ describe("materialized views", () => { ).rejects.toThrow("non-negative integer"); } expect(await collect(db.listMaterializedViews())).toEqual([]); - - const view = await db.createMaterializedView("copy", "people"); - for (const sourceVersion of [-1, 1.5, Infinity, NaN]) { - await expect(view.refresh({ sourceVersion })).rejects.toThrow( - "non-negative integer", - ); - } }); - it("quotes bare select names", async () => { + experimentalTest( + "rejects invalid source versions before refreshing", + async () => { + const view = await db.createMaterializedView("copy", "people"); + for (const sourceVersion of [-1, 1.5, Infinity, NaN]) { + await expect(view.refresh({ sourceVersion })).rejects.toThrow( + "non-negative integer", + ); + } + }, + ); + + experimentalTest("quotes bare select names", async () => { await db.createTable("odd_names", [{ "order item": "widget" }]); const view = await db.createMaterializedView("quoted", "odd_names", { select: ["order item"], @@ -167,11 +192,14 @@ describe("materialized views", () => { expect(Number(result.rowsWritten)).toBe(1); }); - it("does not require stable row ids on the source", async () => { - await db.createTable("plain", [{ x: 1 }]); - const view = await db.createMaterializedView("v", "plain"); - expect(await view.table().countRows()).toBe(1); - }); + experimentalTest( + "does not require stable row ids on the source", + async () => { + await db.createTable("plain", [{ x: 1 }]); + const view = await db.createMaterializedView("v", "plain"); + expect(await view.table().countRows()).toBe(1); + }, + ); }); async function collect(items: AsyncIterable): Promise { diff --git a/nodejs/__test__/native_symbols.test.ts b/nodejs/__test__/native_symbols.test.ts new file mode 100644 index 000000000..5445867f6 --- /dev/null +++ b/nodejs/__test__/native_symbols.test.ts @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +const { + checkNativeBinary, + findForbiddenUndefinedSymbols, +} = require("../scripts/check-native-symbols.js"); + +test("detects the unresolved AVX-512 symbol from broken musl binaries", () => { + const output = [ + " U napi_create_function", + " U sum_4bit_dist_table_32bytes_batch_avx512", + " U strlen", + ].join("\n"); + + expect(findForbiddenUndefinedSymbols(output)).toEqual([ + "sum_4bit_dist_table_32bytes_batch_avx512", + ]); +}); + +test("accepts native binaries without unresolved internal Lance symbols", () => { + const runNm = jest.fn(() => ({ + status: 0, + stdout: + " U napi_create_function\n U strlen\n", + stderr: "", + })); + + expect(() => checkNativeBinary("lancedb.node", runNm)).not.toThrow(); + expect(runNm).toHaveBeenCalledWith( + "nm", + ["-D", "--undefined-only", "lancedb.node"], + { encoding: "utf8" }, + ); +}); + +test("rejects native binaries with the unresolved AVX-512 symbol", () => { + const runNm = jest.fn(() => ({ + status: 0, + stdout: " U sum_4bit_dist_table_32bytes_batch_avx512\n", + stderr: "", + })); + + expect(() => checkNativeBinary("lancedb.node", runNm)).toThrow( + "lancedb.node contains unresolved internal Lance symbols: sum_4bit_dist_table_32bytes_batch_avx512", + ); +}); diff --git a/nodejs/__test__/nested_blob.test.ts b/nodejs/__test__/nested_blob.test.ts new file mode 100644 index 000000000..508b57c77 --- /dev/null +++ b/nodejs/__test__/nested_blob.test.ts @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import * as tmp from "tmp"; +import { type Table, blob, connect, isBlobField } from "../lancedb"; +import { + DataType, + Field, + Int64, + List, + Schema, + Struct, + Utf8, +} from "../lancedb/arrow"; + +describe('nested blobs with blobMode "bytes"', () => { + let tmpDir: tmp.DirResult; + let table: Table; + + const caption = new Field( + "caption", + new Utf8(), + false, + new Map([["label", "caption"]]), + ); + const info = new Field( + "info", + new Struct([ + blob("image"), + caption, + new Field("preview", new Struct([blob("image")]), true), + ]), + true, + new Map([["label", "info"]]), + ); + const schema = new Schema( + [new Field("id", new Int64(), false), info, blob("cover")], + new Map([["source", "nested-blobs"]]), + ); + + beforeEach(async () => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + const db = await connect(tmpDir.name); + table = await db.createTable( + "nested_blobs", + [ + { + id: 1n, + info: { + image: Buffer.from("hello"), + caption: "first", + preview: { image: Buffer.from("preview") }, + }, + cover: Buffer.from("cover"), + }, + { id: 2n, info: null, cover: null }, + { + id: 3n, + info: { image: null, caption: "third", preview: null }, + cover: null, + }, + { + id: 4n, + info: { + image: Buffer.alloc(0), + caption: "fourth", + preview: { image: null }, + }, + cover: Buffer.alloc(0), + }, + ], + { schema }, + ); + }); + + afterEach(() => tmpDir.removeCallback()); + + it.each([false, true])( + "reads struct leaves across batches (select parent: %s)", + async (selectParent) => { + const query = table + .query() + .orderBy({ columnName: "id", ascending: true }); + if (selectParent) { + query.select(["info"]); + } + const result = await query.toArrow({ + blobMode: "bytes", + maxBatchLength: 1, + }); + expect(result.batches.length).toBeGreaterThan(1); + expect(result.schema.fields.map((field) => field.name)).toEqual( + selectParent ? ["info"] : ["id", "info", "cover"], + ); + expect(result.schema.metadata).toEqual(schema.metadata); + const infoField = result.schema.fields.find( + (field) => field.name === "info", + )!; + expect(infoField.nullable).toBe(true); + expect(infoField.metadata).toEqual(info.metadata); + const fields = (infoField.type as Struct).children; + expect(DataType.isLargeBinary(fields[0].type)).toBe(true); + expect(isBlobField(fields[0])).toBe(false); + expect(fields[0].metadata.size).toBe(0); + expect(fields[1]).toEqual(caption); + expect( + DataType.isLargeBinary((fields[2].type as Struct).children[0].type), + ).toBe(true); + + const rows = result.toArray(); + expect(Buffer.from(rows[0].info.image).toString()).toBe("hello"); + expect(rows[0].info.caption).toBe("first"); + expect(Buffer.from(rows[0].info.preview.image).toString()).toBe( + "preview", + ); + expect(rows[1].info).toBeNull(); + expect(rows[2].info.image).toBeNull(); + expect(rows[2].info.caption).toBe("third"); + expect(rows[2].info.preview).toBeNull(); + expect(Buffer.from(rows[3].info.image)).toEqual(Buffer.alloc(0)); + expect(rows[3].info.preview.image).toBeNull(); + if (!selectParent) { + expect(Buffer.from(rows[0].cover).toString()).toBe("cover"); + expect(rows[1].cover).toBeNull(); + } + }, + ); + + it("reads direct leaf and struct aliases", async () => { + const rows = await table + .query() + .orderBy({ columnName: "id", ascending: true }) + .select({ + image: "info.image", + details: "info", + preview: "info.preview", + caption: "info.caption", + }) + .toArray({ blobMode: "bytes", maxBatchLength: 1 }); + expect(Object.keys(rows[0])).toEqual([ + "image", + "details", + "preview", + "caption", + ]); + expect(Buffer.from(rows[0].image).toString()).toBe("hello"); + expect(Buffer.from(rows[0].details.image).toString()).toBe("hello"); + expect(Buffer.from(rows[0].details.preview.image).toString()).toBe( + "preview", + ); + expect(Buffer.from(rows[0].preview.image).toString()).toBe("preview"); + expect(rows[0].caption).toBe("first"); + expect(rows[1].details).toBeNull(); + expect(rows[1].image).toBeNull(); + expect(rows[2].image).toBeNull(); + expect(Buffer.from(rows[3].image)).toEqual(Buffer.alloc(0)); + }); + + it.each([false, true])( + "preserves a literal scalar alias matching a nested blob path (reverse: %s)", + async (reverse) => { + const projection: [string, string][] = [ + ["info", "info"], + ["info.image", "id"], + ]; + if (reverse) { + projection.reverse(); + } + const [row] = await table + .query() + .where("id = 1") + .select(new Map(projection)) + .toArray({ blobMode: "bytes" }); + expect(row["info.image"]).toBe(1n); + expect(Buffer.from(row.info.image).toString()).toBe("hello"); + }, + ); + + it.each([false, true])( + "materializes every overlapping blob projection (reverse: %s)", + async (reverse) => { + const columns = ["info.image", "info"]; + if (reverse) { + columns.reverse(); + } + const result = await table + .query() + .orderBy({ columnName: "id", ascending: true }) + .select(columns) + .toArrow({ blobMode: "bytes", maxBatchLength: 1 }); + expect(result.schema.fields.map((field) => field.name)).toEqual(columns); + expect(DataType.isLargeBinary(result.getChild("info.image")!.type)).toBe( + true, + ); + expect( + DataType.isLargeBinary( + result.getChild("info")!.getChild("image")!.type, + ), + ).toBe(true); + const rows = result.toArray(); + expect(Buffer.from(rows[0]["info.image"]).toString()).toBe("hello"); + expect(Buffer.from(rows[0].info.image).toString()).toBe("hello"); + expect(rows[0].info.caption).toBe("first"); + expect(rows[1]["info.image"]).toBeNull(); + expect(rows[1].info).toBeNull(); + expect(rows[2]["info.image"]).toBeNull(); + expect(rows[2].info.image).toBeNull(); + expect(Buffer.from(rows[3]["info.image"])).toEqual(Buffer.alloc(0)); + expect(Buffer.from(rows[3].info.image)).toEqual(Buffer.alloc(0)); + }, + ); + + it("materializes dotted aliases independently of nested fields", async () => { + const [row] = await table + .query() + .where("id = 1") + .select({ + details: "info", + "details.image": "info.image", + "details.preview": "info.preview", + "details.preview.image": "info.preview.image", + }) + .toArray({ blobMode: "bytes" }); + expect(Buffer.from(row.details.image).toString()).toBe("hello"); + expect(Buffer.from(row["details.image"]).toString()).toBe("hello"); + expect(Buffer.from(row.details.preview.image).toString()).toBe("preview"); + expect(Buffer.from(row["details.preview"].image).toString()).toBe( + "preview", + ); + expect(Buffer.from(row["details.preview.image"]).toString()).toBe( + "preview", + ); + }); + + it.each([false, true])( + "converts the empty result schema (alias: %s)", + async (alias) => { + const query = table.query().where("id < 0"); + if (alias) { + query.select({ image: "info.image", details: "info" }); + } + const result = await query.toArrow({ blobMode: "bytes" }); + expect(result.numRows).toBe(0); + expect(result.schema.fields.map((field) => field.name)).toEqual( + alias ? ["image", "details"] : ["id", "info", "cover"], + ); + const fields = ( + result.schema.fields.find( + (field) => field.name === (alias ? "details" : "info"), + )!.type as Struct + ).children; + expect(DataType.isLargeBinary(fields[0].type)).toBe(true); + expect(isBlobField(fields[0])).toBe(false); + expect(fields[1]).toEqual(caption); + expect( + DataType.isLargeBinary((fields[2].type as Struct).children[0].type), + ).toBe(true); + if (alias) { + expect(DataType.isLargeBinary(result.schema.fields[0].type)).toBe(true); + } + }, + ); + + it("preserves requested row IDs and leaves subsequent descriptors intact", async () => { + const query = table.query().where("id = 1").select(["info"]); + const [bytes] = await query.toArray({ blobMode: "bytes" }); + expect(Object.keys(bytes)).toEqual(["info"]); + const [description] = await query.toArray(); + expect(Object.keys(description)).toEqual(["info"]); + expect(Number(description.info.image.size)).toBe(5); + const [withRowId] = await query.withRowId().toArray({ blobMode: "bytes" }); + expect(typeof withRowId._rowid).toBe("bigint"); + expect(await table.fetchBlobs("info.image", [withRowId._rowid])).toEqual([ + Buffer.from(withRowId.info.image), + ]); + }); + + it("keeps descriptors in description mode", async () => { + const [description] = await table + .query() + .where("id = 1") + .toArray({ blobMode: "descriptions" }); + expect(Number(description.info.image.size)).toBe(5); + }); + + it("keeps list elements as descriptors alongside struct blob bytes", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable( + "list_blobs", + [ + { + info: { image: Buffer.from("hello"), images: [Buffer.from("list")] }, + }, + ], + { + schema: new Schema([ + new Field( + "info", + new Struct([ + blob("image"), + new Field("images", new List(blob("item")), true), + ]), + true, + ), + ]), + }, + ); + const [bytes] = await table.query().toArray({ blobMode: "bytes" }); + expect(Buffer.from(bytes.info.image).toString()).toBe("hello"); + expect(Number(bytes.info.images.get(0).size)).toBe(4); + const [row] = await table + .query() + .select(["info.images"]) + .toArray({ blobMode: "bytes" }); + expect(Number(row["info.images"].get(0).size)).toBe(4); + expect(Object.keys(row)).toEqual(["info.images"]); + const result = await table.query().toArrow({ blobMode: "bytes" }); + const fields = (result.schema.fields[0].type as Struct).children; + const descriptions = await table.query().toArrow(); + expect(fields[1]).toEqual( + (descriptions.schema.fields[0].type as Struct).children[1], + ); + expect(DataType.isStruct((fields[1].type as List).children[0].type)).toBe( + true, + ); + }); +}); diff --git a/nodejs/__test__/query.test.ts b/nodejs/__test__/query.test.ts index 786f04015..068e55c2f 100644 --- a/nodejs/__test__/query.test.ts +++ b/nodejs/__test__/query.test.ts @@ -538,11 +538,17 @@ describe("IVF search effort", () => { const db = await connect(directory.name); const rows = Array.from({ length: 512 }, (_, id) => ({ id, - vector: Array.from( - { length: 16 }, - (_, j) => - (Math.floor(id / 32) === j ? 1 : 0) + Math.sin(id * 17 + j) * 0.001, - ), + // Keep all eight exact neighbors together even if random IVF training + // splits the first cluster. This tests effort, not training recall. + vector: + id < 8 + ? [...vector] + : Array.from( + { length: 16 }, + (_, j) => + (Math.floor(id / 32) === j ? 1 : 0) + + Math.sin(id * 17 + j) * 0.001, + ), })); table = await db.createTable("effort", rows.slice(0, 256)); await table.add(rows.slice(256)); diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 7e9479f94..8d5c21aa3 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -98,6 +98,57 @@ async function withMockDatabase( } describe("remote connection", () => { + it.each([ + { dataStorageVersion: "2.0" }, + { enableV2ManifestPaths: false }, + { storageOptions: { bogusOptionXyz: "1" } }, + ])("rejects local create options %j before sending data", async (options) => { + const requests: string[] = []; + await withMockDatabase( + (req, res) => { + requests.push(req.url ?? ""); + res.writeHead(200).end(); + }, + async (db) => { + await expect( + db.createTable("test", [{ value: 1 }], { + ...options, + mode: "overwrite", + }), + ).rejects.toThrow(/write_options.*LanceDB Distributed/); + await expect( + db.createEmptyTable( + "test", + new Schema([new Field("value", new Int64(), true)]), + options, + ), + ).rejects.toThrow(/write_options.*LanceDB Distributed/); + }, + ); + expect(requests).toEqual([]); + }); + + it.each([{ indexCacheSize: 5 }, { storageOptions: { x: "y" } }])( + "rejects local open options %j before sending a request", + async (options) => { + const requests: string[] = []; + await withMockDatabase( + (req, res) => { + requests.push(req.url ?? ""); + res.writeHead(200).end(); + }, + async (db) => { + await expect( + db.openTable("test", undefined, options), + ).rejects.toThrow( + /not supported for table access in LanceDB Distributed/, + ); + }, + ); + expect(requests).toEqual([]); + }, + ); + it.each([false, true])( "normalizes remote blob writes (range target: %s)", async (wide) => { @@ -267,7 +318,7 @@ describe("remote connection", () => { ], ]; for (const [run, operation] of cases) { - let message = `LanceDBError: not supported: ${operation} is not supported for remote tables.`; + let message = `LanceDBError: not supported: ${operation} is not supported in LanceDB Distributed.`; if (operation === "IVF_HNSW_PQ") { message += " Please use IVF_HNSW_SQ instead."; } @@ -414,7 +465,7 @@ describe("remote connection", () => { table.add([{ id: 1n }], { allowExternalBlobOutsideBases: true, }), - ).rejects.toThrow("only supported on local tables"); + ).rejects.toThrow("only supported in LanceDB Embedded"); expect(insertRequests).toBe(0); await expect(table.add([{ id: 2n }])).resolves.toMatchObject({ @@ -432,23 +483,6 @@ describe("remote connection", () => { expect(insertRequests).toBe(2); }); - it("lists materialized views through the namespace route", async () => { - await withMockDatabase( - (req, res) => { - expect(req.method).toBe("GET"); - expect(req.url).toBe("/v1/namespace/$/materialized_view/list"); - res - .writeHead(200, { "content-type": "application/json" }) - .end(JSON.stringify({ views: ["daily_sales"] })); - }, - async (db) => { - expect(await collect(db.listMaterializedViews())).toEqual([ - "daily_sales", - ]); - }, - ); - }); - it("creates a view and decodes the schema it resolved to", async () => { await withMockDatabase( (req, res) => { @@ -1676,14 +1710,13 @@ async function collect(items: AsyncIterable): Promise { } describe("lazy resource listings", () => { - for (const kind of ["views", "materializedViews", "jobs"] as const) { + for (const kind of ["views", "jobs"] as const) { const listing = ( db: Connection, options: { pageToken?: string; pageLimit?: number } = {}, ) => { if (kind === "jobs") return db.listJobs(options); - if (kind === "views") return db.listViews(["team"], options); - return db.listMaterializedViews(options); + return db.listViews(["team"], options); }; const page = (names: string[], token?: string) => { const items = @@ -1758,11 +1791,7 @@ describe("lazy resource listings", () => { limit: 2, }); } else { - expect(url.pathname).toBe( - kind === "views" - ? "/v1/namespace/team/view/list" - : "/v1/namespace/$/materialized_view/list", - ); + expect(url.pathname).toBe("/v1/namespace/team/view/list"); expect(url.searchParams.get("page_token")).toBe(token); expect(url.searchParams.get("limit")).toBe("2"); } diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 7d10f8b59..b41d98767 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -47,6 +47,7 @@ import { register, } from "../lancedb/embedding"; import { Index } from "../lancedb/indices"; +import { experimentalFunctionsEnabled } from "../lancedb/native"; import { BooleanQuery, Occur, @@ -1706,6 +1707,39 @@ describe("When creating an index", () => { }); }); + it.each([ + ["IvfPq", Index.ivfPq({ targetPartitionSize: 100 })], + ["IvfFlat", Index.ivfFlat({ targetPartitionSize: 100 })], + ["IvfRq", Index.ivfRq({ targetPartitionSize: 100 })], + ["IvfHnswPq", Index.hnswPq({ targetPartitionSize: 100 })], + ["IvfHnswSq", Index.hnswSq({ targetPartitionSize: 100 })], + ])("should create %s with targetPartitionSize", async (indexType, config) => { + await tbl.createIndex("vec", { config }); + + const indices = await tbl.listIndices(); + expect(indices).toHaveLength(1); + expect(indices[0].indexType).toBe(indexType); + expect( + (indices[0].indexDetails as Record)[ + "target_partition_size" + ], + ).toBe(100); + }); + + it("should prefer numPartitions over targetPartitionSize", async () => { + await tbl.createIndex("vec", { + config: Index.ivfFlat({ numPartitions: 2, targetPartitionSize: 100 }), + }); + + // Lance records the target size the partition count implies: 300 rows / 2. + const indices = await tbl.listIndices(); + expect( + (indices[0].indexDetails as Record)[ + "target_partition_size" + ], + ).toBe(150); + }); + it("should allow me to replace (or not) an existing index", async () => { await tbl.createIndex("id"); // Default is replace=true @@ -3314,51 +3348,64 @@ describe("when dealing with blob columns", () => { ).rejects.toThrow(/blobMode must be/); }); - it("reruns the query when the table changes before the version check", async () => { - const { table, native, update } = await openVersionedBlobTable(); - const liveVersion = native.version.bind(native); - native.version = async () => { - native.version = liveVersion; - await update(2n, "new"); - return liveVersion(); - }; - const [row] = await table.query().toArray({ blobMode: "bytes" }); - expect(row.generation).toBe(2n); - expect(Buffer.from(row.image).toString()).toBe("new"); - }); + it.each([false, true])( + "reruns the query when the table changes before the version check (nested: %s)", + async (nested) => { + const { table, native, update } = await openVersionedBlobTable(nested); + const liveVersion = native.version.bind(native); + native.version = async () => { + native.version = liveVersion; + await update(2n, "new"); + return liveVersion(); + }; + const [row] = await table.query().toArray({ blobMode: "bytes" }); + expect(row.generation).toBe(2n); + expect(Buffer.from(nested ? row.info.image : row.image).toString()).toBe( + "new", + ); + }, + ); - it("reads bytes from the query's version when a write lands before the fetch", async () => { - const { table, native, update } = await openVersionedBlobTable(); - const liveVersion = native.version.bind(native); - native.version = async () => { - native.version = liveVersion; - const version = await liveVersion(); - await update(2n, "new"); - return version; - }; - const [row] = await table.query().toArray({ blobMode: "bytes" }); - expect(row.generation).toBe(1n); - expect(Buffer.from(row.image).toString()).toBe("old"); - }); + it.each([false, true])( + "reads bytes from the query's version when a write lands before the fetch (nested: %s)", + async (nested) => { + const { table, native, update } = await openVersionedBlobTable(nested); + const liveVersion = native.version.bind(native); + native.version = async () => { + native.version = liveVersion; + const version = await liveVersion(); + await update(2n, "new"); + return version; + }; + const [row] = await table.query().toArray({ blobMode: "bytes" }); + expect(row.generation).toBe(1n); + expect(Buffer.from(nested ? row.info.image : row.image).toString()).toBe( + "old", + ); + }, + ); - it("fails when the table changes during every attempt", async () => { - const { table, native, update } = await openVersionedBlobTable(); - const liveVersion = native.version.bind(native); - let generation = 1n; - native.version = async () => { - generation += 1n; - await update(generation, `generation ${generation}`); - return liveVersion(); - }; - try { - await expect( - table.query().toArray({ blobMode: "bytes" }), - ).rejects.toThrow(/changed during each of 3 attempts/); - expect(generation).toBe(4n); - } finally { - native.version = liveVersion; - } - }); + it.each([false, true])( + "fails when the table changes during every attempt (nested: %s)", + async (nested) => { + const { table, native, update } = await openVersionedBlobTable(nested); + const liveVersion = native.version.bind(native); + let generation = 1n; + native.version = async () => { + generation += 1n; + await update(generation, `generation ${generation}`); + return liveVersion(); + }; + try { + await expect( + table.query().toArray({ blobMode: "bytes" }), + ).rejects.toThrow(/changed during each of 3 attempts/); + expect(generation).toBe(4n); + } finally { + native.version = liveVersion; + } + }, + ); it("rejects fetchBlobs on a non-blob column", async () => { const { table, rowIds } = await openBlobTable(); @@ -3385,6 +3432,106 @@ describe("when dealing with blob columns", () => { expect(bytes[0]!.equals(payload)).toBe(true); }); + it("returns bytes for blobs nested in structs", async () => { + const { table, alpha, empty } = await openNestedBlobTable(); + const rows = await table.query().toArray({ blobMode: "bytes" }); + const byId = new Map(rows.map((row) => [Number(row.id), row])); + expect(Buffer.from(byId.get(1)!.info.image)).toEqual(alpha); + expect(byId.get(1)!.info.caption).toBe("one"); + expect(byId.get(2)!.info.image).toBeNull(); + expect(byId.get(2)!.info.caption).toBe("two"); + expect(byId.get(3)!.info).toBeNull(); + expect(Buffer.from(byId.get(4)!.info.image)).toEqual(empty); + }); + + it("lines up nested rows and bytes across single-row batches", async () => { + const { table, alpha, empty } = await openNestedBlobTable(); + const result = await table + .query() + .toArrow({ blobMode: "bytes", maxBatchLength: 1 }); + expect(result.batches.length).toBe(4); + const byId = new Map(result.toArray().map((row) => [Number(row.id), row])); + expect(Buffer.from(byId.get(1)!.info.image)).toEqual(alpha); + expect(byId.get(1)!.info.caption).toBe("one"); + expect(byId.get(2)!.info.image).toBeNull(); + expect(byId.get(2)!.info.caption).toBe("two"); + expect(byId.get(3)!.info).toBeNull(); + expect(Buffer.from(byId.get(4)!.info.image)).toEqual(empty); + }); + + it("handles struct fields named like Object prototypes", async () => { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field( + "info", + new Struct([ + new Field("constructor", new Struct([blob("image")]), true), + ]), + true, + ), + ]); + const payload = Buffer.from("proto"); + const table = await db.createTable( + "prototype_named_blobs", + [{ id: 1n, info: { constructor: { image: payload } } }], + { schema }, + ); + expect(await table.blobColumns()).toEqual(["info.constructor.image"]); + const [row] = await table.query().toArray({ blobMode: "bytes" }); + // Arrow's StructRow shadows the `constructor` property, so read the + // field through the JSON form instead of property access. + const info = JSON.parse(JSON.stringify(row.info)); + expect(Buffer.from(Object.values(info.constructor.image))).toEqual( + payload, + ); + }); + + it("returns nested blob bytes for a struct selection", async () => { + const { table, alpha } = await openNestedBlobTable(); + const [row] = await table + .query() + .where("id = 1") + .select(["info"]) + .toArray({ blobMode: "bytes" }); + expect(Object.keys(row)).toEqual(["info"]); + expect(Buffer.from(row.info.image)).toEqual(alpha); + expect(row.info.caption).toBe("one"); + }); + + it("returns nested blob bytes through aliases", async () => { + const { table, alpha } = await openNestedBlobTable(); + const [row] = await table + .query() + .where("id = 1") + .select( + new Map([ + ["picture", "info.image"], + ["details", "info"], + ]), + ) + .toArray({ blobMode: "bytes" }); + expect(Buffer.from(row.picture)).toEqual(alpha); + expect(Buffer.from(row.details.image)).toEqual(alpha); + expect(row.details.caption).toBe("one"); + }); + + it("returns a nested bytes schema for an empty result", async () => { + const { table } = await openNestedBlobTable(); + const result = await table + .query() + .where("id > 100") + .toArrow({ blobMode: "bytes" }); + expect(result.numRows).toBe(0); + const field = result.schema.fields.find((f) => f.name === "info")!; + expect(arrow.DataType.isStruct(field.type)).toBe(true); + const image = (field.type as Struct).children.find( + (f) => f.name === "image", + )!; + expect(arrow.DataType.isLargeBinary(image.type)).toBe(true); + expect(isBlobField(image)).toBe(false); + }); + it("creates list blobs without advertising unfetchable elements", async () => { const db = await connect(tmpDir.name); const schema = new Schema([ @@ -3542,18 +3689,28 @@ describe("when dealing with blob columns", () => { ).map((value) => (value == null ? null : Number(value.size))); } - async function openVersionedBlobTable() { + async function openVersionedBlobTable(nested = false) { const db = await connect(tmpDir.name, { storageOptions: { newTableEnableStableRowIds: "true" }, }); const schema = new Schema([ new Field("id", new Int64(), false), new Field("generation", new Int64(), true), - blob("image"), + nested + ? new Field("info", new Struct([blob("image")]), true) + : blob("image"), ]); const table = await db.createTable( "versions", - [{ id: 1n, generation: 1n, image: Buffer.from("old") }], + [ + { + id: 1n, + generation: 1n, + ...(nested + ? { info: { image: Buffer.from("old") } } + : { image: Buffer.from("old") }), + }, + ], { schema }, ); const native = ( @@ -3563,7 +3720,15 @@ describe("when dealing with blob columns", () => { await table .mergeInsert("id") .whenMatchedUpdateAll() - .execute([{ id: 1n, generation, image: Buffer.from(image) }]); + .execute([ + { + id: 1n, + generation, + ...(nested + ? { info: { image: Buffer.from(image) } } + : { image: Buffer.from(image) }), + }, + ]); }; return { table, native, update }; } @@ -3593,6 +3758,31 @@ describe("when dealing with blob columns", () => { return { table, rowIds, alpha, beta }; } + async function openNestedBlobTable() { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field( + "info", + new Struct([blob("image"), new Field("caption", new Utf8(), true)]), + true, + ), + ]); + const alpha = Buffer.from("alpha"); + const empty = Buffer.alloc(0); + const table = await db.createTable( + "nested_blobs", + [{ id: 1n, info: { image: alpha, caption: "one" } }], + { schema }, + ); + await table.add([ + { id: 2n, info: { image: null, caption: "two" } }, + { id: 3n, info: null }, + { id: 4n, info: { image: empty, caption: "four" } }, + ]); + return { table, alpha, empty }; + } + async function openExternalBlobTable() { const db = await connect(path.join(tmpDir.name, "db")); const payload = Buffer.from("external-payload"); @@ -3742,6 +3932,21 @@ describe("when optimizing a dataset", () => { expect(stats.prune.oldVersionsRemoved).toBe(2); }); + it("retains tagged versions older than the cleanup cutoff", async () => { + await (await table.tags()).create("keep", 1); + await table.add([{ id: 3 }]); + + const cutoff = await nextMillisecond(); + const stats = await table.optimize({ cleanupOlderThan: cutoff }); + // Versions 2 and 3 are pruned, tagged version 1 is retained + expect(stats.prune.oldVersionsRemoved).toBe(2); + + await table.checkout("keep"); + expect(await table.countRows()).toBe(1); + await table.checkoutLatest(); + expect(await table.countRows()).toBe(3); + }); + it("delete unverified", async () => { const version = await table.version(); const versionFile = `${tmpDir.name}/${table.name}.lance/_versions/${String( @@ -4354,14 +4559,14 @@ describe.each(arrowVersions)( ]; const table = await db.createTable("prewarm_data_test", data); - // prewarmData is only supported on remote tables. We verify the call + // prewarmData is only supported in LanceDB Distributed. 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 on remote tables", + "prewarm_data is currently only supported in LanceDB Distributed", ); await expect(table.prewarmData(["text"])).rejects.toThrow( - "prewarm_data is currently only supported on remote tables", + "prewarm_data is currently only supported in LanceDB Distributed", ); }); @@ -5306,13 +5511,14 @@ describe("LSM convergence and stats", () => { }); describe("computed columns", () => { + const experimentalTest = experimentalFunctionsEnabled() ? it : it.skip; let tmpDir: tmp.DirResult; beforeEach(() => { tmpDir = tmp.dirSync({ unsafeCleanup: true }); }); afterEach(() => tmpDir.removeCallback()); - it("declares a column and fills it on refresh", async () => { + experimentalTest("declares a column and fills it on refresh", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("computed", [{ x: 1 }, { x: 2 }]); @@ -5333,11 +5539,11 @@ describe("computed columns", () => { const db = await connect(tmpDir.name); const table = await db.createTable("errors_local", [{ x: 1 }]); await expect(table.functionErrors()).rejects.toThrow( - "LanceDB Cloud and Enterprise", + "recorded only in LanceDB Distributed", ); }); - it("returns a job handle from refreshColumnAsync", async () => { + experimentalTest("returns a job handle from refreshColumnAsync", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("computed_job", [{ x: 1 }, { x: 2 }]); @@ -5359,7 +5565,7 @@ describe("computed columns", () => { ); }); - it("fills rows added since the last refresh", async () => { + experimentalTest("fills rows added since the last refresh", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("computed_append", [{ x: 1 }]); diff --git a/nodejs/__test__/transformers.test.ts b/nodejs/__test__/transformers.test.ts new file mode 100644 index 000000000..ac66c1499 --- /dev/null +++ b/nodejs/__test__/transformers.test.ts @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { execFileSync } from "node:child_process"; +import { resolve } from "node:path"; + +describe("Transformers embedding tokenizer selection", () => { + // Run init's native ESM import outside Jest's CommonJS sandbox, like a user. + // The fixture mocks model loading and forbids local/remote model access. + test.each([ + ["default model", 0], + ["default tokenizer", 1], + ["custom tokenizer", 2], + ["tokenizer registry variable", 3], + ["tokenizer loading error", 4], + ])("handles %s", (_name, testCase) => { + execFileSync( + process.execPath, + [ + resolve(__dirname, "fixtures", "transformers_tokenizer.cjs"), + String(testCase), + ], + { stdio: "pipe", timeout: 15_000 }, + ); + }); +}); diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index 68b35e256..56c8e1897 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -61,6 +61,7 @@ import { import { inferSchema } from "./schema"; export * from "apache-arrow"; +export type { Data as ArrowData } from "apache-arrow"; export type SchemaLike = | Schema | { diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index 82729644c..4cfcaf990 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 remote table. + * read stops, including in-flight requests to a LanceDB Distributed table. */ signal?: AbortSignal; }; diff --git a/nodejs/lancedb/catalog.ts b/nodejs/lancedb/catalog.ts index e344d8187..c91e5a70f 100644 --- a/nodejs/lancedb/catalog.ts +++ b/nodejs/lancedb/catalog.ts @@ -82,12 +82,16 @@ export class Catalog { return new LocalConnection(await this.inner.connectDatabase(name)); } - /** Drop an empty database. The server rejects nonempty databases. */ + /** + * Drop a database. A nonempty database is an error unless `cascade` is set, + * which drops everything in it first; the name stays taken until the server + * finishes cleaning up their storage. + */ async dropDatabase( name: string, - options: { ignoreMissing?: boolean } = {}, + options: { ignoreMissing?: boolean; cascade?: boolean } = {}, ): Promise { - await this.inner.dropDatabase(name, options.ignoreMissing); + await this.inner.dropDatabase(name, options.ignoreMissing, options.cascade); } /** diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 11341a8c6..d5a856894 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -30,16 +30,12 @@ import type { DescribeNamespaceResponse, DropNamespaceResponse, JobInfo, - ListNamespacesResponse, - ListTablesResponse, } from "./native"; import { ViewDescription, viewDescriptionFromNative } from "./view"; export type { CreateNamespaceResponse, DescribeNamespaceResponse, DropNamespaceResponse, - ListNamespacesResponse, - ListTablesResponse, }; import { sanitizeTable } from "./sanitize"; import { LocalTable, Table } from "./table"; @@ -53,8 +49,11 @@ export interface CreateTableOptions { * happen. Any provided data will be ignored. * * If this is set to "overwrite" then any existing table will be replaced. + * + * If this is set to "exist_ok" then an existing table is opened and any + * provided data is ignored. */ - mode: "create" | "overwrite"; + mode: "create" | "overwrite" | "exist_ok"; /** * If this is true and the table already exists and the mode is "create" * then no error will be raised. @@ -138,7 +137,7 @@ export interface OpenTableOptions { } /** - * @deprecated Use {@link ListTablesOptions} with {@link Connection.listTables} + * @deprecated Use {@link ListingOptions} with {@link Connection.listTables} * instead. */ export interface TableNamesOptions { @@ -154,32 +153,6 @@ export interface TableNamesOptions { limit?: number; } -export interface ListTablesOptions { - /** - * Token from a previous response, to resume listing where it left off. - * - * The token is opaque: it carries whatever the database needs to resume, and - * callers should not construct or interpret one. - */ - pageToken?: string; - /** - * An upper bound on how many tables to return. - * Defaults to 100. Zero returns an empty page without a continuation token. - * - * A page may hold fewer than this and still not be the last one, so keep - * going while the response carries a page token rather than while pages are - * full. - */ - limit?: number; -} - -export interface ListNamespacesOptions { - /** Token from a previous response for pagination. */ - pageToken?: string; - /** An optional limit to the number of results to return. */ - limit?: number; -} - export interface CreateNamespaceOptions { /** Creation mode. */ mode?: "create" | "exist_ok" | "overwrite"; @@ -275,45 +248,18 @@ export abstract class Connection { options?: Partial, ): Promise; - /** - * List a page of the tables in this database. - * - * To retrieve the tables after the page, pass the `pageToken` the response - * carries back in. A page can be shorter than `limit` without being the last - * one, so walk until a response carries no page token: - * + /** Lazily list tables in a namespace, requesting 100 per page by default. + * @example * ```ts - * const names = []; - * let pageToken = undefined; - * do { - * const page = await conn.listTables({ pageToken, limit: 100 }); - * names.push(...page.tables); - * pageToken = page.pageToken; - * } while (pageToken); + * for await (const name of conn.listTables([], { pageLimit: 20 })) { + * console.log(name); + * } * ``` - * - * @param {Partial} options - Pagination options - * (`pageToken`, `limit`). - * @returns {Promise} A page of table names and an - * optional token for the tables after it. - */ - abstract listTables( - options?: Partial, - ): Promise; - /** - * List a page of the tables in this database. - * - * @param {string[]} namespacePath - The namespace path to list tables from - * (defaults to root namespace) - * @param {Partial} options - Pagination options - * (`pageToken`, `limit`). - * @returns {Promise} A page of table names and an - * optional token for the tables after it. */ abstract listTables( namespacePath?: string[], - options?: Partial, - ): Promise; + options?: ListingOptions, + ): Listing; /** * Open a table in the database. @@ -324,6 +270,10 @@ export abstract class Connection { /** * 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. + * * The view is populated before creation returns. Set `withNoData` to create * only its definition and empty backing table. The view is a normal table: * it can be queried, indexed and searched, and it appears in `tableNames`. @@ -358,8 +308,8 @@ export abstract class Connection { /** * Drop the materialized view named `name`. * - * The view may become unavailable before physical cleanup finishes. Use - * {@link dropMaterializedViewAsync} to retain and wait for the cleanup job. + * Remote drops wait for the SQL command to remove the catalog binding. + * Physical cleanup continues in the background. * * Rejects a table that exists but is not a materialized view. */ @@ -369,8 +319,9 @@ export abstract class Connection { ): Promise; /** - * Start dropping the materialized view named `name` and return its cleanup - * job without waiting for completion. + * Start dropping the materialized view named `name` and return its job. + * Remote jobs have type `query` and use the SQL query ID as `id`. Waiting + * confirms catalog removal; physical cleanup continues in the background. * * Rejects a table that exists but is not a materialized view. */ @@ -539,23 +490,11 @@ export abstract class Connection { namespacePath: string[], ): Promise; - /** - * List the immediate child namespaces under the given parent. - * - * Results may be paginated. To retrieve subsequent pages, pass the - * `pageToken` returned by a previous call. - * - * @param {string[]} namespacePath - The parent namespace path. Defaults - * to the root namespace if omitted. - * @param {Partial} options - Pagination options - * (`pageToken`, `limit`). - * @returns {Promise} Child namespace names and - * an optional token for fetching the next page. - */ + /** Lazily list immediate child namespaces, 100 per page by default. */ abstract listNamespaces( namespacePath?: string[], - options?: Partial, - ): Promise; + options?: ListingOptions, + ): Listing; /** * Create a new namespace at the given path. @@ -620,7 +559,7 @@ export abstract class Connection { /** * Rename a table. * - * Currently only supported by LanceDB Cloud. Local OSS connections and + * Currently only supported in LanceDB Distributed. LanceDB Embedded connections and * namespace-backed connections (via {@link connectNamespace}) reject with * a "not supported" error. * @@ -717,13 +656,13 @@ export class LocalConnection extends Connection { } else { // First argument is options object (backwards compatibility) namespacePath = undefined; - tableNamesOptions = namespacePathOrOptions; + tableNamesOptions = namespacePathOrOptions ?? options; } return this.inner.tableNames( namespacePath ?? [], tableNamesOptions?.startAfter, - tableNamesOptions?.limit, + normalizeTableListingLimit(tableNamesOptions?.limit), ); } @@ -818,22 +757,17 @@ export class LocalConnection extends Connection { ); } - async listTables( - namespacePathOrOptions?: string[] | Partial, - options?: Partial, - ): Promise { - // Detect if first argument is namespacePath array or options object - const namespacePath = Array.isArray(namespacePathOrOptions) - ? namespacePathOrOptions - : undefined; - const listTablesOptions = Array.isArray(namespacePathOrOptions) - ? options - : namespacePathOrOptions; - - return this.inner.listTables( - namespacePath ?? [], - listTablesOptions?.pageToken, - listTablesOptions?.limit, + listTables( + namespacePath?: string[], + options: ListingOptions = {}, + ): Listing { + validateListingOptions(options); + return new Listing( + this.inner.listTables( + namespacePath ?? [], + options.pageToken, + options.pageLimit, + ), ); } @@ -890,23 +824,24 @@ export class LocalConnection extends Connection { private getStorageOptions( options?: Partial, ): Record | undefined { + let storageOptions = options?.storageOptions; if (options?.dataStorageVersion !== undefined) { - if (options.storageOptions === undefined) { - options.storageOptions = {}; - } - options.storageOptions["newTableDataStorageVersion"] = - options.dataStorageVersion; + storageOptions = { + ...storageOptions, + newTableDataStorageVersion: options.dataStorageVersion, + }; } if (options?.enableV2ManifestPaths !== undefined) { - if (options.storageOptions === undefined) { - options.storageOptions = {}; - } - options.storageOptions["newTableEnableV2ManifestPaths"] = - options.enableV2ManifestPaths ? "true" : "false"; + storageOptions = { + ...storageOptions, + newTableEnableV2ManifestPaths: options.enableV2ManifestPaths + ? "true" + : "false", + }; } - return cleanseStorageOptions(options?.storageOptions); + return cleanseStorageOptions(storageOptions); } async createTable( @@ -939,7 +874,7 @@ export class LocalConnection extends Connection { } else { // Third argument is options object (backwards compatibility) namespacePath = undefined; - createOptions = namespacePathOrOptions; + createOptions = namespacePathOrOptions ?? options; } return this._createTableImpl(name, data, namespacePath, createOptions); @@ -986,7 +921,7 @@ export class LocalConnection extends Connection { } else { // Third argument is options object (backwards compatibility) namespacePath = undefined; - createOptions = namespacePathOrOptions; + createOptions = namespacePathOrOptions ?? options; } let mode: string = createOptions?.mode ?? "create"; @@ -1035,12 +970,15 @@ export class LocalConnection extends Connection { listNamespaces( namespacePath?: string[], - options?: Partial, - ): Promise { - return this.inner.listNamespaces( - namespacePath ?? [], - options?.pageToken, - options?.limit, + options: ListingOptions = {}, + ): Listing { + validateListingOptions(options); + return new Listing( + this.inner.listNamespaces( + namespacePath ?? [], + options.pageToken, + options.pageLimit, + ), ); } @@ -1103,6 +1041,13 @@ export class LocalConnection extends Connection { } } +function normalizeTableListingLimit(limit?: number): number | undefined { + validateNonNegativeInteger(limit, "limit"); + // The native binding takes u32: larger JS numbers otherwise wrap to zero or + // a smaller page size. A listing limit is an upper bound, so saturate it. + return limit === undefined ? undefined : Math.min(limit, 0xffffffff); +} + /** * Takes storage options and makes all the keys snake case. */ diff --git a/nodejs/lancedb/embedding/transformers.ts b/nodejs/lancedb/embedding/transformers.ts index 06043ea7c..7e57bc6bc 100644 --- a/nodejs/lancedb/embedding/transformers.ts +++ b/nodejs/lancedb/embedding/transformers.ts @@ -38,6 +38,7 @@ export class TransformersEmbeddingFunction extends EmbeddingFunction< #model?: import("@huggingface/transformers").PreTrainedModel; #tokenizer?: import("@huggingface/transformers").PreTrainedTokenizer; #modelName: XenovaTransformerOptions["model"]; + #tokenizerName: string; #initialized = false; #tokenizerOptions: XenovaTransformerOptions["tokenizerOptions"]; #ndims?: number; @@ -58,6 +59,7 @@ export class TransformersEmbeddingFunction extends EmbeddingFunction< this.#ndims = options.ndims; this.#modelName = modelName; + this.#tokenizerName = options.tokenizer ?? modelName; } async init() { @@ -86,11 +88,11 @@ export class TransformersEmbeddingFunction extends EmbeddingFunction< } try { this.#tokenizer = await transformers.AutoTokenizer.from_pretrained( - this.#modelName, + this.#tokenizerName, ); } catch (e) { throw new Error( - `error loading tokenizer for ${this.#modelName}. Make sure you are using a wasm compatible model:\nReason: ${e}`, + `error loading tokenizer ${this.#tokenizerName}. Make sure you are using a wasm compatible model:\nReason: ${e}`, ); } this.#initialized = true; diff --git a/nodejs/lancedb/expr.ts b/nodejs/lancedb/expr.ts new file mode 100644 index 000000000..5880bec60 --- /dev/null +++ b/nodejs/lancedb/expr.ts @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { + Expr as NativeExpr, + col as nativeCol, + func as nativeFunc, + lit as nativeLit, + litBool as nativeLitBool, + litInt as nativeLitInt, +} from "./native.js"; + +export { Expr as NativeExpr } from "./native"; + +/** Values accepted by expression operators. */ +export type ExprLike = Expr | string | number | boolean; + +function coerce(value: ExprLike): Expr { + if (value instanceof Expr) { + return value; + } + if (typeof value === "string") { + return lit(value); + } + if (typeof value === "boolean") { + return litBool(value); + } + if (typeof value === "number") { + return lit(value); + } + throw new TypeError(`Unsupported literal type: ${typeof value}`); +} + +/** + * A SQL expression backed by the shared LanceDB expression builder. + * + * @example + * ```ts + * table.query().where(col("firstName").eq("Alice")).toArray(); + * ``` + */ +export class Expr { + inner: NativeExpr; + + constructor(inner: NativeExpr) { + this.inner = inner; + } + + /** Compare for equality. */ + eq(other: ExprLike): Expr { + return new Expr(this.inner.eq(coerce(other).inner)); + } + + /** Compare for inequality. */ + ne(other: ExprLike): Expr { + return new Expr(this.inner.ne(coerce(other).inner)); + } + + /** Compare for less than. */ + lt(other: ExprLike): Expr { + return new Expr(this.inner.lt(coerce(other).inner)); + } + + /** Compare for less than or equal to. */ + lte(other: ExprLike): Expr { + return new Expr(this.inner.lte(coerce(other).inner)); + } + + /** Compare for greater than. */ + gt(other: ExprLike): Expr { + return new Expr(this.inner.gt(coerce(other).inner)); + } + + /** Compare for greater than or equal to. */ + gte(other: ExprLike): Expr { + return new Expr(this.inner.gte(coerce(other).inner)); + } + + /** Combine two predicates with AND. */ + and(other: Expr): Expr { + return new Expr(this.inner.and(other.inner)); + } + + /** Combine two predicates with OR. */ + or(other: Expr): Expr { + return new Expr(this.inner.or(other.inner)); + } + + /** Negate this predicate. */ + not(): Expr { + return new Expr(this.inner.not()); + } + + /** Add a value. */ + add(other: ExprLike): Expr { + return new Expr(this.inner.add(coerce(other).inner)); + } + + /** Subtract a value. */ + sub(other: ExprLike): Expr { + return new Expr(this.inner.sub(coerce(other).inner)); + } + + /** Multiply by a value. */ + mul(other: ExprLike): Expr { + return new Expr(this.inner.mul(coerce(other).inner)); + } + + /** Divide by a value. */ + div(other: ExprLike): Expr { + return new Expr(this.inner.div(coerce(other).inner)); + } + + /** Convert a string to lowercase. */ + lower(): Expr { + return new Expr(this.inner.lower()); + } + + /** Convert a string to uppercase. */ + upper(): Expr { + return new Expr(this.inner.upper()); + } + + /** Test whether a string contains a substring. */ + contains(substr: ExprLike): Expr { + return new Expr(this.inner.contains(coerce(substr).inner)); + } + + /** Test membership in a list of values. */ + isIn(values: ExprLike[]): Expr { + return new Expr(this.inner.isIn(values.map((v) => coerce(v).inner))); + } + + /** Cast to an Arrow data type, such as "Int64". */ + cast(dataType: string): Expr { + return new Expr(this.inner.cast(dataType)); + } + + /** Serialize with the LanceDB SQL dialect, preserving column case. */ + toSql(): string { + return this.inner.toSql(); + } +} + +/** Reference a column by its exact, case-sensitive name. */ +export function col(name: string): Expr { + return new Expr(nativeCol(name)); +} + +/** Create a string or numeric literal. Unsafe integers are represented as Float64. */ +export function lit(value: string | number): Expr { + if (typeof value === "string") { + return new Expr(nativeLit(value)); + } + if (Number.isSafeInteger(value)) { + return new Expr(nativeLitInt(value)); + } + return new Expr(nativeLit(value)); +} + +/** Create a boolean literal. */ +export function litBool(value: boolean): Expr { + return new Expr(nativeLitBool(value)); +} + +/** Create an Int64 literal from a JavaScript safe integer. Other numbers throw RangeError. */ +export function litInt(value: number): Expr { + if (!Number.isSafeInteger(value)) { + throw new RangeError("Integer literals must be safe integers"); + } + return new Expr(nativeLitInt(value)); +} + +/** Call a registered SQL function, such as `func("lower", col("firstName"))`. */ +export function func(name: string, ...args: ExprLike[]): Expr { + return new Expr( + nativeFunc( + name, + args.map((a) => coerce(a).inner), + ), + ); +} diff --git a/nodejs/lancedb/header.ts b/nodejs/lancedb/header.ts index bf86c5332..4926ccec9 100644 --- a/nodejs/lancedb/header.ts +++ b/nodejs/lancedb/header.ts @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors /** - * Header providers for LanceDB remote connections. + * Header providers for LanceDB Enterprise connections. * * This module provides a flexible header management framework for LanceDB remote * connections, allowing users to implement custom header strategies for diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 1057e2d53..52f94f554 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -97,13 +97,9 @@ export { Connection, CreateTableOptions, TableNamesOptions, - ListTablesOptions, OpenTableOptions, - ListNamespacesOptions, CreateNamespaceOptions, DropNamespaceOptions, - ListNamespacesResponse, - ListTablesResponse, CreateNamespaceResponse, DropNamespaceResponse, DescribeNamespaceResponse, @@ -211,6 +207,8 @@ export { MultiVector, } from "./arrow"; export { IntoSql, packBits } from "./util"; +export { Expr, col, lit, litBool, litInt, func } from "./expr"; +export type { ExprLike } from "./expr"; /** * Options for tokenizing a full-text search query without a table index. @@ -290,11 +288,11 @@ export async function tokenize( * * Accepted formats: * - * - `/path/to/database` - local database + * - `/path/to/database` - database on the local file system * - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage - * - `db://host:port` - remote database (LanceDB cloud) + * - `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database * @param {string} uri - The uri of the database. If the database uri starts - * with `db://` then it connects to a remote database. + * with `db://` then it connects to LanceDB Enterprise or LanceDB Cloud (legacy). * @see {@link ConnectionOptions} for more details on the URI format. * @param options - The options to use when connecting to the database * @example @@ -335,9 +333,9 @@ export async function connect( * * Accepted formats: * - * - `/path/to/database` - local database + * - `/path/to/database` - database on the local file system * - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage - * - `db://host:port` - remote database (LanceDB cloud) + * - `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database * @param options - The options to use when connecting to the database * @see {@link ConnectionOptions} for more details on the URI format. * @example @@ -420,10 +418,10 @@ export async function connect( throw new Error("uri is required"); } - finalOptions = (finalOptions as ConnectionOptions) ?? {}; - (finalOptions).storageOptions = cleanseStorageOptions( - (finalOptions).storageOptions, - ); + finalOptions = { + ...finalOptions, + storageOptions: cleanseStorageOptions(finalOptions.storageOptions), + }; // Create native header provider if one was provided let nativeProvider: NativeJsHeaderProvider | undefined; @@ -535,7 +533,7 @@ function restConfigToProperties( * Connect to a LanceDB database through a namespace. * * Unlike {@link connect}, which routes by URI scheme (local path vs. - * `db://` cloud), `connectNamespace` always returns a namespace-backed + * `db://`), `connectNamespace` always returns a namespace-backed * connection. The `implName` selects the namespace implementation: * * - `"dir"` — directory namespace, configured with {@link DirNamespaceConfig}. @@ -630,11 +628,10 @@ export async function connectNamespace( properties = configOrProperties as Record; } - const finalOptions: ConnectNamespaceOptions = (options ?? - {}) as ConnectNamespaceOptions; - finalOptions.storageOptions = cleanseStorageOptions( - finalOptions.storageOptions, - ); + const finalOptions: ConnectNamespaceOptions = { + ...options, + storageOptions: cleanseStorageOptions(options?.storageOptions), + }; const nativeConn = await LanceDbConnection.newWithNamespace( implName, diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts index 43d1cf1b5..4b1b422bf 100644 --- a/nodejs/lancedb/indices.ts +++ b/nodejs/lancedb/indices.ts @@ -11,8 +11,9 @@ export interface IvfPqOptions { * The number of IVF partitions to create. * * This value should generally scale with the number of rows in the dataset. - * By default the number of partitions is the square root of the number of - * rows. + * When set, this takes precedence over `targetPartitionSize`. When omitted, + * the partition count is derived from `targetPartitionSize`, which defaults + * to 8192 rows for this index type. * * If this value is too large then the first part of the search (picking the * right partition) will be slow. If this value is too small then the second @@ -20,6 +21,21 @@ export interface IvfPqOptions { */ numPartitions?: number; + /** + * The target number of rows in each IVF partition. + * + * This is an alternative to `numPartitions`. When it is set and + * `numPartitions` is not, the number of partitions is derived by dividing + * the number of rows by this value. When both are set, `numPartitions` is + * used and this value is ignored. When neither is set, the target is + * 8192 rows. + * + * Larger partitions mean fewer of them, which makes the first part of the + * search (picking the right partitions) faster and the second part + * (searching within a partition) slower. + */ + targetPartitionSize?: number; + /** * Number of sub-vectors of PQ. * @@ -117,8 +133,9 @@ export interface IvfRqOptions { * The number of IVF partitions to create. * * This value should generally scale with the number of rows in the dataset. - * By default the number of partitions is the square root of the number of - * rows. + * When set, this takes precedence over `targetPartitionSize`. When omitted, + * the partition count is derived from `targetPartitionSize`, which defaults + * to 4096 rows for this index type. * * If this value is too large then the first part of the search (picking the * right partition) will be slow. If this value is too small then the second @@ -126,12 +143,28 @@ export interface IvfRqOptions { */ numPartitions?: number; + /** + * The target number of rows in each IVF partition. + * + * This is an alternative to `numPartitions`. When it is set and + * `numPartitions` is not, the number of partitions is derived by dividing + * the number of rows by this value. When both are set, `numPartitions` is + * used and this value is ignored. When neither is set, the target is + * 4096 rows. + * + * Larger partitions mean fewer of them, which makes the first part of the + * search (picking the right partitions) faster and the second part + * (searching within a partition) slower. + */ + targetPartitionSize?: number; + /** * Number of bits per dimension for residual quantization. * * This value controls how much each residual component is compressed. The more * bits, the more accurate the index will be but the slower search. Typical values - * are small integers; the default is 1 bit per dimension. + * are small integers. If unset, uses Lance's default (currently 5 bits per + * dimension). Set to 1 for maximum compression. */ numBits?: number; @@ -214,6 +247,8 @@ export interface HnswPqOptions { /** * The number of IVF partitions to create. * + * When set, this takes precedence over `targetPartitionSize`. + * * For HNSW, we recommend a small number of partitions. Setting this to 1 works * well for most tables. For very large tables, training just one HNSW graph * will require too much memory. Each partition becomes its own HNSW graph, so @@ -222,6 +257,21 @@ export interface HnswPqOptions { */ numPartitions?: number; + /** + * The target number of rows in each IVF partition. + * + * This is an alternative to `numPartitions`. When it is set and + * `numPartitions` is not, the number of partitions is derived by dividing + * the number of rows by this value. When both are set, `numPartitions` is + * used and this value is ignored. When neither is set, the target is + * 1,048,576 rows. + * + * Larger partitions mean fewer of them, which makes the first part of the + * search (picking the right partitions) faster and the second part + * (searching within a partition) slower. + */ + targetPartitionSize?: number; + /** * Number of sub-vectors of PQ. * @@ -330,6 +380,8 @@ export interface HnswSqOptions { /** * The number of IVF partitions to create. * + * When set, this takes precedence over `targetPartitionSize`. + * * For HNSW, we recommend a small number of partitions. Setting this to 1 works * well for most tables. For very large tables, training just one HNSW graph * will require too much memory. Each partition becomes its own HNSW graph, so @@ -338,6 +390,21 @@ export interface HnswSqOptions { */ numPartitions?: number; + /** + * The target number of rows in each IVF partition. + * + * This is an alternative to `numPartitions`. When it is set and + * `numPartitions` is not, the number of partitions is derived by dividing + * the number of rows by this value. When both are set, `numPartitions` is + * used and this value is ignored. When neither is set, the target is + * 1,048,576 rows. + * + * Larger partitions mean fewer of them, which makes the first part of the + * search (picking the right partitions) faster and the second part + * (searching within a partition) slower. + */ + targetPartitionSize?: number; + /** * Max iterations to train kmeans. * @@ -406,8 +473,9 @@ export interface IvfFlatOptions { * The number of IVF partitions to create. * * This value should generally scale with the number of rows in the dataset. - * By default the number of partitions is the square root of the number of - * rows. + * When set, this takes precedence over `targetPartitionSize`. When omitted, + * the partition count is derived from `targetPartitionSize`, which defaults + * to 4096 rows for this index type. * * If this value is too large then the first part of the search (picking the * right partition) will be slow. If this value is too small then the second @@ -415,6 +483,21 @@ export interface IvfFlatOptions { */ numPartitions?: number; + /** + * The target number of rows in each IVF partition. + * + * This is an alternative to `numPartitions`. When it is set and + * `numPartitions` is not, the number of partitions is derived by dividing + * the number of rows by this value. When both are set, `numPartitions` is + * used and this value is ignored. When neither is set, the target is + * 4096 rows. + * + * Larger partitions mean fewer of them, which makes the first part of the + * search (picking the right partitions) faster and the second part + * (searching within a partition) slower. + */ + targetPartitionSize?: number; + /** * Distance type to use to build the index. * @@ -632,6 +715,7 @@ export class Index { options?.numBits, options?.maxIterations, options?.sampleRate, + options?.targetPartitionSize, ), ); } @@ -660,6 +744,7 @@ export class Index { options?.numBits, options?.maxIterations, options?.sampleRate, + options?.targetPartitionSize, ), ); } @@ -687,6 +772,7 @@ export class Index { options?.numPartitions, options?.maxIterations, options?.sampleRate, + options?.targetPartitionSize, ), ); } @@ -797,6 +883,7 @@ export class Index { options?.sampleRate, options?.m, options?.efConstruction, + options?.targetPartitionSize, ), ); } @@ -819,6 +906,7 @@ export class Index { options?.sampleRate, options?.m, options?.efConstruction, + options?.targetPartitionSize, ), ); } diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index 0baa0f571..1c8d74ad2 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -24,7 +24,8 @@ export interface JobEventsOptions { * - {@link Job.refresh} and {@link Job.status} fetch the whole record. * - {@link Job.wait} records the terminal state it establishes, but not the * rest of the record. - * - Everything is null until one of those runs. + * - Registry details are null until one of those runs. Query handles report + * jobType "query" immediately. * * @hideconstructor */ @@ -38,8 +39,10 @@ export class Job { /** * Identifies the operation on the server that is running it. * - * Operations that run in this process have no server id. The value is - * opaque: parsing it or storing it to resume the job later is not supported. + * Registry handles expose a registry job ID; query handles expose a + * connection-scoped SQL query UUID string. Local handles have no ID. + * Query handles report jobType "query". Their IDs are not registry IDs or + * durable resume tokens. */ get id(): string | null { return this.inner.id ?? null; @@ -51,8 +54,8 @@ export class Job { } /** - * The job's type, as the server names it. Null for an in-process job, which - * has no server-side record. + * "query" immediately for SQL-backed handles; otherwise the cached + * server-reported job type. Null for in-process handles. */ get jobType(): string | null { return this.inner.jobType ?? null; diff --git a/nodejs/lancedb/materialized_view.ts b/nodejs/lancedb/materialized_view.ts index 7cf1690e0..afb61b9ab 100644 --- a/nodejs/lancedb/materialized_view.ts +++ b/nodejs/lancedb/materialized_view.ts @@ -186,15 +186,22 @@ export class MaterializedView { /** * Recompute the view from its source. + * Local refresh requires a source build with `experimental-functions`. * - * Every refresh rebuilds the complete view. For local views, - * `sourceVersion` refreshes to that source version instead of the latest; - * remote SQL refreshes do not support source-version pinning. + * `full: true` forces a remote rebuild; otherwise the server chooses the + * refresh mode. Local views always rebuild, and `sourceVersion` selects a + * source version instead of the latest. Remote SQL refreshes do not support + * source-version pinning. Their results leave `mode`, `rowsWritten`, and + * `sourceVersion` absent because the SQL job adapter does not expose these metrics. */ async refresh(options?: { + full?: boolean; sourceVersion?: number; }): Promise { validateNonNegativeInteger(options?.sourceVersion, "sourceVersion"); - return await this.inner.refreshMaterializedView(options?.sourceVersion); + return await this.inner.refreshMaterializedView( + options?.sourceVersion, + options?.full, + ); } } diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index 2abe6db97..27133a326 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -1,8 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +import type { Data as ArrowData } from "apache-arrow"; import { Table as ArrowTable, + DataType, Field, type IntoVector, LargeBinary, @@ -12,10 +14,10 @@ import { extractVectorBuffer, fromBufferToRecordBatch, fromRecordBatchToBuffer, - makeData, tableFromIPC, vectorFromArray, } from "./arrow"; +import { Expr } from "./expr"; import { type IvfPqOptions } from "./indices"; import { JsFullTextQuery, @@ -66,20 +68,42 @@ export interface QueryBlobContext { const BLOB_BYTES_ATTEMPTS = 3; +interface BlobSource { + // Output names are literal: an alias containing dots is still one field. + output: string; + path: string[]; + source: string; +} + function blobSources( blobColumns: string[], projection: [string, string][] | undefined, -): Map { - const columns = new Set(blobColumns); - const pairs = - projection ?? - blobColumns.map((column): [string, string] => [column, column]); - return new Map(pairs.filter(([, source]) => columns.has(source))); +): BlobSource[] { + if (projection === undefined) { + return blobColumns.map((source) => { + const [output, ...path] = source.split("."); + return { output, path, source }; + }); + } + const sources: BlobSource[] = []; + for (const [output, source] of projection) { + for (const column of blobColumns) { + if (column === source || column.startsWith(`${source}.`)) { + sources.push({ + output, + path: + column === source ? [] : column.slice(source.length + 1).split("."), + source: column, + }); + } + } + } + return sources; } async function readBlobBytes( table: ArrowTable, - sources: Map, + sources: BlobSource[], snapshot: NativeTable, dropRowId: boolean, ): Promise { @@ -91,18 +115,25 @@ async function readBlobBytes( rowIdColumn === null ? [] : Array.from(rowIdColumn.toArray() as BigUint64Array); - const replacements = new Map(); - for (const [output, source] of sources) { - const index = table.schema.fields.findIndex( - (field) => field.name === output, - ); - if (index < 0) { + const outputFields = new Map( + table.schema.fields.map((field) => [field.name, field]), + ); + const replacements = new Map(); + for (const { output, path, source } of sources) { + let field = outputFields.get(output); + for (const name of path) { + field = + field !== undefined && DataType.isStruct(field.type) + ? field.type.children.find((child) => child.name === name) + : undefined; + } + if (field === undefined) { continue; } const values = rowIds.length === 0 ? [] : await snapshot.fetchBlobs(source, rowIds); replacements.set( - index, + field, values.map((value) => value ?? null), ); } @@ -117,37 +148,76 @@ async function readBlobBytes( ); } -// A fresh field, not a clone: the descriptor field's metadata must not follow -// the bytes. function withBinaryColumns( table: ArrowTable, - replacements: Map, + replacements: Map, ): ArrowTable { if (replacements.size === 0) { return table; } - const fields = table.schema.fields.map((field, index) => - replacements.has(index) - ? new Field(field.name, new LargeBinary(), true) - : field, - ); + const replaceField = (field: Field): Field => { + if (replacements.has(field)) { + // The descriptor's extension and encoding metadata must not follow bytes. + return new Field(field.name, new LargeBinary(), true); + } + if (DataType.isStruct(field.type)) { + const children = field.type.children.map(replaceField); + if (children.some((child, i) => child !== field.type.children[i])) { + return field.clone({ type: new Struct(children) }); + } + } + return field; + }; + const fields = table.schema.fields.map(replaceField); const schema = new Schema(fields, table.schema.metadata); let offset = 0; const batches = table.batches.map((batch) => { - const children = batch.data.children.map((child, index) => { - const values = replacements.get(index); - if (values === undefined) { - return child; + const replaceData = ( + data: ArrowData, + field: Field, + updated: Field, + ): ArrowData => { + if (field === updated) { + return data; } - return vectorFromArray( - values.slice(offset, offset + batch.numRows), - new LargeBinary(), - ).data[0]; - }); + const values = replacements.get(field); + if (values !== undefined) { + return vectorFromArray( + values.slice(offset, offset + batch.numRows), + new LargeBinary(), + ).data[0]; + } + const children = data.children.map((child, index) => + replaceData( + child, + field.type.children[index], + updated.type.children[index], + ), + ); + // Keep the struct's validity bitmap and offset, including null parents. + return data.clone( + updated.type, + undefined, + undefined, + undefined, + undefined, + children, + ); + }; + const children = batch.data.children.map((child, index) => + replaceData(child, table.schema.fields[index], fields[index]), + ); offset += batch.numRows; return new RecordBatch( schema, - makeData({ type: new Struct(fields), length: batch.numRows, children }), + batch.data.clone( + new Struct(fields), + undefined, + undefined, + undefined, + undefined, + children, + ), ); }); return new ArrowTable(schema, batches); @@ -175,12 +245,14 @@ export interface QueryExecutionOptions { * * - `"descriptions"` (default): each blob is a descriptor. Read the bytes * with {@link Table.fetchBlobs} or {@link Table.fetchBlobFiles}. - * - `"bytes"`: each top-level blob column holds the blob bytes as - * `LargeBinary`. The query also reads `_rowid` to fetch the bytes, and + * - `"bytes"`: each blob column, including blobs nested in structs, holds + * the bytes as `LargeBinary`. The query also reads `_rowid` to fetch them, and * leaves it out of the result unless {@link QueryBase.withRowId} was * called. All the bytes are held in memory. * - * Blobs nested in a struct or a list keep their descriptors. + * Selecting a parent struct or directly aliasing a blob or struct also returns + * bytes. Blobs inside lists keep their descriptors. Arbitrary projection + * expressions are not materialized as bytes. * * The rows and the bytes come from the same table version. If the table * changes while the query runs, the query runs again, up to three times. @@ -433,7 +505,7 @@ export class QueryBase< await snapshot.blobColumns(), context.projection, ); - if (sources.size === 0) { + if (sources.length === 0) { return this.collect(options, false); } const addRowId = !context.withRowId; @@ -578,11 +650,16 @@ export class StandardQueryBase< /** * A filter statement to be applied to this query. * - * The filter should be supplied as an SQL query string. For example: + * The filter may be an SQL query string or an expression built with `col`, + * which preserves case-sensitive column names. For example: * @example * x > 10 * y > 0 AND y < 100 * x > 5 OR y = 'test' + * @example + * ```ts + * table.query().where(col("firstName").eq("Alice")); + * ``` * * Filtering performance can often be improved by creating a scalar index * on the filter column(s). @@ -590,8 +667,14 @@ export class StandardQueryBase< * Calling this multiple times combines the filters with a logical AND rather * than replacing the previous filter. */ - where(predicate: string): this { - this.doCall((inner: NativeQueryType) => inner.onlyIf(predicate)); + where(predicate: string | Expr): this { + this.doCall((inner: NativeQueryType) => { + if (predicate instanceof Expr) { + inner.onlyIf(predicate.toSql()); + } else { + inner.onlyIf(predicate); + } + }); return this; } /** diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 0c79e6a7e..0806f7c6d 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -128,8 +128,8 @@ export interface AddDataOptions { /** * Whether blob URIs outside registered external bases may be written. * - * Defaults to `false`. This option is supported only for local/native - * tables; remote tables return an error when it is enabled. An enabled write + * Defaults to `false`. This option is supported only in LanceDB Embedded; + * LanceDB Distributed 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. @@ -381,6 +381,11 @@ export abstract class Table { * }), * }); * @example + * // Or size the partitions by row count instead of choosing how many. + * await table.createIndex("vector", { + * config: lancedb.Index.ivfPq({ targetPartitionSize: 4096 }), + * }); + * @example * // Or create a Scalar index * await table.createIndex("my_float_col"); */ @@ -438,7 +443,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 on remote tables. + * This feature is currently only supported in LanceDB Distributed. */ abstract prewarmData(columns?: string[]): Promise; @@ -594,6 +599,10 @@ export abstract class Table { /** * 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. + * * The `{ computed }` form stores the expression rather than evaluating it * now: the column is committed with no values, and rows get them from * {@link Table#refreshColumn}. Declaring one therefore costs the same on a @@ -604,7 +613,7 @@ export abstract class Table { * declaration reads a column, that column cannot be renamed, retyped or * dropped. * - * On LanceDB Cloud and Enterprise the expression is planned by the + * In LanceDB Distributed 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: @@ -632,11 +641,12 @@ export abstract class Table { /** * Fill the rows of a computed column that hold no value yet. + * 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. Local tables only: a remote refresh - * runs as a server job, through {@link Table#refreshColumnAsync}. + * everything else is left as it is. LanceDB Embedded only: in LanceDB + * Distributed a refresh runs as a server job, through {@link Table#refreshColumnAsync}. * @param {string} column The name of the computed column to fill. * @returns {Promise} A promise that resolves to the * number of rows filled and the new version number of the table. @@ -646,12 +656,15 @@ export abstract class Table { /** * 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 + * 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. On local tables the job runs in-process; on - * LanceDB Cloud and Enterprise it is the server's backfill job. + * than failing the job. In LanceDB Embedded the job runs in-process; in + * LanceDB Distributed it is the server's backfill job. * @param {string} column The name of the computed column to fill. * @example * ```ts @@ -668,7 +681,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 Cloud and Enterprise only; reading errors needs read + * capped. LanceDB Distributed 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). @@ -692,6 +705,7 @@ export abstract class Table { */ abstract refreshMaterializedView( sourceVersion?: number, + full?: boolean, ): Promise; /** @ignore */ @@ -717,8 +731,6 @@ export abstract class Table { * - `lancedb:description`: for a human-readable description of a field. * - `lancedb:tag:`: for a user-defined key-value tag, where the suffix * names the tag category; e.g. `lancedb:tag:model: "clip"`. - * - `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and - * `feature_v2` might be in the same logical column. * - `lancedb:status`: for status options (`production`, `candidate`, * `deprecated`, `archived`) to designate the current life cycle state of * this column. @@ -988,8 +1000,12 @@ 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. For remote tables, this means the - * same tokenizer model files must also exist locally. + * the client process from index metadata. In LanceDB Distributed, 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 + * server's index produces. If the model files are missing, an error naming + * the tokenizer is raised. */ abstract tokenize( query: string, @@ -1431,8 +1447,9 @@ export class LocalTable extends Table { async refreshMaterializedView( sourceVersion?: number, + full?: boolean, ): Promise { - return await this.inner.refreshMaterializedView(sourceVersion); + return await this.inner.refreshMaterializedView(sourceVersion, full); } async materializedViewDefinition(): Promise { diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index da0158b7d..e417308eb 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.9", + "version": "0.41.0-beta.17", "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 451766110..d7dfa44be 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.9", + "version": "0.41.0-beta.17", "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 d818cb60f..f4a768871 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.9", + "version": "0.41.0-beta.17", "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 4fe1c12cc..a2266260d 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.9", + "version": "0.41.0-beta.17", "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 7dc63ccaa..6af065156 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.9", + "version": "0.41.0-beta.17", "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 dc97bbed8..694449160 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.9", + "version": "0.41.0-beta.17", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 235bb0e55..d852a1e3e 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.9", + "version": "0.41.0-beta.17", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 22f51ce61..cf0c7682e 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.9", + "version": "0.41.0-beta.17", "main": "dist/index.js", "exports": { ".": "./dist/index.js", @@ -90,7 +90,8 @@ "postdocs": "node typedoc_post_process.js", "lint": "biome check . && biome format .", "lint-fix": "biome check --write . && biome format --write .", - "prepublishOnly": "napi prepublish -t npm", + "check:native-symbols": "node scripts/check-native-symbols.js", + "prepublishOnly": "pnpm check:native-symbols && napi prepublish -t npm", "test": "jest --verbose", "integration": "S3_TEST=1 pnpm test", "universal": "napi universalize", diff --git a/nodejs/pnpm-lock.yaml b/nodejs/pnpm-lock.yaml index 4c19305c8..faf0ad428 100644 --- a/nodejs/pnpm-lock.yaml +++ b/nodejs/pnpm-lock.yaml @@ -13,7 +13,7 @@ importers: dependencies: '@opentelemetry/api': specifier: ^1.9.0 - version: 1.9.1 + version: 1.10.0 reflect-metadata: specifier: ^0.2.2 version: 0.2.2 @@ -38,7 +38,7 @@ importers: version: 3.7.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)(@types/node@22.7.4) '@opentelemetry/sdk-metrics': specifier: ^2.10.0 - version: 2.11.0(@opentelemetry/api@1.9.1) + version: 2.12.0(@opentelemetry/api@1.10.0) '@types/axios': specifier: ^0.14.0 version: 0.14.4 @@ -89,7 +89,7 @@ importers: version: 0.2.7 ts-jest: specifier: ^29.1.2 - version: 29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4) + version: 29.4.15(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4) typedoc: specifier: 0.26.4 version: 0.26.4(typescript@5.5.4) @@ -1399,24 +1399,24 @@ packages: '@octokit/types@16.0.0': resolution: {integrity: sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==} - '@opentelemetry/api@1.9.1': - resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==} + '@opentelemetry/api@1.10.0': + resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==} engines: {node: '>=8.0.0'} - '@opentelemetry/core@2.11.0': - resolution: {integrity: sha512-7YP44XH0tV6+Mb54x2YGf84i7yi+31MBZlE8JwvozkxyTvXbSp10X7cI7YE49ChJ3shMJoBmCJF3+1QFBJctGA==} + '@opentelemetry/core@2.12.0': + resolution: {integrity: sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' - '@opentelemetry/resources@2.11.0': - resolution: {integrity: sha512-Ie7+8q8MDF4FAEQCKVMTx3ReUvxiIAgIiiW3c9JdmP8+HMcDy20puT+AHjexnExgnbvBxjQ9fjkFDWrikJ2jQA==} + '@opentelemetry/resources@2.12.0': + resolution: {integrity: sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/sdk-metrics@2.11.0': - resolution: {integrity: sha512-7GXXcObyHyDUUSG+L+kJoquty01bzm7ivE7+SSgXXJcHuPzGviptxwARmI2c+bnnxjexGQbJnyNlN8HxBP/Y7A==} + '@opentelemetry/sdk-metrics@2.12.0': + resolution: {integrity: sha512-mVMaEHwCUJuY3S4Esn+nT0yQA3qCEGh+SOPJsXygU0Gl453WcsDNjtEa8EfdewMwoLyr1tlofB4fXytVpiXuow==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.9.0 <1.10.0' @@ -2434,8 +2434,8 @@ packages: guid-typescript@1.0.9: resolution: {integrity: sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==} - handlebars@4.7.9: - resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==} + handlebars@4.7.10: + resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==} engines: {node: '>=0.4.7'} hasBin: true @@ -3280,12 +3280,12 @@ packages: peerDependencies: typescript: '>=4.2.0' - ts-jest@29.4.12: - resolution: {integrity: sha512-Ov6ClY53Fflh6BGAnY2DlTq1hYDrTycz2PVTXBWFW2CU+9zrEqAp9fWdGXl42EXO5RLSFAcAZ2JFKbP+zBTFfw==} + ts-jest@29.4.15: + resolution: {integrity: sha512-s2qmEUYFRqbjz1wv0EmccNPVOb45HOFpFuhzQJLKShYVisuTbCFPIIAIV2EuK5rIxb4BejLDbH7dnBZfYjybUQ==} engines: {node: ^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0} hasBin: true peerDependencies: - '@babel/core': '>=7.0.0-beta.0 <8' + '@babel/core': '>=7.0.0-beta.0 <9' '@jest/transform': ^29.0.0 || ^30.0.0 '@jest/types': ^29.0.0 || ^30.0.0 babel-jest: ^29.0.0 || ^30.0.0 @@ -5153,24 +5153,24 @@ snapshots: dependencies: '@octokit/openapi-types': 27.0.0 - '@opentelemetry/api@1.9.1': {} + '@opentelemetry/api@1.10.0': {} - '@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/core@2.12.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/resources@2.11.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/resources@2.12.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sdk-metrics@2.11.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/sdk-metrics@2.12.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions@1.43.0': {} @@ -6376,7 +6376,7 @@ snapshots: guid-typescript@1.0.9: optional: true - handlebars@4.7.9: + handlebars@4.7.10: dependencies: minimist: 1.2.8 neo-async: 2.6.2 @@ -7409,11 +7409,11 @@ snapshots: dependencies: typescript: 5.5.4 - ts-jest@29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4): + ts-jest@29.4.15(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4): dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 - handlebars: 4.7.9 + handlebars: 4.7.10 jest: 29.7.0(@types/node@22.7.4) json5: 2.2.3 lodash.memoize: 4.1.2 diff --git a/nodejs/scripts/check-native-symbols.js b/nodejs/scripts/check-native-symbols.js new file mode 100644 index 000000000..2f6dbf9b8 --- /dev/null +++ b/nodejs/scripts/check-native-symbols.js @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +const { spawnSync } = require("node:child_process"); +const { existsSync } = require("node:fs"); +const path = require("node:path"); + +const FORBIDDEN_UNDEFINED_SYMBOLS = new Set([ + "sum_4bit_dist_table_32bytes_batch_avx512", +]); + +function findForbiddenUndefinedSymbols(output) { + const found = new Set(); + + for (const line of output.split(/\r?\n/)) { + const columns = line.trim().split(/\s+/); + const symbol = columns.at(-1)?.split("@")[0]; + if (symbol && FORBIDDEN_UNDEFINED_SYMBOLS.has(symbol)) { + found.add(symbol); + } + } + + return [...found].sort(); +} + +function checkNativeBinary(binaryPath, runNm = spawnSync) { + const result = runNm("nm", ["-D", "--undefined-only", binaryPath], { + encoding: "utf8", + }); + + if (result.error) { + throw new Error(`Unable to inspect ${binaryPath}: ${result.error.message}`); + } + if (result.status !== 0) { + throw new Error( + `Unable to inspect ${binaryPath}: nm exited with status ${result.status}\n${result.stderr}`, + ); + } + + const forbidden = findForbiddenUndefinedSymbols(result.stdout); + if (forbidden.length > 0) { + throw new Error( + `${binaryPath} contains unresolved internal Lance symbols: ${forbidden.join( + ", ", + )}`, + ); + } +} + +function main() { + const binaryPath = path.resolve( + __dirname, + "..", + "npm", + "linux-x64-musl", + "lancedb.linux-x64-musl.node", + ); + + if (!existsSync(binaryPath)) { + throw new Error( + `Missing ${binaryPath}; assemble the native artifacts before publishing`, + ); + } + + checkNativeBinary(binaryPath); +} + +if (require.main === module) { + try { + main(); + } catch (error) { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; + } +} + +module.exports = { checkNativeBinary, findForbiddenUndefinedSymbols }; diff --git a/nodejs/src/catalog.rs b/nodejs/src/catalog.rs index 82edda5da..d55bb3508 100644 --- a/nodejs/src/catalog.rs +++ b/nodejs/src/catalog.rs @@ -124,10 +124,17 @@ impl Catalog { .default_error() } #[napi] - pub async fn drop_database(&self, name: String, ignore_missing: Option) -> Result<()> { + pub async fn drop_database( + &self, + name: String, + ignore_missing: Option, + cascade: Option, + ) -> Result<()> { self.inner .drop_database( - DropDatabaseRequest::new(name).ignore_missing(ignore_missing.unwrap_or(false)), + DropDatabaseRequest::new(name) + .ignore_missing(ignore_missing.unwrap_or(false)) + .cascade(cascade.unwrap_or(false)), ) .await .default_error() diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 58ec9859a..914f9e4c9 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -16,8 +16,7 @@ use crate::table::Table; use lancedb::connection::{ConnectBuilder, Connection as LanceDBConnection, connect_namespace}; use lance_namespace::models::{ - CreateNamespaceRequest, DescribeNamespaceRequest, DropNamespaceRequest, ListNamespacesRequest, - ListTablesRequest, + CreateNamespaceRequest, DescribeNamespaceRequest, DropNamespaceRequest, }; use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema}; @@ -31,18 +30,6 @@ pub struct DescribeNamespaceResponse { pub properties: Option>, } -#[napi(object)] -pub struct ListNamespacesResponse { - pub namespaces: Vec, - pub page_token: Option, -} - -#[napi(object)] -pub struct ListTablesResponse { - pub tables: Vec, - pub page_token: Option, -} - #[napi(object)] pub struct CreateNamespaceResponse { pub properties: Option>, @@ -239,31 +226,20 @@ impl Connection { op.execute().await.default_error() } - /// List a page of tables in the database. + /// Lazily list tables in the database. #[napi(catch_unwind)] - pub async fn list_tables( + pub fn list_tables( &self, namespace_path: Option>, page_token: Option, limit: Option, - ) -> napi::Result { - let request = ListTablesRequest { - // The root namespace is an empty path, not an absent one: a namespace-backed - // database rejects a request that names no namespace. - id: Some(namespace_path.unwrap_or_default()), - page_token, - limit: limit.map(|limit| i32::try_from(limit).unwrap_or(i32::MAX)), - ..Default::default() - }; - let response = self - .get_inner()? - .list_tables(request) - .await - .default_error()?; - Ok(ListTablesResponse { - tables: response.tables, - page_token: response.page_token, - }) + ) -> napi::Result { + Ok(crate::listing::NameListing::new( + self.get_inner()?.list_tables( + &namespace_path.unwrap_or_default(), + crate::listing::options(page_token, limit), + ), + )) } /// Create table from a Apache Arrow IPC (file) buffer. @@ -663,28 +639,19 @@ impl Connection { } #[napi(catch_unwind)] - /// List child namespaces under the given namespace path - pub async fn list_namespaces( + /// Lazily list child namespaces under the given namespace path + pub fn list_namespaces( &self, namespace_path: Option>, page_token: Option, limit: Option, - ) -> napi::Result { - let req = ListNamespacesRequest { - id: namespace_path, - page_token, - limit: limit.map(|l| l as i32), - ..Default::default() - }; - let resp = self - .get_inner()? - .list_namespaces(req) - .await - .default_error()?; - Ok(ListNamespacesResponse { - namespaces: resp.namespaces, - page_token: resp.page_token, - }) + ) -> napi::Result { + Ok(crate::listing::NameListing::new( + self.get_inner()?.list_namespaces( + &namespace_path.unwrap_or_default(), + crate::listing::options(page_token, limit), + ), + )) } #[napi(catch_unwind)] diff --git a/nodejs/src/expr.rs b/nodejs/src/expr.rs new file mode 100644 index 000000000..c12f81a96 --- /dev/null +++ b/nodejs/src/expr.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Napi bindings for the LanceDB expression builder API. + +use std::ops::{Add, Div, Mul, Not, Sub}; + +use lancedb::expr::{ + DfExpr, col as ldb_col, contains, expr_cast, is_in, lit as df_lit, lower, upper, +}; +use napi::bindgen_prelude::*; +use napi_derive::napi; + +#[napi] +#[derive(Clone)] +pub struct Expr { + pub(crate) inner: DfExpr, +} + +#[napi] +impl Expr { + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn eq(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().eq(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn ne(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().not_eq(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn lt(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().lt(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn lte(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().lt_eq(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn gt(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().gt(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn gte(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().gt_eq(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn and(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().and(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn or(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().or(other.inner.clone()), + } + } + + #[napi] + pub fn not(&self) -> Self { + Self { + inner: self.inner.clone().not(), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn add(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().add(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn sub(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().sub(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn mul(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().mul(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn div(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().div(other.inner.clone()), + } + } + + #[napi] + pub fn lower(&self) -> Self { + Self { + inner: lower(self.inner.clone()), + } + } + + #[napi] + pub fn upper(&self) -> Self { + Self { + inner: upper(self.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn contains(&self, substr: &Expr) -> Self { + Self { + inner: contains(self.inner.clone(), substr.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn is_in(&self, list: Vec<&Expr>) -> Self { + let items: Vec = list.into_iter().map(|e| e.inner.clone()).collect(); + Self { + inner: is_in(self.inner.clone(), items), + } + } + + #[napi] + pub fn cast(&self, data_type: String) -> napi::Result { + let arrow_type = data_type + .parse::() + .map_err(|e| napi::Error::from_reason(format!("Invalid data type: {}", e)))?; + Ok(Self { + inner: expr_cast(self.inner.clone(), arrow_type), + }) + } + + #[napi] + pub fn to_sql(&self) -> napi::Result { + lancedb::expr::expr_to_sql_string(&self.inner) + .map_err(|e| napi::Error::from_reason(e.to_string())) + } +} + +/// Create a column reference expression. +/// +/// The column name is preserved exactly as given (case-sensitive), so +/// `col("firstName")` correctly references a field named `firstName`. +#[napi] +#[allow(dead_code)] +pub fn col(name: String) -> Expr { + Expr { + inner: ldb_col(name), + } +} + +/// Create a literal (constant) value expression. +#[napi] +#[allow(dead_code)] +pub fn lit(value: napi::bindgen_prelude::Either) -> napi::Result { + match value { + Either::A(s) => Ok(Expr { inner: df_lit(s) }), + Either::B(f) => Ok(Expr { inner: df_lit(f) }), + } +} + +/// Create a literal boolean value expression. +#[napi] +#[allow(dead_code)] +pub fn lit_bool(value: bool) -> Expr { + Expr { + inner: df_lit(value), + } +} + +/// Create a literal integer value expression. +#[napi] +#[allow(dead_code)] +pub fn lit_int(value: i64) -> Expr { + Expr { + inner: df_lit(value), + } +} + +/// Call an arbitrary registered SQL function by name. +#[napi] +#[allow(dead_code)] +pub fn func(name: String, args: Vec<&Expr>) -> napi::Result { + let df_args: Vec = args.into_iter().map(|e| e.inner.clone()).collect(); + lancedb::expr::func(&name, df_args) + .map(|inner| Expr { inner }) + .map_err(|e| napi::Error::from_reason(e.to_string())) +} diff --git a/nodejs/src/index.rs b/nodejs/src/index.rs index e5884aa4d..39aa6f8b8 100644 --- a/nodejs/src/index.rs +++ b/nodejs/src/index.rs @@ -104,6 +104,7 @@ impl Index { num_bits: Option, max_iterations: Option, sample_rate: Option, + target_partition_size: Option, ) -> napi::Result { let mut ivf_pq_builder = IvfPqIndexBuilder::default(); if let Some(distance_type) = distance_type { @@ -113,6 +114,9 @@ impl Index { if let Some(num_partitions) = num_partitions { ivf_pq_builder = ivf_pq_builder.num_partitions(num_partitions); } + if let Some(target_partition_size) = target_partition_size { + ivf_pq_builder = ivf_pq_builder.target_partition_size(target_partition_size); + } if let Some(num_sub_vectors) = num_sub_vectors { ivf_pq_builder = ivf_pq_builder.num_sub_vectors(num_sub_vectors); } @@ -137,6 +141,7 @@ impl Index { num_bits: Option, max_iterations: Option, sample_rate: Option, + target_partition_size: Option, ) -> napi::Result { let mut ivf_rq_builder = IvfRqIndexBuilder::default(); if let Some(distance_type) = distance_type { @@ -146,6 +151,9 @@ impl Index { if let Some(num_partitions) = num_partitions { ivf_rq_builder = ivf_rq_builder.num_partitions(num_partitions); } + if let Some(target_partition_size) = target_partition_size { + ivf_rq_builder = ivf_rq_builder.target_partition_size(target_partition_size); + } if let Some(num_bits) = num_bits { ivf_rq_builder = ivf_rq_builder.num_bits(num_bits); } @@ -166,6 +174,7 @@ impl Index { num_partitions: Option, max_iterations: Option, sample_rate: Option, + target_partition_size: Option, ) -> napi::Result { let mut ivf_flat_builder = IvfFlatIndexBuilder::default(); if let Some(distance_type) = distance_type { @@ -175,6 +184,9 @@ impl Index { if let Some(num_partitions) = num_partitions { ivf_flat_builder = ivf_flat_builder.num_partitions(num_partitions); } + if let Some(target_partition_size) = target_partition_size { + ivf_flat_builder = ivf_flat_builder.target_partition_size(target_partition_size); + } if let Some(max_iterations) = max_iterations { ivf_flat_builder = ivf_flat_builder.max_iterations(max_iterations); } @@ -283,6 +295,7 @@ impl Index { } #[napi(factory)] + #[allow(clippy::too_many_arguments)] pub fn hnsw_pq( distance_type: Option, num_partitions: Option, @@ -291,6 +304,7 @@ impl Index { sample_rate: Option, m: Option, ef_construction: Option, + target_partition_size: Option, ) -> napi::Result { let mut hnsw_pq_builder = IvfHnswPqIndexBuilder::default(); if let Some(distance_type) = distance_type { @@ -300,6 +314,9 @@ impl Index { if let Some(num_partitions) = num_partitions { hnsw_pq_builder = hnsw_pq_builder.num_partitions(num_partitions); } + if let Some(target_partition_size) = target_partition_size { + hnsw_pq_builder = hnsw_pq_builder.target_partition_size(target_partition_size); + } if let Some(num_sub_vectors) = num_sub_vectors { hnsw_pq_builder = hnsw_pq_builder.num_sub_vectors(num_sub_vectors); } @@ -328,6 +345,7 @@ impl Index { sample_rate: Option, m: Option, ef_construction: Option, + target_partition_size: Option, ) -> napi::Result { let mut hnsw_sq_builder = IvfHnswSqIndexBuilder::default(); if let Some(distance_type) = distance_type { @@ -337,6 +355,9 @@ impl Index { if let Some(num_partitions) = num_partitions { hnsw_sq_builder = hnsw_sq_builder.num_partitions(num_partitions); } + if let Some(target_partition_size) = target_partition_size { + hnsw_sq_builder = hnsw_sq_builder.target_partition_size(target_partition_size); + } if let Some(max_iterations) = max_iterations { hnsw_sq_builder = hnsw_sq_builder.max_iterations(max_iterations); } diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 214e687b4..320812128 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -29,8 +29,8 @@ impl Job { #[napi] impl Job { - /// Identifies the operation on the server that is running it. Operations - /// that run in this process have no server id. The value is opaque. + /// The operation's opaque ID. Interpret registry and query IDs using job_type(). + /// Local handles have no ID. #[napi(getter)] pub fn id(&self) -> Option { self.inner.id().map(str::to_string) @@ -62,8 +62,8 @@ impl Job { /// Ask the backend for this job's current state, and for a server-side job /// its full record, then cache it for the getters below. /// - /// They are all null until this runs, because submitting an operation - /// returns only a job id. {@link Job.status} fetches the whole record too; + /// Registry details are null until this runs; query handles already expose + /// job_type "query". {@link Job.status} fetches the whole registry record too; /// {@link Job.wait} records only the terminal state it establishes. #[napi(catch_unwind)] pub async fn refresh(&self) -> napi::Result<()> { @@ -76,8 +76,8 @@ impl Job { self.inner.state() } - /// The job's type, as the server names it. Null for an in-process job, - /// which has no server-side record. + /// "query" immediately for SQL-backed handles; otherwise the cached + /// server-reported job type. Null for in-process handles. #[napi(getter)] pub fn job_type(&self) -> Option { self.inner.job_type() diff --git a/nodejs/src/lib.rs b/nodejs/src/lib.rs index f47bc113e..368a3530c 100644 --- a/nodejs/src/lib.rs +++ b/nodejs/src/lib.rs @@ -14,6 +14,7 @@ mod blob; mod catalog; mod connection; mod error; +mod expr; mod header; mod index; mod iterator; @@ -30,6 +31,12 @@ mod session; mod table; mod util; +/// Whether this native binding was built with local experimental Functions. +#[napi] +pub fn experimental_functions_enabled() -> bool { + cfg!(feature = "experimental-functions") +} + #[napi(object)] #[derive(Debug)] pub struct ConnectionOptions { @@ -47,34 +54,34 @@ pub struct ConnectionOptions { /// often each read pays the cost of checking for updates against object /// storage, raising per-read latency and cost. pub read_consistency_interval: Option, - /// (For LanceDB OSS only): configuration for object storage. + /// (For LanceDB Embedded only): configuration for object storage. /// /// The available options are described at https://docs.lancedb.com/storage/ pub storage_options: Option>, - /// (For LanceDB OSS only): use directory namespace manifests as the source + /// (For LanceDB Embedded only): use directory namespace manifests as the source /// of truth for table metadata. Existing directory-listed root tables are /// migrated into the manifest on access. pub manifest_enabled: Option, - /// (For LanceDB OSS only): extra properties for the backing namespace + /// (For LanceDB Embedded only): extra properties for the backing namespace /// client used by manifest-enabled native connections. pub namespace_client_properties: Option>, - /// (For LanceDB OSS only): the session to use for this connection. Holds + /// (For LanceDB Embedded only): the session to use for this connection. Holds /// shared caches and other session-specific state. pub session: Option, - /// (For LanceDB cloud only): configuration for the remote HTTP client. + /// (For LanceDB Enterprise or LanceDB Cloud only): configuration for the HTTP client. pub client_config: Option, - /// (For LanceDB cloud only): the API key to use with LanceDB Cloud. + /// (For LanceDB Enterprise or LanceDB Cloud only): the API key to use. /// /// Can also be set via the environment variable `LANCEDB_API_KEY`. pub api_key: Option, - /// (For LanceDB cloud only): the region to use for LanceDB cloud. + /// (For LanceDB Cloud only): the region to use for LanceDB Cloud (legacy). /// Defaults to 'us-east-1'. pub region: Option, - /// (For LanceDB cloud only): the host to use for LanceDB cloud. Used - /// for testing purposes. + /// (For LanceDB Enterprise only): the host of the LanceDB Enterprise + /// deployment to connect to. pub host_override: Option, - /// (For LanceDB cloud only): OAuth configuration for IdP-based + /// (For LanceDB Enterprise only): OAuth configuration for IdP-based /// authentication (e.g., Azure Entra ID). When set, token acquisition /// and refresh are handled entirely in Rust. TypeScript users should pass /// the public `OAuthConfig` type exported from `@lancedb/lancedb`. diff --git a/nodejs/src/remote.rs b/nodejs/src/remote.rs index d7e2a21cd..df882334b 100644 --- a/nodejs/src/remote.rs +++ b/nodejs/src/remote.rs @@ -25,6 +25,10 @@ pub struct TimeoutConfig { /// The timeout for reading data from the server in seconds. Default is 300 /// seconds (5 minutes). This can also be set via the environment variable /// `LANCE_CLIENT_READ_TIMEOUT`, as an integer number of seconds. + /// + /// This also applies while waiting for response headers during an upload. + /// A large or slowly produced request body (for example, when creating a + /// table) may need a longer timeout even if data is still being uploaded. pub read_timeout: Option, /// The timeout for keeping idle connections in the connection pool in seconds. /// Default is 300 seconds (5 minutes). This can also be set via the @@ -65,7 +69,7 @@ pub struct RetryConfig { /// `LANCE_CLIENT_RETRY_BACKOFF_JITTER`. pub backoff_jitter: Option, /// The HTTP status codes for which to retry the request. Default is - /// [429, 500, 502, 503]. + /// [409, 429, 500, 502, 503, 504]. /// /// You can also set this via the environment variable /// `LANCE_CLIENT_RETRY_STATUSES`. Use a comma-separated list of integers. @@ -104,7 +108,7 @@ pub struct ClientConfig { pub tls_config: Option, /// User identifier for tracking purposes. /// - /// This is sent as the `x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise. + /// This is sent as the `x-lancedb-user-id` header in requests to LanceDB Enterprise. /// It can be set directly, or via the `LANCEDB_USER_ID` environment variable. /// Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment /// variable that contains the user ID value. diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 0a40e0a13..ec16ea5b5 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -470,11 +470,12 @@ impl Table { pub async fn refresh_materialized_view( &self, source_version: Option, + full: Option, ) -> napi::Result { let view = lancedb::MaterializedView::from_table(self.inner_ref()?.clone()) .await .default_error()?; - let mut builder = view.refresh(); + let mut builder = view.refresh().full(full.unwrap_or(false)); if let Some(version) = source_version { let version = u64::try_from(version).map_err(|_| { napi::Error::from_reason("sourceVersion must be a non-negative integer") @@ -830,7 +831,7 @@ impl Table { self.inner_ref()? .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "uses_v2_manifest_paths is not supported for remote tables.".into(), + message: "uses_v2_manifest_paths is not supported in LanceDB Distributed.".into(), }) .default_error()? .uses_v2_manifest_paths() @@ -843,7 +844,8 @@ impl Table { self.inner_ref()? .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "migrate_manifest_paths_v2 is not supported for remote tables.".into(), + message: "migrate_manifest_paths_v2 is not supported in LanceDB Distributed." + .into(), }) .default_error()? .migrate_manifest_paths_v2() @@ -866,40 +868,40 @@ pub struct IndexConfig { pub columns: Vec, /// The UUID of the first segment of the index. /// - /// `undefined` for remote tables, which do not yet surface this. + /// `undefined` in LanceDB Distributed, which does not yet surface this. pub index_uuid: Option, /// The protobuf type URL, a precise type identifier for the index. /// - /// `undefined` for remote tables. + /// `undefined` in LanceDB Distributed. pub type_url: Option, /// When the index was created. /// - /// `undefined` for remote tables or indices created before timestamps were tracked. + /// `undefined` in LanceDB Distributed or indices created before timestamps were tracked. pub created_at: Option>, /// The number of rows indexed, across all segments. /// - /// `undefined` for remote tables. + /// May be `undefined` in LanceDB Distributed if the server does not report it. pub num_indexed_rows: Option, /// The number of rows not yet covered by this index. /// - /// `undefined` for remote tables. + /// May be `undefined` in LanceDB Distributed 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` for remote tables or indices without size tracking. + /// `undefined` in LanceDB Distributed or indices without size tracking. pub size_bytes: Option, /// The number of segments that make up the index. /// - /// `undefined` for remote tables. + /// `undefined` in LanceDB Distributed. pub num_segments: Option, /// The on-disk index format version. /// - /// `undefined` for remote tables. + /// `undefined` in LanceDB Distributed. pub index_version: Option, /// Index-type-specific details parsed as a JavaScript object. /// - /// Falls back to a raw string if JSON parsing fails. `undefined` for - /// remote tables or when details are unavailable. + /// Falls back to a raw string if JSON parsing fails. `undefined` in + /// LanceDB Distributed or when details are unavailable. pub index_details: Option, } @@ -1615,22 +1617,24 @@ impl From for FunctionErrors { #[napi(object)] pub struct RefreshMaterializedViewResult { - /// How the view was brought up to date: "rebuild". - pub mode: String, - pub rows_written: i64, - pub source_version: i64, + /// How the view was brought up to date: "rebuild", or absent for LanceDB Distributed SQL refreshes. + pub mode: Option, + /// Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes. + pub rows_written: Option, + /// Source version refreshed to, or absent for LanceDB Distributed SQL refreshes. + pub source_version: Option, pub version: i64, } impl From for RefreshMaterializedViewResult { fn from(value: lancedb::RefreshMaterializedViewResult) -> Self { - let mode = match value.mode { + let mode = value.mode.map(|mode| match mode { lancedb::RefreshMode::Rebuild => "rebuild", - }; + }); Self { - mode: mode.to_string(), - rows_written: value.rows_written as i64, - source_version: value.source_version as i64, + mode: mode.map(str::to_string), + rows_written: value.rows_written.map(|rows| rows as i64), + source_version: value.source_version.map(|version| version as i64), version: value.version as i64, } } diff --git a/nodejs/typedoc.json b/nodejs/typedoc.json index c601ee61e..2c22b35ac 100644 --- a/nodejs/typedoc.json +++ b/nodejs/typedoc.json @@ -1,6 +1,7 @@ { "intentionallyNotExported": [ "lancedb/native.d.ts:Query", + "lancedb/native.d.ts:Expr", "lancedb/native.d.ts:VectorQuery", "lancedb/native.d.ts:TakeQuery", "lancedb/native.d.ts:RecordBatchIterator", diff --git a/python/CONTRIBUTING.md b/python/CONTRIBUTING.md index 122677364..f86dea706 100644 --- a/python/CONTRIBUTING.md +++ b/python/CONTRIBUTING.md @@ -48,6 +48,18 @@ Build the package make develop ``` +Local SQL computed columns and materialized-view creation/refresh are experimental +and disabled in published packages. To opt in when building from this directory: + +```shell +uv run --extra tests --extra dev maturin develop --features experimental-functions --extras tests,dev +uv run --no-sync pytest python/tests -m experimental_functions +``` + +Rebuild without `--features experimental-functions` to test the default package. +The tests detect the compiled feature; remote operations, metadata protections, +and ordinary eager `add_columns` transforms remain available in both builds. + Format: ```shell diff --git a/python/Cargo.toml b/python/Cargo.toml index ce4230f9d..0695180cd 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.9" +version = "0.41.0-beta.17" publish = false edition.workspace = true description = "Python bindings for LanceDB" @@ -8,7 +8,7 @@ license.workspace = true repository.workspace = true keywords.workspace = true categories.workspace = true -rust-version = "1.94.0" +rust-version = "1.95.0" [lib] name = "_lancedb" @@ -22,6 +22,7 @@ bytes.workspace = true lancedb.workspace = true datafusion-common.workspace = true lance-core.workspace = true +lance-arrow.workspace = true lance-namespace.workspace = true lance-namespace-impls.workspace = true lance-io.workspace = true @@ -29,9 +30,9 @@ env_logger.workspace = true log.workspace = true # Maturin enables extension-module mode for Python builds. Keeping it out of # Cargo features lets Rust unit tests link against libpython. -pyo3 = { version = "0.28", features = ["abi3-py310", "chrono", "uuid"] } +pyo3 = { version = "0.29", features = ["abi3-py310", "chrono", "uuid"] } chrono.workspace = true -pyo3-async-runtimes = { version = "0.28", features = [ +pyo3-async-runtimes = { version = "0.29", features = [ "attributes", "tokio-runtime", ] } @@ -45,9 +46,10 @@ uuid.workspace = true libc = "0.2" [build-dependencies] -pyo3-build-config = { version = "0.28", features = ["abi3-py310"] } +pyo3-build-config = "0.29" [features] default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel"] fp16kernels = ["lancedb/fp16kernels"] remote = ["lancedb/remote"] +experimental-functions = ["lancedb/experimental-functions"] diff --git a/python/README.md b/python/README.md index f941c9e20..0b640d27c 100644 --- a/python/README.md +++ b/python/README.md @@ -40,6 +40,33 @@ 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: + +```bash +pip install --pre \ + --extra-index-url https://pypi.fury.io/lancedb/ \ + --extra-index-url https://pypi.fury.io/lance-format/ \ + "lancedb[pylance]" +``` + +With uv, also select the best matching version across the indexes: + +```bash +uv pip install --prerelease allow \ + --index https://pypi.fury.io/lancedb/ \ + --index https://pypi.fury.io/lance-format/ \ + --index-strategy unsafe-best-match \ + "lancedb[pylance]" +``` + +The LanceDB preview index contains old `pylance` releases; current Lance previews +are published to the `lance-format` index. By default, uv only considers versions +from the first index containing a package, which can select an old `pylance` or +backtrack to an older LanceDB release. `unsafe-best-match` searches all configured +indexes, like pip; use it only with indexes you trust. Install the extra rather +than an unconstrained `pylance` so LanceDB's minimum supported version is enforced. + ### Threading in CPU-limited containers LanceDB uses separate pools for compute work and storage I/O. On a container with @@ -74,3 +101,52 @@ print(results) ### Development See [CONTRIBUTING.md](./CONTRIBUTING.md) for information on how to contribute to LanceDB. + +### Opening SQL blob descriptors + +A SQL `blob_descriptor(video)` result keeps the Blob V2 storage metadata and a +`source` struct containing its table URI, version, commit timestamp, branch, +column and row identity. This example uses a remote SQL connection whose SQL +service produces those source-bearing descriptors. Open the reference on the +source table to read incrementally: + +```python +rows = db.execute_query(""" + SELECT f.timestamp, blob_descriptor(v.video) AS video + FROM videos v JOIN frames f ON v.id = f.video_id +""").read_all() + +videos = db.open_table("videos") +for row in rows.to_pylist(): + if row["video"] is not None: + with videos.open_blob_file(row["video"]) as video: + frame = extract_frame(video, row["timestamp"]) +``` + +`open_blob_file` accepts the dictionary or an Arrow struct scalar directly. It +keeps the query's version and branch without changing the table handle's checkout. +Payload bytes load on reads. An external blob with an unspecified size may need a +metadata-only HEAD request to open. + +`videos.open_blob_files(rows["video"])` returns an iterator over the same handles, +preserving order, duplicates and nulls (`None`). It accepts Arrow arrays/chunked +arrays or another iterable and opens each handle as iteration advances. Close each +non-null handle after use. Async tables offer `await videos.open_blob_file(...)` +and `async for video in videos.open_blob_files(...)`. + +```python +for video in videos.open_blob_files(rows["video"]): + if video is not None: + with video: + header = video.read(4096) +``` + +To extract a frame while retaining each row's timestamp, iterate over the +handles and rows together: + +```python +for row, video in zip(rows.to_pylist(), videos.open_blob_files(rows["video"])): + if video is not None: + with video: + frame = extract_frame(video, row["timestamp"]) +``` diff --git a/python/pyproject.toml b/python/pyproject.toml index ed54ae536..1a6c64cee 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -45,7 +45,8 @@ repository = "https://github.com/lancedb/lancedb" [project.optional-dependencies] pylance = [ - "pylance>=5.0.0b5", + # Keep the minimum in the bundled Lance major and compatible with tests below. + "pylance>=15.0.0b3", ] # A library only needs the OpenTelemetry API; the application supplies and # configures the SDK (the actual exporter/reader). See @@ -63,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow<25", "pyarrow-stubs>=16.0", - "pylance==14.0.0b12", + "pylance==15.0.0b6", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 6b902c466..74f37fc2e 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -2,14 +2,12 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors -import importlib.metadata import os from concurrent.futures import ThreadPoolExecutor from datetime import timedelta from typing import Dict, Optional, Union, Any, List, Iterable, TYPE_CHECKING -__version__ = importlib.metadata.version("lancedb") - +from ._lancedb import __version__ as __version__ from ._lancedb import connect as lancedb_connect from ._lancedb import FtsToken from ._lancedb import FunctionErrorFragment as FunctionErrorFragment @@ -24,6 +22,7 @@ from .remote import ClientConfig from .remote.db import RemoteDBConnection from .expr import Expr, col, lit, func from .schema import blob, vector +from ._blob_reader import BlobReader as BlobReader from .job import AsyncJob, Job from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery @@ -48,7 +47,7 @@ from .materialized_view import ( MaterializedViewDefinition, ) from .view import ViewDescription as ViewDescription -from .table import AsyncTable, Table +from .table import AsyncTable, CompactionOptions, Table from .types import BaseTokenizerType from ._lancedb import Session from .namespace import ( @@ -138,18 +137,18 @@ def connect( The uri of the database. When ``namespace_client_impl`` is provided you may omit ``uri`` and connect through a namespace client instead. api_key: str, optional - If presented, connect to LanceDB cloud. + If presented, connect to LanceDB Enterprise or LanceDB Cloud (legacy). Otherwise, connect to a database on file system or cloud storage. Can be set via environment variable `LANCEDB_API_KEY`. OAuth configuration is currently supported only by ``connect_async``; - synchronous LanceDB Cloud connections require an API key. + synchronous ``db://`` connections require an API key. region: str, default "us-east-1" - The region to use for LanceDB Cloud. + The region to use for LanceDB Cloud (legacy). host_override: str, optional - The override url for LanceDB Cloud. + The URL of the LanceDB Enterprise deployment to connect to. sql_host_override: str, optional - The remote SQL service endpoint override. The client connects lazily when SQL - is first executed and retains that connection. + The LanceDB Enterprise SQL service endpoint override. The client + connects lazily when SQL is first executed and retains that connection. read_consistency_interval: timedelta, default None The interval at which to check for updates to the table from other processes. If None, then consistency is not checked. For performance @@ -165,18 +164,19 @@ def connect( often each read pays the cost of checking for updates against object storage, raising per-read latency and cost. client_config: ClientConfig or dict, optional - Configuration options for the LanceDB Cloud HTTP client. If a dict, then + Configuration options for the HTTP client used by ``db://`` connections. + If a dict, then the keys are the attributes of the ClientConfig class. If None, then the default configuration is used. storage_options: dict, optional Additional options for the storage backend. See available options at manifest_enabled : bool, default False - When true for local/native connections, use directory namespace + When true for LanceDB Embedded connections, use directory namespace manifests as the source of truth for table metadata. Existing directory-listed root tables are migrated into the manifest on access. session: Session, optional - (For LanceDB OSS only) + (For LanceDB Embedded only) A session to use for this connection. Sessions allow you to configure cache sizes for index and metadata caches, which can significantly impact memory use and performance. They can also be re-used across @@ -232,7 +232,7 @@ def connect( In-memory databases are not persisted. Tables are dropped when the last connection or table handle referencing them is closed. - Connect to LanceDB cloud: + Connect to LanceDB Enterprise or LanceDB Cloud (legacy): >>> db = lancedb.connect("db://my_database", api_key="ldb_...", ... client_config={"retry_config": {"retries": 5}}) @@ -280,10 +280,27 @@ def connect( "uri is required when not connecting through a namespace client" ) if isinstance(uri, str) and uri.startswith("db://"): + # Preserve the deprecated remote timeout options, but validate all other + # unknown keywords just as the local connection does. + unknown_kwargs = { + key: value + for key, value in kwargs.items() + if key not in ("connection_timeout", "read_timeout") + } + if unknown_kwargs: + raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}") + if session is not None: + raise NotImplementedError( + "session is not supported for LanceDB Distributed connections" + ) + if manifest_enabled: + raise NotImplementedError( + "manifest_enabled is not supported for LanceDB Distributed connections" + ) if api_key is None: api_key = os.environ.get("LANCEDB_API_KEY") if api_key is None: - raise ValueError(f"api_key is required to connect to LanceDB cloud: {uri}") + raise ValueError(f"api_key is required to connect to {uri}") if isinstance(request_thread_pool, int): request_thread_pool = ThreadPoolExecutor(request_thread_pool) return RemoteDBConnection( @@ -466,16 +483,16 @@ async def connect_async( uri: str or Path The uri of the database. api_key: str, optional - If present, connect to LanceDB cloud. + If present, connect to LanceDB Enterprise or LanceDB Cloud (legacy). Otherwise, connect to a database on file system or cloud storage. Can be set via environment variable `LANCEDB_API_KEY`. region: str, default "us-east-1" - The region to use for LanceDB Cloud. + The region to use for LanceDB Cloud (legacy). host_override: str, optional - The override url for LanceDB Cloud. + The URL of the LanceDB Enterprise deployment to connect to. sql_host_override: str, optional - The remote SQL service endpoint override. The client connects lazily when SQL - is first executed and retains that connection. + The LanceDB Enterprise SQL service endpoint override. The client + connects lazily when SQL is first executed and retains that connection. read_consistency_interval: timedelta, default None The interval at which to check for updates to the table from other processes. If None, then consistency is not checked. For performance @@ -491,27 +508,28 @@ async def connect_async( often each read pays the cost of checking for updates against object storage, raising per-read latency and cost. client_config: ClientConfig or dict, optional - Configuration options for the LanceDB Cloud HTTP client. If a dict, then + Configuration options for the HTTP client used by ``db://`` connections. + If a dict, then the keys are the attributes of the ClientConfig class. If None, then the default configuration is used. storage_options: dict, optional Additional options for the storage backend. See available options at session: Session, optional - (For LanceDB OSS only) + (For LanceDB Embedded only) A session to use for this connection. Sessions allow you to configure cache sizes for index and metadata caches, which can significantly impact memory use and performance. They can also be re-used across multiple connections to share the same cache state. manifest_enabled : bool, default False - When true for local/native connections, use directory namespace + When true for LanceDB Embedded connections, use directory namespace manifests as the source of truth for table metadata. Existing directory-listed root tables are migrated into the manifest on access. namespace_client_properties : dict, optional Additional directory namespace client properties to use with ``manifest_enabled=True``. oauth_config : OAuthConfig, optional - OAuth configuration for LanceDB Cloud/Enterprise. This is supported by + OAuth configuration for LanceDB Enterprise. This is supported by ``connect_async`` only; synchronous ``connect`` uses API key authentication for ``db://`` URIs. @@ -537,7 +555,7 @@ async def connect_async( ... ) ... # For tests and temporary data, use an in-memory database ... db = await lancedb.connect_async("memory://") - ... # Connect to LanceDB cloud + ... # Connect to LanceDB Enterprise or LanceDB Cloud (legacy) ... db = await lancedb.connect_async("db://my_database", api_key="ldb_...", ... client_config={ ... "retry_config": {"retries": 5}}) @@ -594,6 +612,7 @@ __all__ = [ "AsyncSqlQuery", "AsyncLanceNamespaceDBConnection", "AsyncTable", + "CompactionOptions", "FtsToken", "col", "Expr", diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py index 1e9110dd0..010c92009 100644 --- a/python/python/lancedb/_blob.py +++ b/python/python/lancedb/_blob.py @@ -7,7 +7,7 @@ from __future__ import annotations import io import operator -from collections.abc import Awaitable, Callable, Iterable +from collections.abc import Awaitable, Callable, Iterable, Mapping from typing import TYPE_CHECKING, Optional, Union import pyarrow as pa @@ -31,6 +31,18 @@ FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray] FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]] +def _normalize_blob_descriptor(value): + if isinstance(value, pa.Scalar): + value = value.as_py() + if value is None: + return None + if not isinstance(value, Mapping): + raise TypeError( + "blob descriptor must be a mapping, an Arrow struct scalar, or None" + ) + return dict(value) + + class BlobFile(io.RawIOBase): """Seekable lazy handle from :meth:`~lancedb.table.Table.fetch_blob_files`. @@ -268,7 +280,11 @@ async def replace_v2_blob_columns_with_bytes( row_ids = _hit_row_ids(tbl, present) for output_name, source_name in present.items(): tbl = _set_blob_column( - tbl, output_name, await fetch_blobs(source_name, row_ids) + tbl, + output_name, + await fetch_blobs(source_name, row_ids) + if row_ids + else pa.array([], type=pa.large_binary()), ) return tbl @@ -283,7 +299,13 @@ def replace_v2_blob_columns_with_bytes_sync( return tbl row_ids = _hit_row_ids(tbl, present) for output_name, source_name in present.items(): - tbl = _set_blob_column(tbl, output_name, fetch_blobs(source_name, row_ids)) + tbl = _set_blob_column( + tbl, + output_name, + fetch_blobs(source_name, row_ids) + if row_ids + else pa.array([], type=pa.large_binary()), + ) return tbl diff --git a/python/python/lancedb/_blob_reader.py b/python/python/lancedb/_blob_reader.py new file mode 100644 index 000000000..c47f8074d --- /dev/null +++ b/python/python/lancedb/_blob_reader.py @@ -0,0 +1,123 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Seekable binary input for Functions that consume Blob V2 values lazily.""" + +import io +import operator +import urllib.request +from collections.abc import Callable +from http import HTTPStatus + +_READ_CHUNK_BYTES = 1024 * 1024 +_READ_TIMEOUT_SECONDS = 300 + + +class BlobReader(io.RawIOBase): + """Read a blob incrementally inside a Function. + + Annotating a Function input with ``BlobReader`` requests a lazy, seekable + reader. Annotating it with ``bytes`` requests materialized bytes instead. + ``read_range`` does not change the sequential cursor. Readers are scoped + to the invocation and must not be retained for a later call. + + A packaged Function's source imports the worker's ``lance_blob.BlobReader`` + in place of this class. + + 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. + """ + + def __init__(self, read_range: Callable[[int, int], bytes], size: int): + super().__init__() + self._read_range = read_range + self._size = operator.index(size) + if self._size < 0: + raise ValueError("blob size must be nonnegative") + self._position = 0 + + @classmethod + def _from_uri(cls, uri: str, size: int): + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + def read_range(offset, length): + request = urllib.request.Request( + uri, headers={"Range": f"bytes={offset}-{offset + length - 1}"} + ) + with opener.open(request, timeout=_READ_TIMEOUT_SECONDS) as response: + if response.status != HTTPStatus.PARTIAL_CONTENT: + raise OSError( + "blob range service did not return a partial response" + ) + data = response.read(length + 1) + if len(data) != length: + raise OSError( + "blob range service returned an invalid payload length" + ) + return data + + return cls(read_range, size) + + def readable(self) -> bool: + return not self.closed + + def seekable(self) -> bool: + return not self.closed + + def size(self) -> int: + """Return the blob size without reading its payload.""" + self._checkClosed() + return self._size + + def tell(self) -> int: + self._checkClosed() + return self._position + + def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: + self._checkClosed() + offset = operator.index(offset) + if whence == io.SEEK_SET: + position = offset + elif whence == io.SEEK_CUR: + position = self._position + offset + elif whence == io.SEEK_END: + position = self._size + offset + else: + raise ValueError(f"invalid whence: {whence}") + if position < 0: + raise ValueError("negative seek position") + self._position = position + return position + + def read_range(self, offset: int, length: int) -> bytes: + """Read a byte range without changing the cursor; truncate at EOF.""" + self._checkClosed() + offset, length = operator.index(offset), operator.index(length) + if offset < 0 or length < 0: + raise ValueError("offset and length must be nonnegative") + remaining = min(length, max(0, self._size - offset)) + chunks = [] + while remaining: + count = min(remaining, _READ_CHUNK_BYTES) + chunk = self._read_range(offset, count) + if len(chunk) != count: + raise OSError("blob range reader returned an invalid payload length") + chunks.append(chunk) + offset += count + remaining -= count + return b"".join(chunks) + + def read(self, size: int = -1) -> bytes: + self._checkClosed() + size = -1 if size is None else operator.index(size) + if size < 0: + size = max(0, self._size - self._position) + data = self.read_range(self._position, size) + self._position += len(data) + return data + + def readinto(self, buffer) -> int: + view = memoryview(buffer).cast("B") + data = self.read(len(view)) + view[: len(data)] = data + return len(data) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 988482a97..2b8d1655a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -19,19 +19,20 @@ from .index import ( FTS, ) from lance_namespace import ( - ListNamespacesResponse, CreateNamespaceResponse, DropNamespaceResponse, DescribeNamespaceResponse, - ListTablesResponse, ) from .remote import ClientConfig from .types import BaseTokenizerType +_experimental_functions_enabled: bool + IvfHnswPq: type[HnswPq] = HnswPq IvfHnswSq: type[HnswSq] = HnswSq IvfHnswFlat: type[HnswFlat] = HnswFlat AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"] +__version__: str class MetricPoint: name: str @@ -114,12 +115,12 @@ class Connection(object): uri: str async def is_open(self): ... async def close(self): ... - async def list_namespaces( + def list_namespaces( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: ... + ) -> NameListing: ... async def create_namespace( self, namespace_path: List[str], @@ -136,12 +137,14 @@ class Connection(object): self, namespace_path: List[str], ) -> DescribeNamespaceResponse: ... - async def list_tables( + async def namespace_exists(self, namespace_id: List[str]) -> bool: ... + async def table_exists(self, table_id: List[str]) -> bool: ... + def list_tables( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: ... + ) -> NameListing: ... async def table_names( self, namespace_path: Optional[List[str]], @@ -270,6 +273,8 @@ class Connection(object): filter: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Table: ... async def create_materialized_view_async( self, @@ -279,6 +284,8 @@ class Connection(object): filter: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Job: ... def list_materialized_views( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None @@ -318,6 +325,8 @@ class Job: @property def id(self) -> Optional[str]: ... @property + def job_type(self) -> Optional[str]: ... + @property def _state(self) -> Optional[str]: ... @property def _description(self) -> Optional[JobDescription]: ... @@ -501,10 +510,17 @@ class Table: async def delete(self, filter: Union[str, PyExpr]) -> DeleteResult: ... async def add_columns(self, columns: list[tuple[str, str]]) -> AddColumnsResult: ... async def add_computed_columns( - self, columns: list[tuple[str, str]] + self, + columns: list[tuple[str, str]], + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[int] = None, ) -> AddColumnsResult: ... async def add_function_columns( - self, application_json: str, output_name: Optional[str] + self, + application_json: str, + output_name: Optional[str], + 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: ... @@ -515,10 +531,10 @@ class Table: limit: Optional[int] = None, ) -> FunctionErrors: ... async def refresh_materialized_view( - self, source_version: Optional[int] = None + self, source_version: Optional[int] = None, *, full: bool = False ) -> RefreshMaterializedViewResult: ... async def refresh_materialized_view_async( - self, source_version: Optional[int] = None + self, source_version: Optional[int] = None, *, full: bool = False ) -> Job: ... async def materialized_view_definition(self) -> str: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... @@ -533,6 +549,7 @@ class Table: *, cleanup_since_ms: Optional[int] = None, delete_unverified: Optional[bool] = None, + compaction_options: Optional[Dict[str, Any]] = None, ) -> OptimizeStats: ... async def uri(self) -> str: ... async def initial_storage_options(self) -> Optional[Dict[str, str]]: ... @@ -569,6 +586,7 @@ class Table: async def fetch_blob_files( self, column: str, row_ids: list[int] ) -> list[Optional[BlobFile]]: ... + async def open_blob_file(self, descriptor: str) -> BlobFile: ... def vector_search(self) -> VectorQuery: ... class Tags: @@ -850,9 +868,9 @@ class RTEWriteSpec: @staticmethod def unsharded() -> "RTEWriteSpec": ... def with_maintained_indexes(self, indexes: Optional[List[str]]) -> "RTEWriteSpec": - """Set which indexes the RTE keeps up to date. None resolves every - index on the table at install, failing if one cannot be maintained; - a list is verbatim, empty means none.""" + """Set which indexes the RTE keeps up to date. None is every index on + the table, now and later, skipping any it cannot maintain; a list is + verbatim, empty means none.""" ... def with_writer_config_defaults(self, defaults: Dict[str, str]) -> "RTEWriteSpec": """Return a copy of this spec recording the given default @@ -906,9 +924,9 @@ class FunctionErrors: class RefreshMaterializedViewResult: @staticmethod def from_json(value: str) -> RefreshMaterializedViewResult: ... - mode: str - rows_written: int - source_version: int + mode: Optional[str] + rows_written: Optional[int] + source_version: Optional[int] version: int class AlterColumnsResult: @@ -940,6 +958,15 @@ class AsyncPermutationBuilder: counts: Optional[List[int]] = None, fixed: Optional[int] = None, ) -> "AsyncPermutationBuilder": ... + def bootstrap_sample( + self, + num_samples: int, + *, + ratios: Optional[List[float]] = None, + counts: Optional[List[int]] = None, + fixed: Optional[int] = None, + seed: Optional[int] = None, + ) -> "AsyncPermutationBuilder": ... def split_calculated(self, calculation: str) -> "AsyncPermutationBuilder": ... def shuffle( self, seed: Optional[int], clump_size: Optional[int] @@ -965,7 +992,7 @@ class Catalog: ) -> Connection: ... async def connect_database(self, name: str) -> Connection: ... async def drop_database( - self, name: str, *, ignore_missing: bool = False + self, name: str, *, ignore_missing: bool = False, cascade: bool = False ) -> None: ... def list_databases( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None @@ -990,6 +1017,7 @@ async def connect_catalog( class NameListing: def num_page_results(self) -> int: ... def page_token(self) -> Optional[str]: ... + async def next_page(self) -> Optional[dict[str, Any]]: ... def __aiter__(self) -> NameListing: ... async def __anext__(self) -> str: ... diff --git a/python/python/lancedb/arrow.py b/python/python/lancedb/arrow.py index 404efafea..c5a278ead 100644 --- a/python/python/lancedb/arrow.py +++ b/python/python/lancedb/arrow.py @@ -2,7 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors from functools import singledispatch -from typing import List, Optional, Tuple, Union +from typing import AsyncIterator, List, Optional, Tuple, Union from lancedb.pydantic import LanceModel, model_to_dict import pyarrow as pa @@ -30,6 +30,7 @@ class AsyncRecordBatchReader: The schema of the batches produced by the stream. Accessing the schema does not consume any data from the stream """ + self._inner: AsyncIterator[pa.RecordBatch] if isinstance(inner, pa.Table): self._inner = self._async_iter_from_table(inner, max_batch_length) self.schema: pa.Schema = inner.schema @@ -39,6 +40,16 @@ class AsyncRecordBatchReader: else: raise TypeError("inner must be a RecordBatchStream or a Table") + @classmethod + def _from_batches( + cls, schema: pa.Schema, batches: AsyncIterator[pa.RecordBatch] + ) -> "AsyncRecordBatchReader": + """Wrap a transformed stream without consuming its first batch.""" + reader = cls.__new__(cls) + reader.schema = schema + reader._inner = batches + return reader + async def read_all(self) -> List[pa.RecordBatch]: """ Read all the record batches from the stream diff --git a/python/python/lancedb/catalog.py b/python/python/lancedb/catalog.py index 666d414a4..9a0dc3412 100644 --- a/python/python/lancedb/catalog.py +++ b/python/python/lancedb/catalog.py @@ -130,9 +130,15 @@ class AsyncCatalog: self._inner.list_databases(page_token=page_token, page_limit=page_limit) ) - async def drop_database(self, name: str, *, ignore_missing: bool = False) -> None: - """Drop an empty database. A nonempty database is an error.""" - await self._inner.drop_database(name, ignore_missing=ignore_missing) + async def drop_database( + self, name: str, *, ignore_missing: bool = False, cascade: bool = False + ) -> None: + """Drop a database. A nonempty database is an error unless ``cascade`` is set, + which drops everything in it first; the name stays taken until the server + finishes cleaning up their storage.""" + await self._inner.drop_database( + name, ignore_missing=ignore_missing, cascade=cascade + ) class Catalog: @@ -207,9 +213,17 @@ class Catalog: self._inner.list_databases(page_token=page_token, page_limit=page_limit) ) - def drop_database(self, name: str, *, ignore_missing: bool = False) -> None: - """Drop an empty database. A nonempty database is an error.""" - LOOP.run(self._inner.drop_database(name, ignore_missing=ignore_missing)) + def drop_database( + self, name: str, *, ignore_missing: bool = False, cascade: bool = False + ) -> None: + """Drop a database. A nonempty database is an error unless ``cascade`` is set, + which drops everything in it first; the name stays taken until the server + finishes cleaning up their storage.""" + LOOP.run( + self._inner.drop_database( + name, ignore_missing=ignore_missing, cascade=cascade + ) + ) async def connect_catalog_async( diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 47d24b762..e13e3dc9c 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -5,6 +5,7 @@ from __future__ import annotations from abc import abstractmethod +import asyncio from datetime import timedelta from pathlib import Path import sys @@ -31,18 +32,24 @@ if sys.version_info >= (3, 12): else: from overrides import EnforceOverrides, override # type: ignore -from lancedb.listing import AsyncListing, Listing +from lancedb.listing import ( + AsyncListing, + AsyncNamespaceListing, + AsyncTableListing, + Listing, + NamespaceListing, + TableListing, + validate_page_limit, +) from lancedb.embeddings.registry import EmbeddingFunctionRegistry from lancedb.common import data_to_reader, sanitize_uri, validate_schema from lancedb.background_loop import LOOP from lance_namespace import ( LanceNamespace, - ListNamespacesResponse, CreateNamespaceResponse, DropNamespaceResponse, DescribeNamespaceResponse, - ListTablesResponse, connect as namespace_connect, ) from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError @@ -170,7 +177,7 @@ class DBConnection(EnforceOverrides): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> NamespaceListing: """List immediate child namespace names in the given namespace. Parameters @@ -186,12 +193,12 @@ class DBConnection(EnforceOverrides): Returns ------- - ListNamespacesResponse + NamespaceListing Response containing namespace names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return ListNamespacesResponse(namespaces=[], page_token=None) + return NamespaceListing(AsyncNamespaceListing(None, empty=True)) def create_namespace( self, @@ -316,8 +323,8 @@ class DBConnection(EnforceOverrides): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: - """List a page of tables in this database. + ) -> TableListing: + """List tables in this database, one page at a time. Parameters ---------- @@ -333,7 +340,7 @@ class DBConnection(EnforceOverrides): Returns ------- - ListTablesResponse + TableListing Response containing table names and optional page_token for pagination. """ raise NotImplementedError( @@ -409,6 +416,10 @@ class DBConnection(EnforceOverrides): - pyarrow.Schema - [LanceModel][lancedb.pydantic.LanceModel] + + Plain binary values are cast into blob columns declared with + [blob][lancedb.schema.blob]. To construct Arrow record batches + explicitly, use [blob_array][lancedb.schema.blob_array]. mode: str; default "create" The mode to use when creating the table. Can be "create", "overwrite", or "exist_ok". @@ -421,10 +432,13 @@ class DBConnection(EnforceOverrides): it will not add the provided data but will validate against any schema that's specified. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. - One of "error", "drop", "fill". + How to handle vectors with incorrect sizes, NaNs, or null elements. + One of "error", "drop", "fill", "null". fill_value: float The value to use when filling vectors. Only used if on_bad_vectors="fill". + NaN or null elements and missing trailing elements are replaced with this + value. Valid elements are preserved, and vectors longer than the expected + dimension are truncated. storage_options: dict, optional Additional options for the storage backend. Options already set on the connection will be inherited by the table, but can be overridden here. @@ -541,7 +555,9 @@ class DBConnection(EnforceOverrides): LanceTable(name='table4', ...) """ - raise NotImplementedError + raise NotImplementedError( + "create_table is not supported for this connection type" + ) def __getitem__(self, name: str) -> LanceTable: return self.open_table(name) @@ -596,7 +612,9 @@ class DBConnection(EnforceOverrides): ------- A LanceTable object representing the table. """ - raise NotImplementedError + raise NotImplementedError( + "open_table is not supported for this connection type" + ) def create_materialized_view( self, @@ -607,9 +625,15 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """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. Published packages leave it + disabled; LanceDB Distributed operations remain available. + The view is populated before creation returns. Pass ``with_no_data=True`` to create only its definition and empty backing table. The view is a normal table: it can be queried, indexed and @@ -631,6 +655,13 @@ class DBConnection(EnforceOverrides): Cap the view at this many rows, in materialization order. 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. + 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. + When omitted, the server determines when to refresh. Returns ------- @@ -649,13 +680,17 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: """Submit materialized-view creation and return its job. - The job may already be complete for a local database. On LanceDB - Cloud and Enterprise, its ``id`` is the server job identifier from - the ``202 Accepted`` create response. Wait for the job before opening - or querying the view. + 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. + Wait for the job before opening or querying the view. """ raise NotImplementedError( "materialized views are not supported on this connection type" @@ -691,9 +726,9 @@ class DBConnection(EnforceOverrides): ) -> None: """Drop a materialized view. - The view may become unavailable before physical cleanup finishes. Use - :meth:`drop_materialized_view_async` to retain and wait for the cleanup - job. + In LanceDB Distributed, 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" @@ -702,11 +737,12 @@ class DBConnection(EnforceOverrides): def drop_materialized_view_async( self, name: str, namespace_path: Optional[List[str]] = None ) -> Job[None]: - """Start dropping a materialized view and return its cleanup job. + """Start dropping a materialized view and return its job. - The job may already be complete for a local database. On LanceDB Cloud - and Enterprise, its ``id`` is the server job identifier from the - ``202 Accepted`` drop response. + The job may already be complete in LanceDB Embedded. In LanceDB + Distributed, 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" @@ -725,13 +761,17 @@ class DBConnection(EnforceOverrides): """ if namespace_path is None: namespace_path = [] - raise NotImplementedError + raise NotImplementedError( + "drop_table is not supported for this connection type" + ) def drop_table_async( self, name: str, namespace_path: Optional[List[str]] = None ) -> Job: """Start dropping a table and return its cleanup job.""" - raise NotImplementedError + raise NotImplementedError( + "drop_table_async is not supported for this connection type" + ) def rename_table( self, @@ -759,19 +799,26 @@ class DBConnection(EnforceOverrides): cur_namespace_path = [] if new_namespace_path is None: new_namespace_path = [] - raise NotImplementedError + raise NotImplementedError( + "rename_table is not supported for this connection type" + ) def drop_database(self): """ Drop database This is the same thing as dropping all the tables """ - raise NotImplementedError + raise NotImplementedError( + "drop_database is not supported for this connection type" + ) def drop_all_tables(self, namespace_path: Optional[List[str]] = None): """ Drop all tables from the database + LanceDB Distributed does not currently support this operation. Use + ``list_tables()`` and ``drop_table()`` to drop tables individually. + Parameters ---------- namespace_path: List[str], optional @@ -780,12 +827,32 @@ class DBConnection(EnforceOverrides): """ if namespace_path is None: namespace_path = [] - raise NotImplementedError + raise NotImplementedError( + "drop_all_tables is not supported for this connection type" + ) @property def uri(self) -> str: + """The URI of this database.""" return self._uri + def _all_table_names(self) -> Generator[str, None, None]: + page_token = None + while True: + response = self.list_tables(page_token=page_token) + yield from response.tables + page_token = response.page_token + if not page_token: + return + + def __len__(self) -> int: + """Return the number of tables in the root namespace across all pages.""" + return sum(1 for _ in self._all_table_names()) + + def __contains__(self, name: str) -> bool: + """Return whether the root namespace contains the named table.""" + return name in self._all_table_names() + def namespace_client(self) -> LanceNamespace: """Get the equivalent namespace client for this connection. @@ -794,7 +861,7 @@ class DBConnection(EnforceOverrides): For namespace connections, this returns the backing namespace client. - For enterprise (remote) connections, this returns a RestNamespace + For LanceDB Enterprise connections, this returns a RestNamespace with the same URI and authentication headers. Returns @@ -830,7 +897,7 @@ class DBConnection(EnforceOverrides): The server builds the OCI image and registers the completed artifact. This is the blocking counterpart of :meth:`create_function_async`. - Local connections raise ``NotImplementedError``. + LanceDB Embedded connections raise ``NotImplementedError``. Parameters ---------- @@ -874,7 +941,7 @@ class DBConnection(EnforceOverrides): The server-side job builds the OCI image, then registers the completed artifact. Waiting on the job returns the immutable Function version. - Local connections raise ``NotImplementedError``. + LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( "Function catalog operations are not supported for this connection type" @@ -902,7 +969,7 @@ 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. Local connections raise + Function name then version. LanceDB Embedded connections raise ``NotImplementedError``. Examples @@ -952,7 +1019,7 @@ class DBConnection(EnforceOverrides): 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. Local connections raise + is already finished and has no id. LanceDB Embedded connections raise NotImplementedError. """ raise NotImplementedError( @@ -981,7 +1048,7 @@ class DBConnection(EnforceOverrides): Fails if it does not exist. Every Function bound to the Secret uses the new value from its next job, and no new Function version is created -- which is how a rotation reaches columns pinned to a version registered - before it. Local connections raise ``NotImplementedError``. + before it. LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( "Secret operations are not supported for this connection type" @@ -997,7 +1064,8 @@ class DBConnection(EnforceOverrides): """The names of every Secret in this database. Names only. No method returns a stored credential, by construction - rather than by policy. Local connections raise ``NotImplementedError``. + rather than by policy. LanceDB Embedded 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 @@ -1015,7 +1083,7 @@ class DBConnection(EnforceOverrides): Functions bound to it fail at their next job, naming the Secret; that is the revocation path. The name becomes free to reuse, and a new Secret under it is picked up by everything still bound to that name. - Local connections raise ``NotImplementedError``. + LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( "Secret operations are not supported for this connection type" @@ -1043,7 +1111,7 @@ class DBConnection(EnforceOverrides): its readers see its sources as they are at read time. There is no replace: a name already taken is an error, and changing a - view is a drop followed by a create. Local connections raise + view is a drop followed by a create. LanceDB Embedded connections raise ``NotImplementedError``. >>> import lancedb @@ -1065,7 +1133,7 @@ class DBConnection(EnforceOverrides): schema that query resolved to. The schema is the one recorded at creation; a source altered since then - shows up when the view is read. Local connections raise + shows up when the view is read. LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( @@ -1079,7 +1147,7 @@ class DBConnection(EnforceOverrides): 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. - Local connections raise ``NotImplementedError``. + LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( "View operations are not supported for this connection type" @@ -1218,18 +1286,19 @@ class DBConnection(EnforceOverrides): parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10], ) - Parameters are supported in queries, not in DDL or DML. A - parameterized query runs on the call that returns its rows: - cancelling it, or dropping its handle before reading, stops it on the - server. Its status follows that stream as well: ``describe()`` - reports ``running`` until the reader has received every row, so open - ``reader()`` directly rather than waiting for ``finished``. + Parameters are supported in queries, not in DDL or DML. With or + without parameters, the server chooses whether to stream rows on the + initial call or return a polling continuation. The reader follows + either path transparently. Dropping an unread handle or its reader + stops a directly streamed query; deferred execution requires explicit + cancellation. Open ``reader()`` directly: a streamed query needs its + reader to make progress and reports ``running`` until the stream ends. - Local connections do not support SQL. + LanceDB Embedded connections do not support SQL. """ raise NotImplementedError("SQL is not supported for this connection type") - def describe_query(self, query_id: UUID) -> QueryDescription: + 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") @@ -1288,6 +1357,10 @@ class LanceDBConnection(DBConnection): self.storage_options = storage_options self._manifest_enabled = manifest_enabled self._namespace_client_properties = namespace_client_properties + # The native connection does not expose the Python Session wrapper. + # Keep the object supplied by the caller so this property stays + # synchronous for debugger inspection. + self._session = session if _inner is not None: self._conn = _inner # Native-derived wrappers resolve this in their async reconstruction @@ -1354,7 +1427,12 @@ class LanceDBConnection(DBConnection): @property def session(self) -> Optional[Session]: - return self._conn.session + """Return the session supplied when this connection was opened. + + None when the caller did not pass a session, including connections + reconstructed with :meth:`from_inner`. + """ + return self._session @property def uri(self) -> str: @@ -1415,7 +1493,7 @@ class LanceDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> NamespaceListing: """List immediate child namespace names in the given namespace. Parameters @@ -1431,16 +1509,14 @@ class LanceDBConnection(DBConnection): Returns ------- - ListNamespacesResponse + NamespaceListing Response containing namespace names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return NamespaceListing( self._conn.list_namespaces( - namespace_path=namespace_path, - page_token=page_token, - limit=limit, + namespace_path=namespace_path, page_token=page_token, limit=limit ) ) @@ -1491,8 +1567,8 @@ class LanceDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: - """List a page of tables in this database. + ) -> TableListing: + """List tables in this database, one page at a time. Parameters ---------- @@ -1508,12 +1584,12 @@ class LanceDBConnection(DBConnection): Returns ------- - ListTablesResponse + TableListing Response containing table names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return TableListing( self._conn.list_tables( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -1562,21 +1638,6 @@ class LanceDBConnection(DBConnection): ) ) - def _all_table_names(self) -> Generator[str, None, None]: - page_token = None - while True: - response = self.list_tables(page_token=page_token) - yield from response.tables - page_token = response.page_token - if not page_token: - return - - def __len__(self) -> int: - return sum(1 for _ in self._all_table_names()) - - def __contains__(self, name: str) -> bool: - return name in self._all_table_names() - @override def create_table( self, @@ -1706,8 +1767,14 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """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. Published packages leave it + disabled; LanceDB Distributed operations remain available. See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. @@ -1717,13 +1784,13 @@ class LanceDBConnection(DBConnection): >>> db = lancedb.connect("./.lancedb") >>> data = [{"name": "ada", "age": 36}, {"name": "kid", "age": 7}] >>> table = db.create_table("people", data) - >>> view = db.create_materialized_view( + >>> view = db.create_materialized_view( # doctest: +SKIP ... "adults", ... "people", ... select=["name", ("shout", "upper(name)")], ... where="age >= 18", ... ) - >>> view.table.count_rows() + >>> view.table.count_rows() # doctest: +SKIP 1 """ LOOP.run( @@ -1734,6 +1801,8 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ) return MaterializedView(self.open_table(name)) @@ -1748,6 +1817,8 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: job = LOOP.run( self._conn.create_materialized_view_async( @@ -1757,6 +1828,8 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ) return Job(job) @@ -2196,12 +2269,12 @@ class AsyncConnection(object): To obtain a connection you can use the [connect_async][lancedb.connect_async] function. - This could be a native connection (using lance) or a remote connection (e.g. for - connecting to LanceDb Cloud) + This could be a LanceDB Embedded connection (using lance) or a LanceDB Distributed + connection (e.g. for connecting to LanceDB Enterprise) - Local 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) Remote - connections represent an open connection to the remote server. The + 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 [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. @@ -2257,12 +2330,12 @@ class AsyncConnection(object): else: return None - async def list_namespaces( + def list_namespaces( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> AsyncNamespaceListing: """List immediate child namespace names in the given namespace. Parameters @@ -2277,15 +2350,18 @@ class AsyncConnection(object): Returns ------- - ListNamespacesResponse + AsyncNamespaceListing Response containing namespace names and optional pagination token """ if namespace_path is None: namespace_path = [] - result = await self._inner.list_namespaces( + validate_page_limit(limit) + inner = self._inner.list_namespaces( namespace_path=namespace_path, page_token=page_token, limit=limit ) - return ListNamespacesResponse(**result) + if limit == 0: + return AsyncNamespaceListing(None, empty=True) + return AsyncNamespaceListing(inner, page_token) async def create_namespace( self, @@ -2364,13 +2440,56 @@ class AsyncConnection(object): result = await self._inner.describe_namespace(namespace_path) return DescribeNamespaceResponse(**result) - async def list_tables( + async def namespace_exists(self, namespace_id: List[str]) -> bool: + """Check if a namespace exists. + + Parameters + ---------- + namespace_id: List[str] + The namespace identifier to check. An empty list represents root. + + Returns + ------- + bool + True if the namespace exists, False if it is not found. + Other errors, including permission errors, are propagated. + + Examples + -------- + >>> async def check_namespace(conn): + ... return await conn.namespace_exists(["analytics"]) + """ + return await self._inner.namespace_exists(namespace_id) + + async def table_exists(self, table_id: List[str]) -> bool: + """Check if a table exists. + + Parameters + ---------- + table_id: List[str] + The full identifier, including namespace segments and table name. + Must contain at least the table name. + + Returns + ------- + bool + True if the table exists, False if it is not found. + Other errors, including permission errors, are propagated. + + Examples + -------- + >>> async def check_table(conn): + ... return await conn.table_exists(["analytics", "events"]) + """ + return await self._inner.table_exists(table_id) + + def list_tables( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: - """List a page of tables in this database. + ) -> AsyncTableListing: + """List tables in this database, one page at a time. Parameters ---------- @@ -2386,15 +2505,18 @@ class AsyncConnection(object): Returns ------- - ListTablesResponse + AsyncTableListing Response containing table names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - result = await self._inner.list_tables( + validate_page_limit(limit) + inner = self._inner.list_tables( namespace_path=namespace_path, page_token=page_token, limit=limit ) - return ListTablesResponse(**result) + if limit == 0: + return AsyncTableListing(None, empty=True) + return AsyncTableListing(inner, page_token) async def table_names( self, @@ -2480,6 +2602,10 @@ class AsyncConnection(object): - pyarrow.Schema - [LanceModel][lancedb.pydantic.LanceModel] + + Plain binary values are cast into blob columns declared with + [blob][lancedb.schema.blob]. To construct Arrow record batches + explicitly, use [blob_array][lancedb.schema.blob_array]. mode: Literal["create", "overwrite", "exist_ok"]; default "create" The mode to use when creating the table. Can be "create", "overwrite", or "exist_ok". @@ -2492,10 +2618,13 @@ class AsyncConnection(object): it will not add the provided data but will validate against any schema that's specified. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. - One of "error", "drop", "fill". + How to handle vectors with incorrect sizes, NaNs, or null elements. + One of "error", "drop", "fill", "null". fill_value: float The value to use when filling vectors. Only used if on_bad_vectors="fill". + NaN or null elements and missing trailing elements are replaced with this + value. Valid elements are preserved, and vectors longer than the expected + dimension are truncated. storage_options: dict, optional Additional options for the storage backend. Options already set on the connection will be inherited by the table, but can be overridden here. @@ -2633,8 +2762,16 @@ class AsyncConnection(object): if fill_value is None: fill_value = 0.0 - data, schema = sanitize_create_table( - data, schema, metadata, on_bad_vectors, fill_value + # Input preparation may advance a user-provided iterator. Keep that work + # off the background event loop so an iterator can use the synchronous + # LanceDB API without blocking the loop that API needs to make progress. + data, schema = await asyncio.to_thread( + sanitize_create_table, + data, + schema, + metadata, + on_bad_vectors, + fill_value, ) validate_schema(schema) @@ -2767,8 +2904,14 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncMaterializedView: """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. Published packages leave it + disabled; LanceDB Distributed operations remain available. See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. """ @@ -2782,6 +2925,8 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, ) return AsyncMaterializedView(AsyncTable(inner)) @@ -2795,10 +2940,14 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job. - Wait for the returned job before opening or querying the view. + Wait for the returned job before opening or querying the view. In LanceDB + Distributed, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` + identifies that query on this connection. """ source, native_options = await self._materialized_view_source( source, select, where, limit @@ -2810,6 +2959,8 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, ) return AsyncJob(inner) @@ -2849,9 +3000,9 @@ class AsyncConnection(object): ) -> None: """Drop a materialized view. - The view may become unavailable before physical cleanup finishes. Use - :meth:`drop_materialized_view_async` to retain and wait for the cleanup - job. + In LanceDB Distributed, drops wait for the SQL command to remove the + catalog binding. + Physical cleanup continues in the background. """ if namespace_path is None: namespace_path = [] @@ -2863,10 +3014,11 @@ class AsyncConnection(object): *, namespace_path: Optional[List[str]] = None, ) -> AsyncJob[None]: - """Start dropping a materialized view and return its cleanup job. + """Start dropping a materialized view and return its job. - Await :meth:`AsyncJob.wait` before assuming physical cleanup has - finished. + In LanceDB Distributed, 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. """ if namespace_path is None: namespace_path = [] @@ -3039,7 +3191,7 @@ class AsyncConnection(object): [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. Local connections raise ``NotImplementedError``. + the root. LanceDB Embedded connections raise ``NotImplementedError``. """ if not isinstance(definition, UdfDefinition): raise TypeError("create_function_async requires a @udf definition") @@ -3071,7 +3223,7 @@ class AsyncConnection(object): """List every published immutable Function version in a namespace. Functions in child namespaces are not included. Results are ordered by - Function name then version. Local connections raise + Function name then version. LanceDB Embedded connections raise ``NotImplementedError``. Returns a lazy iterator. ``page_limit`` limits each request, not the total; @@ -3326,7 +3478,7 @@ class AsyncConnection(object): references. The namespace defaults to ``["public"]``. ``parameters`` binds values to ``$1`` / ``$name`` placeholders; see [DBConnection.execute_query_async][lancedb.db.DBConnection.execute_query_async]. - Local connections raise ``NotImplementedError``. + LanceDB Embedded connections raise ``NotImplementedError``. """ return AsyncSqlQuery( await self._inner.execute_query_async( @@ -3336,8 +3488,14 @@ class AsyncConnection(object): ) ) - async def describe_query(self, query_id: UUID) -> QueryDescription: - """Describe a submitted SQL query by its connection-scoped id.""" + async def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription: + """Describe a submitted SQL query by its UUID or string ID. + + For a handle with ``job_type == "query"``, pass its ``id`` on the + connection that submitted it. Registry job IDs are not query IDs. + """ + if isinstance(query_id, str): + query_id = UUID(query_id) return await self._inner.describe_query(query_id) async def namespace_client(self) -> LanceNamespace: @@ -3348,7 +3506,7 @@ class AsyncConnection(object): For namespace connections, this returns the backing namespace client. - For enterprise (remote) connections, this returns a RestNamespace + For LanceDB Enterprise connections, this returns a RestNamespace with the same URI and authentication headers. Returns diff --git a/python/python/lancedb/embeddings/__init__.py b/python/python/lancedb/embeddings/__init__.py index 636502c9e..20e8c331b 100644 --- a/python/python/lancedb/embeddings/__init__.py +++ b/python/python/lancedb/embeddings/__init__.py @@ -16,6 +16,7 @@ from .instructor import InstructorEmbeddingFunction from .ollama import OllamaEmbeddings from .open_clip import OpenClipEmbeddings from .openai import OpenAIEmbeddings +from .nvidia import NvidiaEmbeddings from .registry import EmbeddingFunctionRegistry, get_registry, register from .sentence_transformers import SentenceTransformerEmbeddings from .gte import GteEmbeddings @@ -40,6 +41,7 @@ __all__ = [ "register", "SentenceTransformerEmbeddings", "OpenAIEmbeddings", + "NvidiaEmbeddings", "OpenClipEmbeddings", "BedRockText", "CohereEmbeddingFunction", diff --git a/python/python/lancedb/embeddings/base.py b/python/python/lancedb/embeddings/base.py index f26a940df..c11914fab 100644 --- a/python/python/lancedb/embeddings/base.py +++ b/python/python/lancedb/embeddings/base.py @@ -38,9 +38,11 @@ class EmbeddingFunction(BaseModel, ABC): 3. ndims() which returns the number of dimensions of the vector column """ - max_retries: int = ( - 7 # Setting 0 disables retires. Maybe this should not be enabled by default, - ) + # Maximum number of retries for transient errors (rate limits, 5xx responses, + # connection errors, ...), with exponential backoff capped at 60 seconds between + # attempts. Permanent errors (HTTP 4xx other than 408/409/429) are never retried. + # Setting 0 disables retries. + max_retries: int = 7 _ndims: int = PrivateAttr() _original_args: dict = PrivateAttr() @@ -239,7 +241,9 @@ class EmbeddingFunction(BaseModel, ABC): Creates a pydantic Field that can automatically annotate the source column for this embedding function """ - return Field(json_schema_extra={"source_column_for": self}, **kwargs) + json_schema_extra = dict(kwargs.pop("json_schema_extra", None) or {}) + json_schema_extra["source_column_for"] = self + return Field(json_schema_extra=json_schema_extra, **kwargs) def VectorField(self, **kwargs): """ @@ -250,7 +254,9 @@ class EmbeddingFunction(BaseModel, ABC): static type checkers. LanceDB will infer the fixed vector dimension from this embedding function. """ - return Field(json_schema_extra={"vector_column_for": self}, **kwargs) + json_schema_extra = dict(kwargs.pop("json_schema_extra", None) or {}) + json_schema_extra["vector_column_for"] = self + return Field(json_schema_extra=json_schema_extra, **kwargs) def __eq__(self, __value: object) -> bool: if not hasattr(__value, "__dict__"): diff --git a/python/python/lancedb/embeddings/cohere.py b/python/python/lancedb/embeddings/cohere.py index 8fc460f9a..286f658ad 100644 --- a/python/python/lancedb/embeddings/cohere.py +++ b/python/python/lancedb/embeddings/cohere.py @@ -22,16 +22,20 @@ class CohereEmbeddingFunction(TextEmbeddingFunction): Parameters ---------- - name : str, default "embed-multilingual-v2.0" + name : str, default "embed-multilingual-v3.0" The name of the model to use. List of acceptable models: * embed-english-v3.0 * embed-multilingual-v3.0 * embed-english-light-v3.0 * embed-multilingual-light-v3.0 - * embed-english-v2.0 - * embed-english-light-v2.0 - * embed-multilingual-v2.0 + + The v2.0 models (embed-english-v2.0, embed-english-light-v2.0 and + embed-multilingual-v2.0) were retired by Cohere on April 4, 2026. + The previous default produced 768-dimensional vectors, while the new + default produces 1024-dimensional vectors. Existing tables containing + vectors from a v2.0 model must be re-embedded with an active model into + a table whose vector column has the matching dimension. source_input_type : str, default "search_document" The input type for the source column in the database @@ -65,7 +69,7 @@ class CohereEmbeddingFunction(TextEmbeddingFunction): cohere = EmbeddingFunctionRegistry .get_instance() .get("cohere") - .create(name="embed-multilingual-v2.0") + .create(name="embed-multilingual-v3.0") class TextModel(LanceModel): text: str = cohere.SourceField() @@ -81,7 +85,7 @@ class CohereEmbeddingFunction(TextEmbeddingFunction): """ - name: str = "embed-multilingual-v2.0" + name: str = "embed-multilingual-v3.0" source_input_type: str = "search_document" query_input_type: str = "search_query" client: ClassVar = None diff --git a/python/python/lancedb/embeddings/jinaai.py b/python/python/lancedb/embeddings/jinaai.py index f6ab601b3..25b5a940b 100644 --- a/python/python/lancedb/embeddings/jinaai.py +++ b/python/python/lancedb/embeddings/jinaai.py @@ -5,9 +5,10 @@ import os import io import base64 +from functools import cached_property from urllib.parse import urlparse from pathlib import Path -from typing import TYPE_CHECKING, ClassVar, List, Union, Optional, Any, Dict +from typing import TYPE_CHECKING, List, Union, Optional, Any, Dict import numpy as np import pyarrow as pa @@ -51,7 +52,6 @@ class JinaEmbeddings(EmbeddingFunction): name: str = "jina-clip-v1" api_key: Optional[str] = None - _session: ClassVar = None def ndims(self): # TODO: fix hardcoding @@ -206,8 +206,7 @@ class JinaEmbeddings(EmbeddingFunction): texts: list[str] or np.ndarray (of str) The texts to embed """ - self._init_client() - resp = JinaEmbeddings._session.post( # type: ignore + resp = self._session.post( API_URL, json={"input": input, "model": self.name} ).json() if "data" not in resp: @@ -220,14 +219,15 @@ class JinaEmbeddings(EmbeddingFunction): return [result["embedding"] for result in sorted_embeddings] - def _init_client(self): + @cached_property + def _session(self): import requests - if JinaEmbeddings._session is None: - if self.api_key is None and os.environ.get("JINA_API_KEY") is None: - api_key_not_found_help("jina") - api_key = self.api_key or os.environ.get("JINA_API_KEY") - JinaEmbeddings._session = requests.Session() - JinaEmbeddings._session.headers.update( - {"Authorization": f"Bearer {api_key}", "Accept-Encoding": "identity"} - ) + if self.api_key is None and os.environ.get("JINA_API_KEY") is None: + api_key_not_found_help("jina") + api_key = self.api_key or os.environ.get("JINA_API_KEY") + session = requests.Session() + session.headers.update( + {"Authorization": f"Bearer {api_key}", "Accept-Encoding": "identity"} + ) + return session diff --git a/python/python/lancedb/embeddings/nvidia.py b/python/python/lancedb/embeddings/nvidia.py new file mode 100644 index 000000000..11fae0d34 --- /dev/null +++ b/python/python/lancedb/embeddings/nvidia.py @@ -0,0 +1,194 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import math +import os +from functools import cached_property +from typing import List, Literal, Optional + +from pydantic import Field, model_validator + +from ..util import attempt_import_or_raise +from .base import TextEmbeddingFunction +from .registry import register +from .utils import TEXT, MissingApiKeyError, retry_with_exponential_backoff + + +NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1" +# Hosted model ID -> (default dimensions, minimum dimensions) +MODEL_DIMENSIONS = { + "nvidia/nemotron-3.5-embed-1b": (2048, 128), + "nvidia/nemotron-3.5-embed-8b": (4096, 1), +} + + +@register("nvidia") +class NvidiaEmbeddings(TextEmbeddingFunction): + """Text embeddings using NVIDIA Nemotron 3.5 Embed 1B or 8B. + + Uses the optional ``openai`` package for NVIDIA-hosted and self-hosted NIM + ``/v1/embeddings`` endpoints. Documents use ``input_type="passage"`` and + queries use ``input_type="query"``. Null and empty strings get a null + embedding. Image inputs are not supported. + + Parameters + ---------- + name : str + Hosted model ID, or the served model ID from a NIM ``/v1/models`` response. + dim : int, optional + Requested output dimensions. Defaults to 2048 for the hosted 1B model + and 4096 for the hosted 8B model. Required for other served model IDs; + use a dimension supported by your deployment. + base_url : str + API base URL including ``/v1``. Defaults to NVIDIA's hosted API. + api_key : str, optional + Registry variable reference, such as ``$var:nvidia-key``. Otherwise the + hosted API uses ``NVIDIA_API_KEY``. Custom endpoints only receive an + explicit ``api_key`` and can run without authentication. + batch_size : int + Maximum inputs per request (default 32). Reduce for deployment limits. + truncate : str + ``END`` (default) truncates overlong text; ``NONE`` rejects it. + max_retries : int + Inherited LanceDB retry limit, applied to each request. The OpenAI + client's own retries are disabled. + + Examples + -------- + Set ``NVIDIA_API_KEY`` before using the hosted API: + + >>> from lancedb.embeddings import get_registry + >>> from lancedb.pydantic import LanceModel, Vector + >>> func = get_registry().get("nvidia").create() + >>> class Document(LanceModel): + ... text: str = func.SourceField() + ... vector: Vector(func.ndims()) = func.VectorField() + + Embedding runs client-side for both local and remote tables. For a custom + endpoint restored from table metadata in a new process, first call + [allow_endpoint][lancedb.embeddings.EmbeddingFunctionRegistry.allow_endpoint]. + """ + + name: str = "nvidia/nemotron-3.5-embed-1b" + dim: Optional[int] = Field(default=None, gt=0) + base_url: str = NVIDIA_BASE_URL + api_key: Optional[str] = Field(default=None, repr=False) + batch_size: int = Field(default=32, gt=0) + truncate: Literal["END", "NONE"] = "END" + + @model_validator(mode="after") + def _validate_dimensions(self): + dimensions = MODEL_DIMENSIONS.get(self.name) + if dimensions is None and self.dim is None: + raise ValueError("Set dim explicitly for self-hosted NIM model IDs") + if dimensions is not None and self.dim is not None: + native_dim, minimum = dimensions + if not minimum <= self.dim <= native_dim: + raise ValueError( + f"{self.name} supports dimensions from {minimum} to {native_dim}" + ) + return self + + @staticmethod + def sensitive_keys(): + return ["api_key"] + + def endpoints(self) -> List[str]: + return [] if self.base_url.rstrip("/") == NVIDIA_BASE_URL else [self.base_url] + + def ndims(self) -> int: + return self.dim if self.dim is not None else MODEL_DIMENSIONS[self.name][0] + + def compute_query_embeddings( + self, query: str, *args, **kwargs + ) -> List[Optional[List[float]]]: + return self._embed(query, input_type="query") + + def generate_embeddings(self, texts: TEXT) -> List[Optional[List[float]]]: + return self._embed(texts, input_type="passage") + + # Retry each request rather than the whole call, so a transient failure does + # not resend batches that already succeeded, and invalid inputs or responses + # fail at once instead of being retried. + def compute_query_embeddings_with_retry( + self, query: str, *args, **kwargs + ) -> List[Optional[List[float]]]: + return self._embed(query, input_type="query", max_retries=self.max_retries) + + def compute_source_embeddings_with_retry( + self, texts: TEXT, *args, **kwargs + ) -> List[Optional[List[float]]]: + return self._embed(texts, input_type="passage", max_retries=self.max_retries) + + def _embed( + self, + texts: TEXT, + *, + input_type: Literal["passage", "query"], + max_retries: int = 0, + ) -> List[Optional[List[float]]]: + texts = list(self.sanitize_input(texts)) + if any(text is not None and not isinstance(text, str) for text in texts): + raise ValueError("NVIDIA embeddings support text strings only") + request = self._request + if max_retries > 0: + request = retry_with_exponential_backoff(request, max_retries=max_retries) + embeddings = [None] * len(texts) + valid = [index for index, text in enumerate(texts) if text] + for start in range(0, len(valid), self.batch_size): + rows = valid[start : start + self.batch_size] + data = request([texts[row] for row in rows], input_type) + if not isinstance(data, list) or len(data) != len(rows): + raise ValueError("NVIDIA returned an unexpected number of embeddings") + indices = [getattr(item, "index", None) for item in data] + if any(type(index) is not int for index in indices) or sorted( + indices + ) != list(range(len(rows))): + raise ValueError("NVIDIA returned invalid embedding indices") + for row, item in zip(rows, sorted(data, key=lambda item: item.index)): + vector = getattr(item, "embedding", None) + if ( + not isinstance(vector, list) + or len(vector) != self.ndims() + or any( + type(value) not in (int, float) or not math.isfinite(value) + for value in vector + ) + ): + raise ValueError( + "NVIDIA returned an invalid embedding: expected " + f"{self.ndims()} finite numeric values" + ) + embeddings[row] = vector + return embeddings + + def _request(self, batch: List[str], input_type: str): + response = self._client.embeddings.create( + model=self.name, + input=batch, + encoding_format="float", + # The typed dimensions parameter is unavailable in openai 1.6.1. + extra_body={ + "dimensions": self.ndims(), + "input_type": input_type, + "modality": "text", + "truncate": self.truncate, + }, + ) + return getattr(response, "data", None) + + @cached_property + def _client(self): + openai = attempt_import_or_raise("openai") + hosted = not self.endpoints() + # Never send the hosted API key from the environment to a custom endpoint + api_key = self.api_key or (os.environ.get("NVIDIA_API_KEY") if hosted else None) + if not api_key and hosted: + raise MissingApiKeyError( + "Set NVIDIA_API_KEY or provide api_key via a registry variable" + ) + return openai.OpenAI( + base_url=self.base_url, + api_key=api_key or "not-required", + max_retries=0, + ) diff --git a/python/python/lancedb/embeddings/ollama.py b/python/python/lancedb/embeddings/ollama.py index aad8742de..3151c7c72 100644 --- a/python/python/lancedb/embeddings/ollama.py +++ b/python/python/lancedb/embeddings/ollama.py @@ -70,6 +70,8 @@ class OllamaEmbeddings(TextEmbeddingFunction): The texts to embed """ # TODO retry, rate limit, token limit + if isinstance(texts, np.ndarray): + texts = texts.tolist() embeddings = self._compute_embedding(texts) return list(embeddings) diff --git a/python/python/lancedb/embeddings/open_clip.py b/python/python/lancedb/embeddings/open_clip.py index 8b3f0eb06..6199ef271 100644 --- a/python/python/lancedb/embeddings/open_clip.py +++ b/python/python/lancedb/embeddings/open_clip.py @@ -49,6 +49,9 @@ class OpenClipEmbeddings(EmbeddingFunction): self.name, pretrained=self.pretrained ) model.to(self.device) + # open_clip returns the model in training mode, which keeps dropout, + # stochastic depth and batch norm in their training behaviour. + model.eval() self._model, self._preprocess = model, preprocess self._tokenizer = open_clip.get_tokenizer(self.name) self._ndims = None diff --git a/python/python/lancedb/embeddings/openai.py b/python/python/lancedb/embeddings/openai.py index 1edfaa2ca..d4ecbdf3f 100644 --- a/python/python/lancedb/embeddings/openai.py +++ b/python/python/lancedb/embeddings/openai.py @@ -101,24 +101,35 @@ class OpenAIEmbeddings(TextEmbeddingFunction): valid_indices.append(idx) # TODO retry, rate limit, token limit - try: + def embed_batch(texts_batch, indices_batch): kwargs = { - "input": valid_texts, + "input": texts_batch, "model": self.name, } if self.name != "text-embedding-ada-002": kwargs["dimensions"] = self.dim rs = self._openai_client.embeddings.create(**kwargs) - valid_embeddings = { - idx: v.embedding for v, idx in zip(rs.data, valid_indices) - } + return {idx: v.embedding for v, idx in zip(rs.data, indices_batch)} + + def embed_one_or_log(idx, text): + # Retry a single rejected input + try: + return embed_batch([text], [idx]) + except openai.BadRequestError: + logging.exception("Bad request for input at index %d: %r", idx, text) + return {} + + try: + valid_embeddings = embed_batch(valid_texts, valid_indices) except openai.AuthenticationError: logging.error("Authentication failed: Invalid API key provided") raise except openai.BadRequestError: - logging.exception("Bad request: %s", texts) - return [None] * len(texts) + # Retry each input individually + valid_embeddings = {} + for idx, text in zip(valid_indices, valid_texts): + valid_embeddings.update(embed_one_or_log(idx, text)) except Exception: logging.exception("OpenAI embeddings error") raise diff --git a/python/python/lancedb/embeddings/registry.py b/python/python/lancedb/embeddings/registry.py index 1dc7ffcb8..a7093094d 100644 --- a/python/python/lancedb/embeddings/registry.py +++ b/python/python/lancedb/embeddings/registry.py @@ -69,11 +69,15 @@ class EmbeddingFunctionRegistry: def decorator(cls): if not issubclass(cls, EmbeddingFunction): raise TypeError("Must be a subclass of EmbeddingFunction") - if cls.__name__ in self._functions: - raise KeyError(f"{cls.__name__} was already registered") key = alias or cls.__name__ + if key in self._functions and ( + not alias or self._functions[key] is not cls + ): + raise KeyError(f"{key} was already registered") self._functions[key] = cls - cls.__embedding_function_registry_alias__ = alias + # Store the name the class is registered under, so the table + # metadata written for it can be looked up again when reading. + cls.__embedding_function_registry_alias__ = key return cls return decorator @@ -97,6 +101,25 @@ class EmbeddingFunctionRegistry: """ return self._functions[name] + def list_functions(self) -> list[str]: + """List the names of registered embedding functions. + + Returns + ------- + list[str] + Registered aliases, or class names for functions registered without + an alias, in registration order. Each name can be passed to + :meth:`get`. The returned list is a copy; changing it does not + change the registry. + + Examples + -------- + >>> registry = get_registry() + >>> "openai" in registry.list_functions() + True + """ + return list(self._functions) + def parse_functions( self, metadata: Optional[Dict[bytes, bytes]] ) -> Dict[str, "EmbeddingFunctionConfig"]: diff --git a/python/python/lancedb/embeddings/utils.py b/python/python/lancedb/embeddings/utils.py index f76c9b1a5..ff8fc6a18 100644 --- a/python/python/lancedb/embeddings/utils.py +++ b/python/python/lancedb/embeddings/utils.py @@ -241,15 +241,30 @@ def retry_with_exponential_backoff( exponential_base: float = 2, jitter: bool = True, max_retries: int = 7, + max_delay: float = 60, ): """Retry a function with exponential backoff. + Only errors that may succeed when repeated are retried. Errors that carry an + HTTP status code are retried when the status is 408, 409, 429 or >= 500; any + other 4xx status (for example 400, 401, 403, 404 or 422) is a permanent failure + that is raised immediately. Errors without a recognisable status code (for + example connection errors, timeouts, or exceptions raised by a custom embedding + function) are retried. + + The delay before the n-th retry is ``initial_delay * exponential_base ** n``, + never more than ``max_delay``. With ``jitter`` enabled, a random amount of up to + half of that delay is removed ("equal jitter"), so the actual wait is always in + the range ``[delay / 2, delay]``. + Args: func (function): The function to be retried. initial_delay (float): Initial delay in seconds (default is 1). exponential_base (float): The base for exponential backoff (default is 2). jitter (bool): Whether to add jitter to the delay (default is True). max_retries (int): Maximum number of retries (default is 7). + max_delay (float): Maximum delay between two attempts, in seconds + (default is 60). Returns: function: The decorated function. @@ -265,13 +280,12 @@ def retry_with_exponential_backoff( try: return func(*args, **kwargs) - # Currently retrying on all exceptions as there is no way to know the - # format of the error msgs used by different APIs. We'll log the error - # and say that it is assumed that if this portion errors out, it's due - # to rate limit but the user should check the error message to be sure. + # Errors are retried unless they are known to be permanent (see + # `_is_non_retryable_error`). Custom embedding functions can raise + # arbitrary exceptions, so unknown errors are assumed to be transient. except Exception as e: # noqa: PERF203 - # Don't retry on authentication errors (e.g., OpenAI 401) - # These are permanent failures that won't be fixed by retrying + # Don't retry permanent failures (e.g., OpenAI 401 or 404). They + # won't be fixed by retrying and would only delay the real error. if _is_non_retryable_error(e): raise @@ -280,24 +294,72 @@ def retry_with_exponential_backoff( if num_retries > max_retries: raise Exception( f"Maximum number of retries ({max_retries}) exceeded.", e - ) + ) from e - delay *= exponential_base * (1 + jitter * random.random()) + delay = min(delay * exponential_base, max_delay) + sleep_for = delay + if jitter: + sleep_for = delay / 2 + random.random() * delay / 2 logging.warning( "Error occurred: %s \n Retrying in %s seconds (retry %s of %s) \n", e, - delay, + sleep_for, num_retries, max_retries, ) - time.sleep(delay) + time.sleep(sleep_for) return wrapper +# HTTP statuses in the 4xx range that are worth retrying: request timeout, +# conflict (the OpenAI SDK treats it as transient) and rate limiting. +_RETRYABLE_CLIENT_STATUSES = (408, 409, 429) + +# AWS error codes that are reported with a 4xx status but are transient. +_RETRYABLE_AWS_ERROR_CODES = ( + "Throttl", + "TooManyRequests", + "RequestLimitExceeded", + "ProvisionedThroughputExceeded", + "ModelNotReady", + "ModelTimeout", +) + + +def _get_http_status(error: Exception): + """Best-effort extraction of an HTTP status code from an exception. + + Provider SDKs expose it in different ways: ``status_code`` (openai, cohere), + ``http_status`` (voyageai), ``response.status_code`` (requests, httpx), + ``code`` (google-api-core, urllib) or ``response["ResponseMetadata"]`` + (botocore). Returns None if no status can be found. + """ + candidates = [ + getattr(error, "status_code", None), + getattr(error, "http_status", None), + ] + response = getattr(error, "response", None) + if isinstance(response, dict): + candidates.append(response.get("ResponseMetadata", {}).get("HTTPStatusCode")) + else: + candidates.append(getattr(response, "status_code", None)) + candidates.append(getattr(error, "code", None)) + + for status in candidates: + if isinstance(status, int) and not isinstance(status, bool): + if 100 <= status <= 599: + return status + return None + + def _is_non_retryable_error(error: Exception) -> bool: """Check if an error should not be retried. + An error is non-retryable if it is an authentication error or if it carries an + HTTP client-error status (4xx) other than 408, 409 and 429. Errors without a + recognisable status are treated as retryable. + Args: error: The exception to check @@ -314,13 +376,25 @@ def _is_non_retryable_error(error: Exception) -> bool: if error_type == "AuthenticationError": return True - # Check for other common non-retryable HTTP status codes - # 401 Unauthorized, 403 Forbidden - if hasattr(error, "status_code"): - if error.status_code in (401, 403): - return True + # A missing API key or a missing optional dependency fails the same way on + # every attempt + if isinstance(error, (MissingApiKeyError, ImportError)): + return True - return False + status = _get_http_status(error) + if status is None or not 400 <= status < 500: + return False + if status in _RETRYABLE_CLIENT_STATUSES: + return False + + # AWS reports throttling with a 400 status; the error code tells them apart. + response = getattr(error, "response", None) + if isinstance(response, dict): + aws_code = str(response.get("Error", {}).get("Code", "")) + if aws_code.startswith(_RETRYABLE_AWS_ERROR_CODES): + return False + + return True def url_retrieve(url: str): @@ -337,9 +411,15 @@ def url_retrieve(url: str): raise ConnectionError("could not download {} due to {}".format(url, err)) +class MissingApiKeyError(ValueError): + """Raised when an embedding provider's API key is not set.""" + + def api_key_not_found_help(provider): logging.error("Could not find API key for %s", provider) - raise ValueError(f"Please set the {provider.upper()}_API_KEY environment variable.") + raise MissingApiKeyError( + f"Please set the {provider.upper()}_API_KEY environment variable." + ) def is_flash_attn_2_available(): diff --git a/python/python/lancedb/embeddings/voyageai.py b/python/python/lancedb/embeddings/voyageai.py index 4a721c998..bcb2fd5a3 100644 --- a/python/python/lancedb/embeddings/voyageai.py +++ b/python/python/lancedb/embeddings/voyageai.py @@ -75,7 +75,7 @@ def transform_input(input_data: Union[str, bytes, Path]): content = {"type": "text", "text": input_data} elif isinstance(input_data, PIL_Image.Image): buffered = BytesIO() - input_data.save(buffered, format="JPEG") + input_data.convert("RGB").save(buffered, format="JPEG") img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") content = { "type": "image_base64", @@ -84,7 +84,7 @@ def transform_input(input_data: Union[str, bytes, Path]): elif isinstance(input_data, bytes): img = PIL_Image.open(BytesIO(input_data)) buffered = BytesIO() - img.save(buffered, format="JPEG") + img.convert("RGB").save(buffered, format="JPEG") img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") content = { "type": "image_base64", @@ -103,7 +103,7 @@ def transform_input(input_data: Union[str, bytes, Path]): else: img = PIL_Image.open(input_data) buffered = BytesIO() - img.save(buffered, format="JPEG") + img.convert("RGB").save(buffered, format="JPEG") img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") content = { "type": "image_base64", @@ -145,6 +145,8 @@ def sanitize_text_input(inputs: TEXT) -> List[str]: """ if isinstance(inputs, str): inputs = [inputs] + elif isinstance(inputs, (list, np.ndarray)): + inputs = list(inputs) elif isinstance(inputs, pa.Array): inputs = inputs.to_pylist() elif isinstance(inputs, pa.ChunkedArray): diff --git a/python/python/lancedb/expr.py b/python/python/lancedb/expr.py index 80d01e29a..f65fbd21a 100644 --- a/python/python/lancedb/expr.py +++ b/python/python/lancedb/expr.py @@ -79,6 +79,13 @@ class Expr: >>> from lancedb.expr import col, lit >>> filt = (col("age") > lit(18)) & (col("name").lower() == lit("alice")) >>> proj = {"double": col("x") * lit(2)} + + Notes + ----- + An ``Expr`` has no Python truth value: ``bool(expr)`` raises ``TypeError``. + Combine expressions with ``&``, ``|`` and ``~`` (wrapping each comparison in + parentheses) instead of ``and``, ``or`` and ``not``, and write a range as + ``(col("x") > 1) & (col("x") < 5)`` rather than ``1 < col("x") < 5``. """ # Make Expr unhashable so that == returns an Expr rather than being used @@ -89,6 +96,19 @@ class Expr: self._inner = inner self._column_path = column_path + def __bool__(self) -> bool: + # An Expr describes a predicate that the query engine evaluates per row, + # so it has no Python truth value. Without this, ``and`` / ``or`` / + # ``not`` and chained comparisons (``1 < col("x") < 5``) would silently + # keep a single operand and drop the rest of the filter. + raise TypeError( + "The truth value of an Expr is ambiguous. Combine expressions with " + "'&' (and), '|' (or) and '~' (not), and wrap each comparison in " + "parentheses, e.g. (col('x') > 1) & (col('x') < 5). Do not use " + "'and', 'or', 'not', 'in' or chained comparisons such as " + "1 < col('x') < 5; use Expr.isin() for membership." + ) + # ── comparisons ────────────────────────────────────────────────────────── def __eq__(self, other: ExprLike) -> "Expr": # type: ignore[override] diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 7f5776b32..2125542af 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -4,7 +4,7 @@ """Canonical Function values exchanged with LanceDB Enterprise services. These immutable models contain client/wire state only. Catalog persistence, -environment bake, secret resolution, and execution are owned by Sophon. +environment bake, secret resolution, and execution are owned by LanceDB Enterprise. ``RefreshColumnResult`` is also the backend-neutral result of a local expression-backed refresh job. """ @@ -33,6 +33,7 @@ from typing import ( Annotated, Any, Callable, + Literal, Optional, Union, get_args, @@ -52,7 +53,9 @@ from pydantic import ( model_validator, ) +from .schema import blob as _blob_field from .schema import is_blob_v2_field as _is_blob_v2_field +from ._blob_reader import BlobReader from .secrets import EnvVarSecret _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) @@ -213,6 +216,7 @@ class FunctionParameter(_RemoteValue): name: str arrow_type: str nullable: bool + blob_access: Optional[Literal["bytes", "reader"]] = None class FunctionResultField(_OpenRemoteValue): @@ -271,7 +275,7 @@ class FunctionSignature(_RemoteValue): class PythonEnvironmentSpec(_RemoteValue): - """One Sophon-managed Python environment source.""" + """One LanceDB Enterprise-managed Python environment source.""" kind: str packages: tuple[str, ...] = () @@ -279,6 +283,7 @@ class PythonEnvironmentSpec(_RemoteValue): path: Optional[str] = None modules: tuple[str, ...] = () image: Optional[str] = None + system_packages: tuple[str, ...] = () class PythonRuntimeSpec(_RemoteValue): @@ -362,6 +367,12 @@ class FunctionVersion(_RemoteValue): [SecretReference][lancedb.functions.SecretReference] carries a Secret's; they are what [get_function][lancedb.db.DBConnection.get_function] takes. An empty ``namespace_path`` is the root namespace. + + ``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. + It is ``None`` when the server does not provide a source digest. """ name: str @@ -370,6 +381,7 @@ class FunctionVersion(_RemoteValue): location: str version: _ObjectVersion image: FunctionImage + source_digest: Optional[str] = None signature: FunctionSignature secret_bindings: tuple[SecretBinding, ...] = () created_at_millis: int @@ -649,8 +661,8 @@ class FunctionBinding(_RemoteValue): class RefreshColumnResult(_RemoteValue): """Terminal result of an expression-backed or Function-backed refresh Job. - Local jobs produce this value in process. LanceDB Cloud and Enterprise - decode the same value from the durable server-job terminal payload. + LanceDB Embedded jobs produce this value in process. LanceDB Distributed + decodes the same value from the durable server-job terminal payload. """ rows_assigned: _UInt64 @@ -670,7 +682,7 @@ class RefreshColumnResult(_RemoteValue): return self.published_version -_FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*$") +_FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") _FUNCTION_BLOB_V2_TYPE = "blob_v2" _ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name" @@ -989,6 +1001,11 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: if isinstance(annotation, pa.DataType): return annotation, nullable + if annotation is pa.Array or annotation is pa.RecordBatch: + raise TypeError( + f"cannot infer Arrow types from Function annotation {annotation!r}; " + "provide input_schema and output_schema together for batch callables" + ) if annotation is bool: return pa.bool_(), nullable if annotation is int: @@ -1093,8 +1110,43 @@ def _infer_signature( parameters = _callable_parameters(function) if method: parameters = parameters[1:] - if (input_schema is None) != (output_schema is None): - raise ValueError("input_schema and output_schema must be provided together") + + try: + annotations = get_type_hints(function, include_extras=True) + except Exception as error: + raise TypeError(f"failed to resolve Function annotations: {error}") from error + + def input_parameter(field): + annotation = annotations.get(field.name) + if get_origin(annotation) in (Union, types.UnionType): + choices = [ + value for value in get_args(annotation) if value is not type(None) + ] + if len(choices) == 1: + annotation = choices[0] + arrow_type = _canonical_arrow_field(field) + if annotation is BlobReader: + if arrow_type != _FUNCTION_BLOB_V2_TYPE: + raise TypeError( + f"BlobReader input '{field.name}' requires a Blob V2 field" + ) + access = "reader" + elif annotation is bytes: + if arrow_type != _FUNCTION_BLOB_V2_TYPE and not ( + pa.types.is_binary(field.type) or pa.types.is_large_binary(field.type) + ): + raise TypeError( + f"bytes input '{field.name}' requires binary or Blob V2" + ) + access = "bytes" + else: + access = "bytes" if arrow_type == _FUNCTION_BLOB_V2_TYPE else None + return FunctionParameter( + name=field.name, + arrow_type=arrow_type, + nullable=field.nullable, + blob_access=access, + ) if input_schema is not None: if not isinstance(input_schema, pa.Schema): @@ -1110,45 +1162,46 @@ def _infer_signature( "input_schema fields must exactly match callable parameters in order: " f"expected {expected!r}, got {actual!r}" ) - inputs = tuple( - FunctionParameter( - name=field.name, - arrow_type=_canonical_arrow_field(field), - nullable=field.nullable, - ) - for field in input_schema - ) - return FunctionSignature(inputs=inputs, output=_function_output(output_schema)) + inputs = tuple(input_parameter(field) for field in input_schema) + else: + inputs = None + + missing = [] + if inputs is None: + missing += [p.name for p in parameters if p.name not in annotations] + if output_schema is None and "return" not in annotations: + missing.append("return") + if missing: + raise TypeError(f"missing Function annotations: {missing!r}") + if output_schema is not None: + output = _function_output(output_schema) + else: + output_type, output_nullable = _annotation_type(annotations["return"]) + if output_nullable: + raise ValueError("Function output must be non-nullable") + output = _function_output(pa.field("result", output_type, nullable=False)) + if inputs is not None: + return FunctionSignature(inputs=inputs, output=output) - try: - annotations = get_type_hints(function, include_extras=True) - except Exception as error: - raise TypeError(f"failed to resolve Function annotations: {error}") from error - missing = [ - parameter.name for parameter in parameters if parameter.name not in annotations - ] - if missing or "return" not in annotations: - names = missing + ([] if "return" in annotations else ["return"]) - raise TypeError(f"missing Function annotations: {names!r}") inputs = [] for parameter in parameters: - data_type, nullable = _annotation_type(annotations[parameter.name]) - inputs.append( - FunctionParameter( - name=parameter.name, - arrow_type=_canonical_arrow_field( - pa.field(parameter.name, data_type, nullable=nullable) - ), - nullable=nullable, + annotation = annotations[parameter.name] + base = annotation + nullable = False + if get_origin(base) in (Union, types.UnionType): + choices = [value for value in get_args(base) if value is not type(None)] + if len(choices) == 1: + base, nullable = choices[0], True + if base is BlobReader: + inputs.append( + input_parameter(_blob_field(parameter.name, nullable=nullable)) ) + continue + data_type, nullable = _annotation_type(annotation) + inputs.append( + input_parameter(pa.field(parameter.name, data_type, nullable=nullable)) ) - output_type, output_nullable = _annotation_type(annotations["return"]) - if output_nullable: - raise ValueError("Function output must be non-nullable") - return FunctionSignature( - inputs=tuple(inputs), - output=_function_output(pa.field("result", output_type, nullable=False)), - ) + return FunctionSignature(inputs=tuple(inputs), output=output) def _is_udf_decorator(node: ast.expr) -> bool: @@ -1239,7 +1292,7 @@ _PYTHON_CALLABLE_ARTIFACT = "python_callable" _PYTHON_BUNDLE_ARTIFACT = "python_bundle" # Modules the Function image places beside user code. _RESERVED_SOURCE_MODULES = frozenset( - {"user_function", "lance_source", "lance_callable"} + {"user_function", "lance_source", "lance_callable", "lance_blob"} ) # The service accepts bundle paths made of these components only. _SOURCE_PATH_COMPONENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") @@ -1426,8 +1479,8 @@ class _SourcePackager: self._packaged: set[int] = set() self._names: dict[str, Any] = {} - def package(self, target: Any) -> str: - entry = self._definition(target, entry=True) + def package(self, target: Any, signature: FunctionSignature) -> str: + entry = self._definition(target, entry=True, signature=signature) parts = [_SOURCE_HEADER] if self._imports: parts.extend(["", *(self._imports[name] for name in sorted(self._imports))]) @@ -1436,12 +1489,20 @@ class _SourcePackager: parts.extend(["", entry, ""]) return "\n".join(parts) - def _definition(self, target: Any, *, entry: bool) -> str: + def _definition( + self, target: Any, *, entry: bool, signature: Optional[FunctionSignature] = None + ) -> str: 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" ) + namespace = _definition_namespace(target) + reader_name = ( + self._blob_annotations(definition, signature, namespace) + if signature is not None + else None + ) source = ast.unparse(definition) references = _module_references(f"{_SOURCE_HEADER}\n\n{source}\n") dynamic = _namespace_acquisition(definition, references) @@ -1449,9 +1510,10 @@ class _SourcePackager: raise ValueError( f"@udf cannot package dynamic namespace access: {dynamic!r}" ) - namespace = _definition_namespace(target) self._packaged.add(id(target)) self._claim(target.__name__, ("definition", id(target))) + if reader_name is not None: + self._bind(reader_name, BlobReader) unresolved = [] for name in sorted(references): if name == target.__name__: @@ -1472,6 +1534,44 @@ class _SourcePackager: ) return source + def _blob_annotations( + self, + definition: Union[ast.FunctionDef, ast.ClassDef], + signature: FunctionSignature, + namespace: Mapping[str, Any], + ) -> Optional[str]: + """Bind reader inputs to the worker type, including postponed aliases.""" + readers = { + parameter.name: parameter + for parameter in signature.inputs + if parameter.blob_access == "reader" + } + if not readers: + return None + call = definition + if isinstance(definition, ast.ClassDef): + call = next( + ( + member + for member in definition.body + if isinstance(member, ast.FunctionDef) and member.name == "__call__" + ), + None, + ) + if call is None: + return None + # Avoid shadowing globals used by the body or other packaged definitions. + name = "_lance_blob_reader" + while name in namespace or name in self._names or name == definition.name: + name += "_" + for argument in (*call.args.args, *call.args.kwonlyargs): + if argument.arg in readers: + annotation = name + if readers[argument.arg].nullable: + annotation += " | None" + argument.annotation = ast.parse(annotation, mode="eval").body + return name + def _claim(self, name: str, meaning: Any) -> None: claimed = self._names.setdefault(name, meaning) if claimed != meaning: @@ -1499,6 +1599,8 @@ class _SourcePackager: """One module-level line that rebinds `name` to `value` in the artifact: an import for modules and importable classes/functions, a literal otherwise.""" + if value is BlobReader: + return f"from lance_blob import BlobReader as {name}" if isinstance(value, types.ModuleType): if value.__name__.split(".")[0] in _NAMESPACE_MODULES: raise ValueError( @@ -1753,6 +1855,7 @@ class UdfDefinition: gpu: bool = False, conda: tuple[str, ...] = (), conda_channels: tuple[str, ...] = (), + apt: tuple[str, ...] = (), code: tuple[types.ModuleType, ...] = (), ): is_class = inspect.isclass(function) @@ -1768,14 +1871,23 @@ class UdfDefinition: if conda_channels and not conda: raise ValueError("conda_channels requires conda packages") packages = tuple(sorted(set(conda if conda else pip))) - if any(not package or package != package.strip() for package in packages): + system_packages = tuple(sorted(set(apt))) + if any( + not package or package != package.strip() + for package in packages + system_packages + ): raise ValueError("package requirements must be non-empty and trimmed") if conda: environment_spec = PythonEnvironmentSpec( - kind="conda", packages=packages, channels=tuple(conda_channels) + kind="conda", + packages=packages, + channels=tuple(conda_channels), + system_packages=system_packages, ) else: - environment_spec = PythonEnvironmentSpec(kind="pip", packages=packages) + environment_spec = PythonEnvironmentSpec( + kind="pip", packages=packages, system_packages=system_packages + ) environment = dict(env) if any( not isinstance(key, str) or not isinstance(value, str) @@ -1807,7 +1919,7 @@ class UdfDefinition: code_files, code_modules = _code_files(code) entry_source = _SourcePackager( code_modules, frozenset(_requirement_name(package) for package in packages) - ).package(function) + ).package(function, signature) if code_files: kind = _PYTHON_BUNDLE_ARTIFACT source = json.dumps( @@ -1944,6 +2056,7 @@ def udf( gpu: bool = False, conda: tuple[str, ...] | list[str] = (), conda_channels: tuple[str, ...] | list[str] = (), + apt: tuple[str, ...] | list[str] = (), code: Sequence[types.ModuleType] = (), ) -> Callable[[Callable[..., Any]], UdfDefinition]: ... @@ -1960,20 +2073,33 @@ def udf( gpu: bool = False, conda: tuple[str, ...] | list[str] = (), conda_channels: tuple[str, ...] | list[str] = (), + apt: tuple[str, ...] | list[str] = (), code: Sequence[types.ModuleType] = (), ): """Prepare a Python function or class for remote Function registration. - Input and output signatures are inferred from supported annotations. For - Arrow types annotations cannot express precisely, pass ``input_schema`` - and ``output_schema`` together. Scalar outputs must be non-nullable. Every - named-struct field may be nullable; Enterprise preserves the struct's - validity when the result is expanded into sibling columns. + Input and output signatures are inferred from supported annotations. A + parameter annotated ``T`` is non-nullable and binds only a non-nullable + column; annotate ``Optional[T]`` to bind a nullable one, and it receives + ``None`` for a null value. PyArrow fields are nullable unless declared + otherwise, so most columns need ``Optional``. For Arrow types annotations + cannot express precisely, pass ``input_schema``, ``output_schema``, or + both; the one omitted is inferred. Scalar outputs must be non-nullable. + Every named-struct field may be nullable; Enterprise preserves the + struct's validity when the result is expanded into sibling columns. + + **Large values.** A ``bytes`` parameter receives the whole value, which + is held in memory with its row and counts against the server's per-row + input limit. To pass large binary values, such as video, store them in a + Blob V2 column and annotate the parameter ``BlobReader``, which streams. **Functions and classes.** A decorated function is called once per row, or once per batch when its parameters are annotated ``pyarrow.Array`` or - it takes one ``pyarrow.RecordBatch``. A decorated class is the same - callable with state: each remote instance calls ``__init__`` once, calls + it takes one ``pyarrow.RecordBatch``. These batch annotations require both + ``input_schema`` and ``output_schema`` explicitly: the annotations do not + specify Arrow element types or fields. This also applies to a class's + ``__call__`` method. A decorated class is the same callable with state: + each remote instance calls ``__init__`` once, calls ``__call__`` for every row or batch of every input it processes, and calls ``close()``, if defined, once when it retires. Load models, open clients, and build rate limiters in ``__init__``; every batch of the instance then @@ -2021,18 +2147,28 @@ def udf( The synchronous callable, or the class whose instances are called. name : str, optional The remote Function name. Defaults to the callable name. + Must start with an ASCII letter or underscore and contain only ASCII + letters, digits, and underscores. input_schema : pyarrow.Schema, optional Explicit input fields in the exact order of the callable parameters. - Must be provided together with ``output_schema``. + Required for batch annotations. When omitted, inputs are inferred from + the parameter annotations. output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional Explicit scalar or named-struct output. Scalar outputs must be - non-nullable. Must be provided together with ``input_schema``. + non-nullable. Required for batch annotations. When omitted, the output + is inferred from the return annotation. pip : sequence of str, optional Pip requirements for the remote environment. conda : sequence of str, optional Conda packages for the remote environment, instead of ``pip``. conda_channels : sequence of str, optional Conda channels in priority order; requires ``conda``. + apt : sequence of str, optional + Debian packages (``"name"`` or ``"name=version"``) added to the remote + image before the Python environment, for shared libraries pip and + 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. env : mapping of str to str, optional Environment variables included in the Function definition. Not for credentials -- these are ordinary configuration, stored with the @@ -2064,6 +2200,15 @@ def udf( ... return value * 2 >>> score(1.5) 3.0 + >>> import pyarrow as pa + >>> @udf( + ... input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + ... output_schema=pa.int64(), + ... ) + ... def batch_identity(value: pa.Array) -> pa.Array: + ... return value + >>> batch_identity(pa.array([1, 2, 3])).to_pylist() + [1, 2, 3] >>> @udf(pip=["cupy-cuda12x"], gpu=True) ... def gpu_score(value: int) -> int: ... return value * 2 @@ -2093,6 +2238,7 @@ def udf( gpu=gpu, conda=tuple(conda), conda_channels=tuple(conda_channels), + apt=tuple(apt), code=tuple(code), ) diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py index cf3bf8e4f..8c192a2f0 100644 --- a/python/python/lancedb/index.py +++ b/python/python/lancedb/index.py @@ -145,9 +145,9 @@ class FTS: Lance tokenizer can panic on malformed triples; see https://github.com/lance-format/lance/issues/8812. - Remote tables use the same ``FTS()`` configuration and require a server - that supports JSON FTS. Wait for ``table.wait_for_index(["doc_idx"])`` - before searching a newly created remote index with its default name. + LanceDB Distributed 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. Examples -------- @@ -210,12 +210,12 @@ 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 remote tables. + not persisted with the index and does not apply to LanceDB Distributed. 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 remote tables. + not persisted with the index and does not apply to LanceDB Distributed. 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 @@ -882,8 +882,12 @@ class IvfRq: num_partitions: int, default sqrt(num_rows) Number of IVF partitions to create. - num_bits: int, default 1 + num_bits: int, optional Number of bits to encode each dimension in the RabitQ codebook. + If None, uses Lance's default (currently 5), matching Rust and Node. + Set to 1 to retain the previous Python default and maximum compression. + Five-bit vector codes use roughly five times the storage of one-bit codes, + in addition to other index overhead. max_iterations: int, default 50 Max iterations to train kmeans when computing IVF partitions. @@ -897,7 +901,7 @@ class IvfRq: distance_type: Literal["l2", "cosine", "dot"] = "l2" num_partitions: Optional[int] = None - num_bits: int = 1 + num_bits: Optional[int] = None max_iterations: int = 50 sample_rate: int = 256 target_partition_size: Optional[int] = None diff --git a/python/python/lancedb/integrations/pyarrow.py b/python/python/lancedb/integrations/pyarrow.py index 085964690..1626a6b57 100644 --- a/python/python/lancedb/integrations/pyarrow.py +++ b/python/python/lancedb/integrations/pyarrow.py @@ -52,6 +52,9 @@ class PyarrowScannerAdapter(pa.dataset.Scanner): raise NotImplementedError("memory_pool not supported") def count_rows(self): + if isinstance(self.filter, pa.compute.Expression): + # stream the batches so memory does not grow with the matching rows + return sum(batch.num_rows for batch in self.to_reader()) return self.table.count_rows(self.filter) def from_batches(self, **kwargs): @@ -83,6 +86,8 @@ class PyarrowScannerAdapter(pa.dataset.Scanner): return self.to_reader().read_all() def to_reader(self, *, limit: Optional[int] = None): + if isinstance(self.filter, pa.compute.Expression): + return self._to_reader_with_expression(limit=limit) query = self.table.search() # Disable the builtin limit if limit is None: @@ -98,13 +103,30 @@ class PyarrowScannerAdapter(pa.dataset.Scanner): query = query.where(self.filter, prefilter=True) return query.to_batches(batch_size=self.batch_size) + def _to_reader_with_expression(self, *, limit: Optional[int] = None): + # LanceDB filters are SQL strings, but engines such as DuckDB push down + # pyarrow compute expressions. Scan the table and apply the filter and + # projection with pyarrow, since the filter may reference columns that + # are not part of the projection. + if limit is not None and limit <= 0: + raise ValueError("limit must be positive") + query = self.table.search().limit(self.table.count_rows()) + scanner = pa.dataset.Scanner.from_batches( + query.to_batches(batch_size=self.batch_size), + columns=self.columns, + filter=self.filter, + ) + if limit is None: + return scanner.to_reader() + return scanner.head(limit).to_reader() + class PyarrowDatasetAdapter(pa.dataset.Dataset): def __init__(self, table: Table): self.table = table def count_rows(self, filter: Optional[Filter] = None): - return self.table.count_rows(filter) + return self.scanner(filter=filter).count_rows() def get_fragments(self, filter: Optional[Filter] = None): raise NotImplementedError diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index e57fde0ea..e61a188f2 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Handles to operations a server may run asynchronously.""" +"""Handles to asynchronous registry jobs, SQL queries, and local operations.""" import asyncio import json @@ -44,12 +44,12 @@ class AsyncJob(Generic[T]): @property def id(self) -> Optional[str]: - """Identifies the operation on the server that is running it. + """The operation's opaque ID, interpreted according to :attr:`job_type`. - Returned for correlating with server logs or the jobs API. Operations - that run in this process have no server id and return `None`. The value - is opaque: parsing it or storing it to resume the job later is not - supported. + Registry jobs expose a registry job ID; SQL-backed jobs expose a + connection-scoped query ID as a string. Local operations return ``None``. + Query IDs cannot be used with registry job APIs or to resume after a + client restart. """ return self._inner.id if self._inner is not None else None @@ -94,9 +94,11 @@ class AsyncJob(Generic[T]): """Ask the backend for this job's current state, and for a server-side job its full record, then cache it for the properties below. - The properties are all `None` until this runs, because submitting an - operation returns only a job id. `status` fetches the whole record too; - `wait` records only the terminal state it establishes. + Registry details are `None` until this runs, because submitting an + operation does not fetch its full registry record. Query-backed jobs + expose only lifecycle state through this method. For registry jobs, + `status` fetches the whole record too; `wait` records only the terminal + state it establishes. """ if self._inner is None: return @@ -114,11 +116,13 @@ class AsyncJob(Generic[T]): @property def job_type(self) -> Optional[str]: - """The job's type, as the server names it. + """The job's kind of work, without contacting the backend. - `None` for an in-process job, which has no server-side record. + SQL-backed handles report ``"query"`` immediately. Registry handles + report the server's job type after :meth:`refresh` or :meth:`status`. + In-process handles return ``None``. """ - return self._field("job_type") + return self._inner.job_type if self._inner is not None else None @property def creation_ms(self) -> Optional[int]: @@ -294,7 +298,7 @@ class Job(Generic[T]): @property def job_type(self) -> Optional[str]: """The job's type. See :attr:`AsyncJob.job_type`.""" - return self._field("job_type") + return self._inner.job_type if self._inner is not None else None @property def creation_ms(self) -> Optional[int]: diff --git a/python/python/lancedb/listing.py b/python/python/lancedb/listing.py index 0620aa7d8..8abc9d85b 100644 --- a/python/python/lancedb/listing.py +++ b/python/python/lancedb/listing.py @@ -5,6 +5,7 @@ from __future__ import annotations +import asyncio from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar from .background_loop import LOOP @@ -83,3 +84,173 @@ class Listing(Iterator[T], Generic[T]): for initial, cached, final-page, and error behavior. """ return self._inner.page_token() + + +def validate_page_limit(limit: Optional[int]) -> None: + """Validate the legacy limit argument before passing it to the bindings.""" + if limit is not None and ( + not isinstance(limit, int) or limit < 0 or limit > 2**31 - 1 + ): + raise ValueError("limit must be between 0 and 2147483647") + + +class _AsyncPagedNameListing(AsyncIterator[str]): + """An async listing with an inspectable copy of its current backend page.""" + + def __init__( + self, inner: Any, page_token: Optional[str] = None, *, empty: bool = False + ): + self._inner = inner + self._token = page_token + self._page: Optional[list[str]] = [] if empty else None + self._position = 0 + self._done = empty + self._failure: Optional[BaseException] = None + self._lock = asyncio.Lock() + + @property + def page_token(self) -> Optional[str]: + """The continuation token for the next backend request.""" + return self._token + + def num_page_results(self) -> int: + """Count the remaining names in the current page.""" + return 0 if self._page is None else len(self._page) - self._position + + def _page_copy(self) -> list[str]: + if self._page is None: + raise RuntimeError("Await or iterate the listing before reading its page") + return self._page.copy() + + async def _fetch_page(self) -> None: + try: + page = await self._inner.next_page() + except asyncio.CancelledError: + raise + except BaseException as exc: + self._failure = exc + self._done = True + raise + if page is None: + self._page = [] + self._token = None + self._done = True + else: + self._page = page["items"] + self._token = page["page_token"] + self._done = self._token is None + self._position = 0 + + async def _load_initial(self): + async with self._lock: + if self._failure is not None: + raise self._failure + if self._page is None: + await self._fetch_page() + return self + + def __await__(self): + return self._load_initial().__await__() + + def __aiter__(self): + return self + + async def __anext__(self) -> str: + async with self._lock: + if self._failure is not None: + raise StopAsyncIteration + if self._page is None: + await self._fetch_page() + assert self._page is not None + while self._position >= len(self._page): + if self._done: + raise StopAsyncIteration + await self._fetch_page() + assert self._page is not None + item = self._page[self._position] + self._position += 1 + return item + + +class AsyncTableListing(_AsyncPagedNameListing): + """Awaitable table iterator; awaiting loads one page. + + For example:: + + page = await db.list_tables(limit=20) + print(page.tables, page.page_token) + async for name in db.list_tables(limit=20): + print(name) + """ + + @property + def tables(self) -> list[str]: + """A copy of every table name in the most recently fetched page.""" + return self._page_copy() + + +class AsyncNamespaceListing(_AsyncPagedNameListing): + """Awaitable namespace iterator; awaiting loads one page. + + For example:: + + page = await db.list_namespaces(limit=20) + print(page.namespaces, page.page_token) + """ + + @property + def namespaces(self) -> list[str]: + """A copy of every name in the most recently fetched page.""" + return self._page_copy() + + +class _PagedNameListing(Iterator[str]): + def __init__(self, inner: _AsyncPagedNameListing): + self._inner = inner + LOOP.run(inner._load_initial()) + + def __iter__(self): + return self + + def __next__(self) -> str: + try: + return LOOP.run(self._inner.__anext__()) + except StopAsyncIteration: + raise StopIteration from None + + @property + def page_token(self) -> Optional[str]: + return self._inner.page_token + + def num_page_results(self) -> int: + return self._inner.num_page_results() + + +class TableListing(_PagedNameListing): + """Table iterator retaining the current page as a list. + + For example:: + + page = db.list_tables(limit=20) + print(page.tables, page.page_token) + for name in db.list_tables(limit=20): + print(name) + """ + + @property + def tables(self) -> list[str]: + return self._inner.tables + + +class NamespaceListing(_PagedNameListing): + """Namespace iterator retaining the current page as a list. + + For example:: + + page = db.list_namespaces(limit=20) + print(page.namespaces, page.page_token) + """ + + @property + def namespaces(self) -> list[str]: + return self._inner.namespaces diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index 6342641ff..7b0b3b80a 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -2,7 +2,13 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors """Materialized views: tables defined by a query over a source table and -maintained by refresh. See ``DBConnection.create_materialized_view``.""" +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 +available. +""" from __future__ import annotations @@ -179,31 +185,38 @@ class AsyncMaterializedView: return _definition_from_json(raw) async def refresh( - self, *, source_version: Optional[int] = None + self, *, full: bool = False, source_version: Optional[int] = None ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. - Every refresh rebuilds the complete view. For local views, - ``source_version`` refreshes to that source version instead of the - latest; remote SQL refreshes do not support source-version pinning. + In LanceDB Distributed, ``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 Distributed 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 + source_version=source_version, full=full ) async def refresh_async( - self, *, source_version: Optional[int] = None + self, *, full: bool = False, source_version: Optional[int] = None ) -> "AsyncJob[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. - The job may already be complete for a local view. Remote refreshes are - submitted through the SQL service. + The job may already be complete in LanceDB Embedded. In LanceDB + Distributed, refreshes are submitted through the SQL service. Options and + result metrics follow + [refresh][lancedb.materialized_view.AsyncMaterializedView.refresh]. """ from ._lancedb import RefreshMaterializedViewResult return _typed_job( await self._table._inner.refresh_materialized_view_async( - source_version=source_version + source_version=source_version, full=full ), RefreshMaterializedViewResult.from_json, ) @@ -235,18 +248,22 @@ class MaterializedView: return LOOP.run(self._async.definition()) def refresh( - self, *, source_version: Optional[int] = None + self, *, full: bool = False, source_version: Optional[int] = None ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. See [AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh].""" - return LOOP.run(self._async.refresh(source_version=source_version)) + return LOOP.run(self._async.refresh(full=full, source_version=source_version)) def refresh_async( - self, *, source_version: Optional[int] = None + self, *, full: bool = False, source_version: Optional[int] = None ) -> "Job[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. See [AsyncMaterializedView.refresh_async][lancedb.materialized_view.AsyncMaterializedView.refresh_async]. """ - return Job(LOOP.run(self._async.refresh_async(source_version=source_version))) + return Job( + LOOP.run( + self._async.refresh_async(full=full, source_version=source_version) + ) + ) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 26c62925f..3356b363c 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -11,6 +11,7 @@ through a namespace abstraction. from __future__ import annotations import sys +import warnings from typing import Any, Dict, Iterable, List, Optional, Union from uuid import UUID @@ -51,7 +52,14 @@ from lancedb.background_loop import LOOP from lancedb.arrow import AsyncRecordBatchReader from lancedb.db import AsyncConnection, DBConnection from lancedb.job import AsyncJob, Job -from lancedb.listing import AsyncListing, Listing +from lancedb.listing import ( + AsyncListing, + AsyncNamespaceListing, + AsyncTableListing, + Listing, + NamespaceListing, + TableListing, +) from lancedb.sql import AsyncQuery as AsyncSqlQuery from lancedb.sql import QueryDescription, QueryParameters from lance_namespace import ( @@ -60,8 +68,6 @@ from lance_namespace import ( CreateNamespaceResponse, DescribeNamespaceResponse, DropNamespaceResponse, - ListNamespacesResponse, - ListTablesResponse, NamespaceExistsRequest, TableExistsRequest, ) @@ -82,6 +88,31 @@ from ._lancedb import Session _MAX_QUERY_K = 2**31 - 1 +def _create_table_storage_options( + storage_options: Optional[Dict[str, str]], + data_storage_version: Optional[str], + enable_v2_manifest_paths: Optional[bool], +) -> Optional[Dict[str, str]]: + if data_storage_version is None and enable_v2_manifest_paths is None: + return storage_options + options = dict(storage_options or {}) + for name, value in ( + ("data_storage_version", data_storage_version), + ("enable_v2_manifest_paths", enable_v2_manifest_paths), + ): + if value is not None: + warnings.warn( + f"setting {name} directly on create_table is deprecated. " + "Use storage_options instead.", + DeprecationWarning, + stacklevel=3, + ) + options[f"new_table_{name}"] = ( + str(value).lower() if isinstance(value, bool) else value + ) + return options + + def _query_to_namespace_request( table_id: List[str], query: "Query", @@ -587,6 +618,9 @@ class LanceNamespaceDBConnection(DBConnection): if mode.lower() not in ["create", "overwrite"]: raise ValueError("mode must be either 'create' or 'overwrite'") validate_table_name(name) + storage_options = _create_table_storage_options( + storage_options, data_storage_version, enable_v2_manifest_paths + ) async_table = LOOP.run( self._inner.create_table( name, @@ -665,6 +699,8 @@ class LanceNamespaceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> "MaterializedView": """Define a materialized view over a table in the root namespace. See @@ -680,6 +716,8 @@ class LanceNamespaceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ).name ) @@ -695,6 +733,8 @@ class LanceNamespaceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: job = LOOP.run( self._inner.create_materialized_view_async( @@ -704,6 +744,8 @@ class LanceNamespaceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ) return Job(job) @@ -817,7 +859,7 @@ class LanceNamespaceDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> NamespaceListing: """ List child namespaces under the given namespace. @@ -834,12 +876,12 @@ class LanceNamespaceDBConnection(DBConnection): Returns ------- - ListNamespacesResponse + NamespaceListing Response containing namespace names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return NamespaceListing( self._inner.list_namespaces( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -986,7 +1028,7 @@ class LanceNamespaceDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: + ) -> TableListing: """ List all tables in this database with pagination support. @@ -1003,12 +1045,12 @@ class LanceNamespaceDBConnection(DBConnection): Returns ------- - ListTablesResponse + TableListing Response containing table names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return TableListing( self._inner.list_tables( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -1222,6 +1264,9 @@ class AsyncLanceNamespaceDBConnection: if mode.lower() not in ["create", "overwrite"]: raise ValueError("mode must be either 'create' or 'overwrite'") validate_table_name(name) + storage_options = _create_table_storage_options( + storage_options, data_storage_version, enable_v2_manifest_paths + ) table = await self._inner.create_table( name, data, @@ -1288,6 +1333,8 @@ class AsyncLanceNamespaceDBConnection: where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> "AsyncMaterializedView": """Define a materialized view over a table in the root namespace.""" view = await self._inner.create_materialized_view( @@ -1297,6 +1344,8 @@ class AsyncLanceNamespaceDBConnection: where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) # Reopen through the namespace so the view's table carries the # namespace client and pushdown configuration a bare inner table lacks. @@ -1311,6 +1360,8 @@ class AsyncLanceNamespaceDBConnection: where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job.""" return await self._inner.create_materialized_view_async( @@ -1320,6 +1371,8 @@ class AsyncLanceNamespaceDBConnection: where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) async def open_materialized_view(self, name: str) -> "AsyncMaterializedView": @@ -1411,12 +1464,12 @@ class AsyncLanceNamespaceDBConnection: namespace_path = [] await self._inner.drop_all_tables(namespace_path=namespace_path) - async def list_namespaces( + def list_namespaces( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> AsyncNamespaceListing: """ List child namespaces under the given namespace. @@ -1433,12 +1486,12 @@ class AsyncLanceNamespaceDBConnection: Returns ------- - ListNamespacesResponse + NamespaceListing Response containing namespace names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return await self._inner.list_namespaces( + return self._inner.list_namespaces( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -1568,12 +1621,12 @@ class AsyncLanceNamespaceDBConnection: except TableNotFoundError: return False - async def list_tables( + def list_tables( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: + ) -> AsyncTableListing: """ List all tables in this database with pagination support. @@ -1590,12 +1643,12 @@ class AsyncLanceNamespaceDBConnection: Returns ------- - ListTablesResponse + TableListing Response containing table names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return await self._inner.list_tables( + return self._inner.list_tables( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -1622,7 +1675,7 @@ class AsyncLanceNamespaceDBConnection: ) -> AsyncSqlQuery: """Start executing SQL when supported by the underlying connection. - Namespace-backed local connections do not support SQL. + Namespace-backed LanceDB Embedded connections do not support SQL. """ return await self._inner.execute_query_async( query, @@ -1630,7 +1683,7 @@ class AsyncLanceNamespaceDBConnection: parameters=parameters, ) - async def describe_query(self, query_id: UUID) -> QueryDescription: + async def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription: """Describe a submitted SQL query when supported.""" return await self._inner.describe_query(query_id) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index 103ec0aa4..b70c96979 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -169,6 +169,50 @@ class PermutationBuilder: ) return self + def bootstrap_sample( + self, + num_samples: int, + *, + ratios: Optional[list[float]] = None, + counts: Optional[list[int]] = None, + fixed: Optional[int] = None, + seed: Optional[int] = None, + split_names: Optional[list[str]] = None, + ) -> "PermutationBuilder": + """ + Sample rows uniformly **with replacement**, independently per split. + + Unlike the other split strategies, the number of output rows is + ``num_samples``, not the number of (optionally filtered) input rows: the + same row can appear zero, one, or many times, and ``num_samples`` may be + larger or smaller than the input row count. Useful for bootstrap + resampling, oversampling rare classes, or any training workload that + wants a fixed-size stream of random draws rather than a single + deterministic pass over every row. Combine with :meth:`filter` to + restrict the eligible population. + + One of ratios, counts, or fixed must be provided, with the same meaning + as in :meth:`split_random`, except they divide ``num_samples`` across + splits rather than the input row count: if fixed is 4, each split gets + ``num_samples // 4`` samples. + + Each split draws its own sample using a seed derived independently from + ``(seed, split_index)``, so a split's content does not change if the samples are + later redistributed across a different number of splits. + + The optional split_names can be provided to name the splits. If not provided, + the splits can only be referenced by their index. + """ + self._async.bootstrap_sample( + num_samples, + ratios=ratios, + counts=counts, + fixed=fixed, + seed=seed, + split_names=split_names, + ) + return self + def split_calculated( self, calculation: str, split_names: Optional[list[str]] = None ) -> "PermutationBuilder": @@ -504,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 local and remote LanceDB connections: + A factory is optional for normal LanceDB Embedded and Distributed 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 @@ -543,7 +587,7 @@ class Permutation: {"root": "/data/lance_db"}, ) - LanceDB Cloud, reading credentials from env vars at worker startup + LanceDB Enterprise, reading credentials from env vars at worker startup so secrets aren't pickled into the dataset:: import os, lancedb @@ -597,7 +641,7 @@ class Permutation: if split is not None: if permutation_table is None: raise ValueError( - "Cannot create a permutation on split `{split}`" + f"Cannot create a permutation on split `{split}`" " because no permutation table is provided" ) if isinstance(split, str): @@ -865,9 +909,11 @@ class Permutation: f"Cannot rename column `{old_name}` to `{new_name}` because a column " "with that name already exists" ) - new_selection = self.selection.copy() - new_selection[new_name] = new_selection[old_name] - del new_selection[old_name] + # Rebuild the mapping so the renamed column keeps its position + new_selection = { + (new_name if name == old_name else name): value + for name, value in self.selection.items() + } return self._with_selection(new_selection) def rename_columns(self, column_map: dict[str, str]) -> "Permutation": diff --git a/python/python/lancedb/pydantic.py b/python/python/lancedb/pydantic.py index 313c514c3..d2b5cb22d 100644 --- a/python/python/lancedb/pydantic.py +++ b/python/python/lancedb/pydantic.py @@ -127,7 +127,11 @@ def Vector( core_schema.list_schema( min_length=dim, max_length=dim, - items_schema=core_schema.float_schema(), + items_schema=( + core_schema.int_schema() + if pa.types.is_integer(value_type) + else core_schema.float_schema() + ), ), ) @@ -208,7 +212,11 @@ def MultiVector( items_schema=core_schema.list_schema( min_length=dim, max_length=dim, - items_schema=core_schema.float_schema(), + items_schema=( + core_schema.int_schema() + if pa.types.is_integer(value_type) + else core_schema.float_schema() + ), ), ), ) @@ -251,6 +259,15 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType: f"{py_type}. Specify the element type, e.g. List[int] instead " "of a bare List." ) + # An Arrow list has a single element type, so a tuple such as + # Tuple[int, str] cannot be stored as one. Tuple[int, ...] is homogeneous. + element_types = {arg for arg in args if arg is not Ellipsis} + if len(element_types) > 1: + raise TypeError( + "Converting Pydantic type to Arrow Type: unsupported type " + f"{py_type}. All tuple elements must have the same type; use a " + "nested LanceModel for a fixed set of fields with different types." + ) child = args[0] return _pydantic_list_child_to_arrow(child, field) raise TypeError( @@ -260,7 +277,9 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType: def _pydantic_model_to_fields(model: pydantic.BaseModel) -> List[pa.Field]: return [ - _pydantic_to_field(name, field) for name, field in model.model_fields.items() + _pydantic_to_field(name, field) + for name, field in model.model_fields.items() + if field.exclude is not True ] @@ -409,6 +428,15 @@ def pydantic_to_schema(model: Type[pydantic.BaseModel]) -> pa.Schema: pyarrow.Schema The Arrow Schema + Raises + ------ + TypeError + If a field has a type with no Arrow equivalent. A ``Tuple`` field becomes + 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. + Examples -------- @@ -493,6 +521,9 @@ class LanceModel(pydantic.BaseModel): vec_and_function = [] for name, field_info in cls.safe_get_fields().items(): + if field_info.exclude is True: + continue + func = get_extras(field_info, "vector_column_for") if func is not None: vec_and_function.append([name, func]) @@ -500,6 +531,8 @@ class LanceModel(pydantic.BaseModel): configs = [] for vec, func in vec_and_function: for source, field_info in cls.safe_get_fields().items(): + if field_info.exclude is True: + continue src_func = get_extras(field_info, "source_column_for") if src_func is func: # note we can't use == here since the function is a pydantic @@ -524,4 +557,20 @@ 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 model.model_dump() + return _enum_members_to_values(model.model_dump()) + + +def _enum_members_to_values(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 + if isinstance(value, dict): + return {k: _enum_members_to_values(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 value diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index c427820e8..c9ca258e7 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -82,6 +82,7 @@ if TYPE_CHECKING: T = TypeVar("T", bound="LanceModel") AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"] +_SYNC_VECTOR_QUERY_TYPES = (list, tuple, np.ndarray, pa.Array, pa.ChunkedArray) # Number of rows a hybrid query returns when no limit was set on it. This # mirrors the default the Rust query builder applies to its sub-queries. @@ -103,11 +104,13 @@ class _LanceScanner(Protocol): def _unsupported_blob_pandas_error(reason: str) -> RuntimeError: + reason = reason.rstrip(".") + reason = reason[0].upper() + reason[1:] return RuntimeError( - "blob columns require Lance native scanner conversion for query " - f"to_pandas(), but {reason}. Use a plain scan query, pass " - "blob_mode='bytes' or blob_mode='descriptions', or remove blob columns " - "from the projection." + "Blob columns require Lance native scanner conversion for this query's " + f"to_pandas(). {reason}. For supported blob v2 queries, pass " + "blob_mode='bytes' or blob_mode='descriptions'. Otherwise, install " + "pylance for scanner conversion or remove blob columns from the projection." ) @@ -122,7 +125,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. Remote tables and namespace QueryTable pushdown " + "stable table snapshot. LanceDB Distributed and namespace QueryTable pushdown " "run the query on a server, so the blob fetch could read another table " "version. Use blob_mode='descriptions'." ) @@ -442,6 +445,7 @@ class FullTextQueryType(str, Enum): MATCH_PHRASE = "match_phrase" BOOST = "boost" MULTI_MATCH = "multi_match" + COMBINED_FIELDS = "combined_fields" BOOLEAN = "boolean" @@ -590,8 +594,8 @@ class PhraseQuery(FullTextQuery): ---------- query : str The query string to match against. - column : str - The name of the column to match against. + column : str, optional + The column to match against. None leaves column selection to query planning. slop : int, default 0 The maximum number of intervening positions permitted in the phrase. document_granularity : DocumentGranularity, optional @@ -601,7 +605,7 @@ class PhraseQuery(FullTextQuery): """ query: str - column: str + column: Optional[str] = None slop: int = pydantic.Field(0, kw_only=True) document_granularity: Optional[DocumentGranularity] = pydantic.Field( None, kw_only=True @@ -666,6 +670,42 @@ class MultiMatchQuery(FullTextQuery): return FullTextQueryType.MULTI_MATCH +@pydantic.dataclasses.dataclass +class CombinedFieldsQuery(FullTextQuery): + """ + Combined-fields (BM25F) query for full-text search. + + Unlike `MultiMatchQuery`, which scores each column on its own and keeps + the best one, this query treats the columns as a single virtual field, so + term statistics are blended across them. A query term can then match in + any of the columns, e.g. a first name in one column and a last name in + another. + + Parameters + ---------- + query : str + The query string to match against. + columns : list[str] + The columns combined into the virtual field. Every column must have the + same tokenizer configuration, and at least one must have an FTS index. + boosts : list[float], optional + The weight of each column, aligned with `columns`. Each weight must be + at least 1. If not provided, every column has a weight of 1. + operator : FullTextOperator, default OR + The operator to use for combining the query terms. + If `AND`, every term must appear in at least one of the columns. + If `OR`, at least one term must match. + """ + + query: str + columns: list[str] + boosts: Optional[list[float]] = pydantic.Field(None, kw_only=True) + operator: FullTextOperator = pydantic.Field(FullTextOperator.OR, kw_only=True) + + def query_type(self) -> FullTextQueryType: + return FullTextQueryType.COMBINED_FIELDS + + @pydantic.dataclasses.dataclass class BooleanQuery(FullTextQuery): """ @@ -909,6 +949,8 @@ class Query(pydantic.BaseModel): query.filter = req.filter query.full_text_query = req.full_text_search query.columns = req.select + # Keep the unset value for this opt-in flag, as in the sync builders. + query.fast_search = req.fast_search or None query.with_row_id = req.with_row_id # use_rte is a genuine tri-state (None / True / False); preserve it as-is # so a round-tripped query keeps an explicit False. @@ -1024,10 +1066,12 @@ class LanceQueryBuilder(ABC): fast_search=fast_search, ) - if isinstance(query, list): + if isinstance(query, (list, tuple)): query = np.array(query, dtype=np.float32) elif isinstance(query, np.ndarray): query = query.astype(np.float32) + elif isinstance(query, (pa.Array, pa.ChunkedArray)): + query = np.array(query.to_pylist(), dtype=np.float32) else: raise TypeError(f"Unsupported query type: {type(query)}") @@ -1049,7 +1093,7 @@ class LanceQueryBuilder(ABC): query = cls._query_to_vector(table, query, vector_column_name) return query, query_type elif query_type == "auto": - if isinstance(query, (list, np.ndarray)): + if isinstance(query, _SYNC_VECTOR_QUERY_TYPES): return query, "vector" else: conf = table.embedding_functions.get(vector_column_name) @@ -1065,7 +1109,7 @@ class LanceQueryBuilder(ABC): @classmethod def _query_to_vector(cls, table, query, vector_column_name): - if isinstance(query, (list, np.ndarray)): + if isinstance(query, _SYNC_VECTOR_QUERY_TYPES): return query conf = table.embedding_functions.get(vector_column_name) if conf is not None: @@ -1134,12 +1178,14 @@ class LanceQueryBuilder(ABC): The maximum time to wait for the query to complete. If None, wait indefinitely. blob_mode: str, default "lazy" - Controls how blob columns are returned. Eligible local plain scans - use Lance's scanner, which returns lazy blob handles in ``"lazy"`` - mode and also supports legacy blob columns. Other local blob v2 + Controls how blob columns are returned. Local blob v2 queries support + ``"bytes"`` and ``"descriptions"`` without pylance. Eligible local + plain scans use pylance's scanner for lazy blob handles in ``"lazy"`` + mode and for legacy blob columns. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - Remote blob queries support only ``"descriptions"`` until a stable + LanceDB Distributed blob queries support only ``"descriptions"`` until a + stable table snapshot can bind the query and blob fetches. **kwargs Forwarded to pyarrow.Table.to_pandas after query execution and @@ -1214,15 +1260,16 @@ class LanceQueryBuilder(ABC): batch_size: Optional[int] = None, *, timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", ) -> pa.RecordBatchReader: """ Execute the query and return the results as a pyarrow [RecordBatchReader](https://arrow.apache.org/docs/python/generated/pyarrow.RecordBatchReader.html) - For v2 blob projections, ``to_batches`` keeps the auto ``_rowid`` - column visible so batch consumers can call ``fetch_blobs``. Use - ``to_arrow``, ``to_list``, or ``to_pandas`` if you want LanceDB to hide - auto row ids in the final collected result. + For v2 blob projections, the default ``blob_mode="lazy"`` keeps the + auto ``_rowid`` column visible so batch consumers can call + ``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide + automatic row ids. Parameters ---------- @@ -1231,6 +1278,16 @@ class LanceQueryBuilder(ABC): timeout: Optional[timedelta] The maximum time to wait for the query to complete. If None, wait indefinitely. + blob_mode: str, default "lazy" + ``"lazy"`` keeps blob descriptors and auto row ids for manual fetches. + ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2 + payloads one batch at a time, without requiring pylance. Bytes mode + has the same restrictions as :meth:`to_arrow`. + + Examples + -------- + Stream blob payloads with ``query.to_batches(blob_mode="bytes")`` and + convert each batch separately with ``batch.to_pandas()``. """ raise NotImplementedError @@ -1494,6 +1551,28 @@ class LanceQueryBuilder(ABC): finalized = finalized.drop_columns(["_rowid"]) return finalized + def _batches_in_mode( + self, + reader: pa.RecordBatchReader, + blob_mode: BlobMode, + blob_sources: dict[str, str], + ) -> pa.RecordBatchReader: + if blob_mode == "lazy": + return reader + + def convert(tbl: pa.Table) -> pa.Table: + return self._finalize_blob_query_table( + tbl, blob_mode=blob_mode, blob_sources=blob_sources + ) + + schema = convert(pa.Table.from_batches([], schema=reader.schema)).schema + + def batches(): + for batch in reader: + yield from convert(pa.Table.from_batches([batch])).to_batches() + + return pa.RecordBatchReader.from_batches(schema, batches()) + def with_row_address(self, with_row_address: bool = True) -> Self: """Set whether to return row addresses. @@ -1558,9 +1637,10 @@ class LanceQueryBuilder(ABC): ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance] GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL - SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] + SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 - LanceRead: uri=..., projection=[vector], ... + LanceRead: uri=..., projection=[vector], num_fragments=..., ... + Parameters ---------- @@ -1616,8 +1696,8 @@ class LanceQueryBuilder(ABC): GlobalLimitExec: elapsed=..., skip=0, fetch=10, metrics=[output_rows=..., elapsed_compute=..., output_bytes=...] FilterExec: elapsed=..., _distance@2 IS NOT NULL, metrics=[...] - SortExec: elapsed=..., TopK(fetch=10), expr=[...], - preserve_partitioning=[...], + SortExec: elapsed=..., TopK(fetch=1), expr=[...], + preserve_partitioning=[...], filter=[...], metrics=[output_rows=..., elapsed_compute=..., output_bytes=..., row_replacements=...] KNNVectorDistance: elapsed=..., metric=l2, @@ -1630,6 +1710,7 @@ class LanceQueryBuilder(ABC): metrics=[output_rows=..., elapsed_compute=..., output_bytes=..., fragments_scanned=..., ranges_scanned=1, rows_scanned=1, bytes_read=..., iops=..., requests=..., task_wait_time=...] + Parameters ---------- @@ -1648,12 +1729,12 @@ class LanceQueryBuilder(ABC): self.to_query_object(), distributed_metrics=distributed_metrics ) - def vector(self, vector: Union[np.ndarray, list]) -> Self: + def vector(self, vector: Union[VEC, Tuple]) -> Self: """Set the vector to search for. Parameters ---------- - vector: np.ndarray or list + vector: list, tuple, np.ndarray, pa.Array, or pa.ChunkedArray The vector to search for. Returns @@ -1710,7 +1791,18 @@ class LanceQueryBuilder(ABC): get_uri_scheme(self._table._dataset_path) == "memory" ): return None - dataset = self._table.to_lance() + # Blob v2 payloads and descriptions use LanceDB's native fetch path. + # Only lazy handles, legacy blobs, and scanner-only options need pylance. + if ( + blob_mode != "lazy" + and not _query_needs_lance_scanner(self) + and blob_v2_projection_sources(self._table.schema, query.columns) + ): + return None + try: + dataset = self._table.to_lance() + except ImportError as err: + raise _unsupported_blob_pandas_error(str(err)) from err blob_auto_row_id = self._blob_auto_row_id_enabled() blob_sources = ( blob_v2_projection_sources(self._table.schema, query.columns) @@ -2069,6 +2161,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): batch_size: Optional[int] = None, *, timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", ) -> pa.RecordBatchReader: """ Execute the query and return the result as a RecordBatchReader object. @@ -2080,11 +2173,15 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): timeout: timedelta, default None The maximum time to wait for the query to complete. If None, wait indefinitely. + blob_mode: str, default "lazy" + Controls blob conversion as described in + :meth:`LanceQueryBuilder.to_batches`. Returns ------- pa.RecordBatchReader """ + blob_sources = self._validated_blob_sources(blob_mode) vector = self._query if isinstance(self._query, list) else self._query.tolist() if isinstance(vector[0], np.ndarray): vector = [v.tolist() for v in vector] @@ -2101,7 +2198,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): result_set.schema, result_set.to_batches() ) - return result_set + return self._batches_in_mode(result_set, blob_mode, blob_sources) def where( self, where: Union[str, Expr], prefilter: bool = None @@ -2316,7 +2413,12 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): ) def to_batches( - self, /, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None + self, + /, + batch_size: Optional[int] = None, + timeout: Optional[timedelta] = None, + *, + blob_mode: BlobMode = "lazy", ): raise NotImplementedError("to_batches on an FTS query") @@ -2372,10 +2474,19 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): return self._table._output_schema(query) def to_batches( - self, /, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None + self, + /, + batch_size: Optional[int] = None, + timeout: Optional[timedelta] = None, + *, + blob_mode: BlobMode = "lazy", ) -> pa.RecordBatchReader: + blob_sources = self._validated_blob_sources(blob_mode) query = self._query_for_scan() - return self._table._execute_query(query, batch_size=batch_size, timeout=timeout) + reader = self._table._execute_query( + query, batch_size=batch_size, timeout=timeout + ) + return self._batches_in_mode(reader, blob_mode, blob_sources) def rerank(self, reranker: Reranker) -> LanceEmptyQueryBuilder: """Rerank the results using the specified reranker. @@ -2438,12 +2549,20 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): if query is not None and (vector is not None or text is not None): raise ValueError( "You can either provide a string query in search() method " - "or set `vector()` and `text()` explicitly for hybrid search." + "or set `vector()` and `text()` explicitly for hybrid search. " "But not both." ) vector_query = vector if vector is not None else query - if not isinstance(vector_query, (str, list, np.ndarray)): + # Accept the same containers as the vector search path, which + # normalizes them in `LanceQueryBuilder.create`. + if isinstance(vector_query, (list, tuple)): + vector_query = np.array(vector_query, dtype=np.float32) + elif isinstance(vector_query, np.ndarray): + vector_query = vector_query.astype(np.float32) + elif isinstance(vector_query, (pa.Array, pa.ChunkedArray)): + vector_query = np.array(vector_query.to_pylist(), dtype=np.float32) + elif not isinstance(vector_query, str): raise ValueError("Vector query must be either a string or a vector") text_query = text or query @@ -2572,10 +2691,6 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): with_row_ids: bool, offset: Optional[int] = None, ) -> pa.Table: - if norm == "rank": - vector_results = LanceHybridQueryBuilder._rank(vector_results, "_distance") - fts_results = LanceHybridQueryBuilder._rank(fts_results, "_score") - # If both result sets are empty (e.g. after hard filtering), # return early to avoid errors in reranking or score restoration. if vector_results.num_rows == 0 and fts_results.num_rows == 0: @@ -2602,15 +2717,23 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): original_score_row_ids = None # normalize the scores to be between 0 and 1, 0 being most relevant # We check whether the results (vector and FTS) are empty, because when - # they are, they often are missing the _rowid column, which causes an error + # they are, they often are missing the _rowid column, which causes an error. + # The original values are captured before any rank conversion so that + # they can be restored after reranking. if vector_results.num_rows > 0: distance_i = vector_results.column_names.index("_distance") original_distances = vector_results.column(distance_i) original_distance_row_ids = vector_results.column("_rowid") + if norm == "rank": + vector_results = LanceHybridQueryBuilder._rank( + vector_results, "_distance" + ) vector_results = vector_results.set_column( distance_i, vector_results.field(distance_i), - LanceHybridQueryBuilder._normalize_scores(original_distances), + LanceHybridQueryBuilder._normalize_scores( + vector_results.column(distance_i) + ), ) # In fts higher scores represent relevance. Not inverting them here as @@ -2619,10 +2742,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): score_i = fts_results.column_names.index("_score") original_scores = fts_results.column(score_i) original_score_row_ids = fts_results.column("_rowid") + if norm == "rank": + fts_results = LanceHybridQueryBuilder._rank(fts_results, "_score") fts_results = fts_results.set_column( score_i, fts_results.field(score_i), - LanceHybridQueryBuilder._normalize_scores(original_scores), + LanceHybridQueryBuilder._normalize_scores(fts_results.column(score_i)), ) results = reranker.rerank_hybrid(fts_query, vector_results, fts_results) @@ -2655,7 +2780,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): return results def to_batches( - self, /, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None + self, + /, + batch_size: Optional[int] = None, + timeout: Optional[timedelta] = None, + *, + blob_mode: BlobMode = "lazy", ): raise NotImplementedError("to_batches not yet supported on a hybrid query") @@ -2910,7 +3040,19 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): self._refine_factor = refine_factor return self - def vector(self, vector: Union[np.ndarray, list]) -> LanceHybridQueryBuilder: + def vector(self, vector: Union[VEC, Tuple]) -> LanceHybridQueryBuilder: + """Set the vector to search for. + + Parameters + ---------- + vector: list, tuple, np.ndarray, pa.Array, or pa.ChunkedArray + The vector to search for. + + Returns + ------- + LanceHybridQueryBuilder + The LanceHybridQueryBuilder object. + """ self._vector = vector return self @@ -2950,9 +3092,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance] GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL - SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] + SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 - LanceRead: uri=..., projection=[vector], ... + LanceRead: uri=..., projection=[vector], num_fragments=..., ... + Parameters ---------- @@ -3050,7 +3193,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): if columns: self._vector_query.select(columns) self._fts_query.select(columns) - if self._where: + # An Expr has no truth value (it raises on bool()), so test for it + # explicitly instead of relying on truthiness; an empty SQL string is + # still skipped. + if isinstance(self._where, Expr) or self._where: self._vector_query.where(self._where, not self._postfilter) self._fts_query.where(self._where, not self._postfilter) # WAL-PK-FUSION: without the fallback, `if self._with_row_id:`. @@ -3242,6 +3388,7 @@ class AsyncQueryBase(object): *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", ) -> AsyncRecordBatchReader: """ Execute the query and return the results as an Apache Arrow RecordBatchReader. @@ -3258,7 +3405,47 @@ 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. + blob_mode: str, default "lazy" + ``"lazy"`` keeps blob descriptors and auto row ids for manual fetches. + ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2 + payloads one batch at a time, without requiring pylance. Bytes mode + has the same restrictions as :meth:`to_arrow`. + + Examples + -------- + Use ``async for batch in await query.to_batches(blob_mode="bytes")`` + to stream blob payloads and convert each batch with ``batch.to_pandas()``. """ + blob_sources = await self._validated_blob_sources(blob_mode) + reader = await self._execute_batches( + max_batch_length=max_batch_length, timeout=timeout + ) + if blob_mode == "lazy": + return reader + + async def convert(tbl: pa.Table) -> pa.Table: + tbl = self._finalize_blob_query_table(tbl) + tbl = await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources) + if not self._user_requested_row_id() and "_rowid" in tbl.column_names: + tbl = tbl.drop_columns(["_rowid"]) + return tbl + + schema = (await convert(pa.Table.from_batches([], schema=reader.schema))).schema + + async def batches(): + async for batch in reader: + tbl = await convert(pa.Table.from_batches([batch])) + for converted in tbl.to_batches(): + yield converted + + return AsyncRecordBatchReader._from_batches(schema, batches()) + + async def _execute_batches( + self, + *, + max_batch_length: Optional[int] = None, + timeout: Optional[timedelta] = None, + ) -> AsyncRecordBatchReader: await self._maybe_add_blob_row_id() return AsyncRecordBatchReader( await self._inner.execute( @@ -3334,7 +3521,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. - Remote tables and namespace query pushdown refuse ``"bytes"``. + LanceDB Distributed and namespace query pushdown refuse ``"bytes"``. """ blob_sources = await self._validated_blob_sources(blob_mode) batch_iter = await self.to_batches(timeout=timeout) @@ -3407,12 +3594,14 @@ class AsyncQueryBase(object): If not specified, no timeout is applied. If the query does not complete within the specified time, an error will be raised. blob_mode: str, default "lazy" - Controls how blob columns are returned. Eligible local plain scans - use Lance's scanner, which returns lazy blob handles in ``"lazy"`` - mode and also supports legacy blob columns. Other local blob v2 + Controls how blob columns are returned. Local blob v2 queries support + ``"bytes"`` and ``"descriptions"`` without pylance. Eligible local + plain scans use pylance's scanner for lazy blob handles in ``"lazy"`` + mode and for legacy blob columns. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - Remote blob queries support only ``"descriptions"`` until a stable + LanceDB Distributed blob queries support only ``"descriptions"`` until a + stable table snapshot can bind the query and blob fetches. **kwargs Forwarded to pyarrow.Table.to_pandas after query execution and @@ -3499,7 +3688,16 @@ class AsyncQueryBase(object): get_uri_scheme(await self._table.uri()) == "memory" ): return None - dataset = await self._table.to_lance() + if ( + blob_mode != "lazy" + and not _query_needs_lance_scanner(self) + and blob_v2_projection_sources(schema, query.columns) + ): + return None + try: + dataset = await self._table.to_lance() + except ImportError as err: + raise _unsupported_blob_pandas_error(str(err)) from err scanner = dataset.scanner( **_scanner_kwargs_for_query( query, @@ -3592,9 +3790,10 @@ class AsyncQueryBase(object): ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance] GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL - SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] + SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 - LanceRead: uri=..., projection=[vector], ... + LanceRead: uri=..., projection=[vector], num_fragments=..., ... + Parameters @@ -3998,13 +4197,13 @@ class AsyncFTSQuery(AsyncStandardQuery): self._table, ) - async def to_batches( + async def _execute_batches( self, *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, ) -> AsyncRecordBatchReader: - reader = await super().to_batches(timeout=timeout) + reader = await super()._execute_batches(timeout=timeout) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: results = self._reranker.rerank_fts(self.get_query(), results) @@ -4049,9 +4248,10 @@ class AsyncVectorQueryBase: your actual data to find the smallest possible value that will still give you the desired recall. - LanceDB retains this as `nprobes` through local and remote request - construction. Lance sets both probe bounds to this value. Explicit minimum - or maximum settings can override their respective bounds. + LanceDB retains this as `nprobes` through LanceDB Embedded and LanceDB + Distributed request construction. Lance sets both probe bounds to this + value. Explicit minimum or maximum settings can override their respective + bounds. """ self._inner.nprobes(nprobes) return self @@ -4289,13 +4489,13 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): self._inner.nearest_to_text({"query": query}), self._table ) - async def to_batches( + async def _execute_batches( self, *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, ) -> AsyncRecordBatchReader: - reader = await super().to_batches(timeout=timeout) + reader = await super()._execute_batches(timeout=timeout) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: results = self._reranker.rerank_vector(self._query_string, results) @@ -4418,7 +4618,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): return fts_query, vec_query, limit, offset - async def to_batches( + async def _execute_batches( self, *, max_batch_length: Optional[int] = None, @@ -4512,9 +4712,9 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): LanceRead: uri=..., projection=[text], source=stream(_rowid) GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL - SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] + SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 - LanceRead: uri=..., projection=[vector], ... + LanceRead: uri=..., projection=[vector], num_fragments=..., ... ProjectionExec: expr=[vector@2 as vector, text@3 as text, _score@1 as _score, _rowid@0 as _rowid] LanceRead: uri=..., projection=[vector, text], source=stream(_rowid) GlobalLimitExec: skip=0, fetch=10 @@ -4688,6 +4888,7 @@ class BaseQueryBuilder(object): *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", ) -> pa.RecordBatchReader: """ Execute the query and return the results as an Apache Arrow RecordBatchReader. @@ -4704,9 +4905,14 @@ 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. + blob_mode: str, default "lazy" + Controls blob conversion as described in + :meth:`AsyncQueryBase.to_batches`. """ async_reader = LOOP.run( - self._inner.to_batches(max_batch_length=max_batch_length, timeout=timeout) + self._inner.to_batches( + max_batch_length=max_batch_length, timeout=timeout, blob_mode=blob_mode + ) ) def iter_sync(): @@ -4868,9 +5074,10 @@ class BaseQueryBuilder(object): ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance] GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL - SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] + SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 - LanceRead: uri=..., projection=[vector], ... + LanceRead: uri=..., projection=[vector], num_fragments=..., ... + Parameters diff --git a/python/python/lancedb/remote/__init__.py b/python/python/lancedb/remote/__init__.py index a1c8ebee5..4d082d2c8 100644 --- a/python/python/lancedb/remote/__init__.py +++ b/python/python/lancedb/remote/__init__.py @@ -52,7 +52,10 @@ class TimeoutConfig: `LANCE_CLIENT_CONNECT_TIMEOUT`, as an integer number of seconds. read_timeout: Optional[timedelta] The timeout for reading data from the server. Default is 300 seconds - (5 minutes). This can also be set via the environment variable + (5 minutes). This also applies while waiting for response headers during + an upload. Increase it for large or slowly produced inputs to + `create_table`, even if data is still being uploaded. This can also be + set via the environment variable `LANCE_CLIENT_READ_TIMEOUT`, as an integer number of seconds. pool_idle_timeout: Optional[timedelta] The timeout for keeping idle connections in the connection pool. Default @@ -121,7 +124,7 @@ class RetryConfig: `LANCE_CLIENT_RETRY_BACKOFF_JITTER`. statuses: Optional[List[int] The HTTP status codes for which to retry the request. Default is - [429, 500, 502, 503]. + [409, 429, 500, 502, 503, 504]. You can also set this via the environment variable `LANCE_CLIENT_RETRY_STATUSES`. Use a comma-separated list of integers. @@ -160,7 +163,7 @@ class TlsConfig: @dataclass class ClientConfig: - """Configuration for the LanceDB Cloud HTTP client. + """Configuration for the HTTP client used to connect to LanceDB Enterprise. Attributes ---------- @@ -187,7 +190,7 @@ class ClientConfig: Provider for dynamic headers to be added to each request. user_id: Optional[str] User identifier for tracking purposes. This is sent as the - `x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise. + `x-lancedb-user-id` header in requests to LanceDB Enterprise. This can also be set via the `LANCEDB_USER_ID` environment variable. Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index ac6b8b99d..d97e6526b 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -7,7 +7,6 @@ from __future__ import annotations from dataclasses import replace from datetime import timedelta import json -import logging from concurrent.futures import ThreadPoolExecutor import sys from typing import ( @@ -36,7 +35,7 @@ from lancedb.remote import ClientConfig, RetryConfig, TimeoutConfig, TlsConfig import pyarrow as pa from ..common import DATA -from lancedb.listing import Listing +from lancedb.listing import Listing, NamespaceListing, TableListing from ..db import DBConnection, LOOP from ..functions import FunctionVersion, UdfDefinition from ..job import AsyncJob, Job @@ -47,15 +46,13 @@ from ..secrets import EnvVarSecret, SecretInfo from ..view import ViewDescription if TYPE_CHECKING: - from .._lancedb import JobInfo + from .._lancedb import JobInfo, Session from ..embeddings import EmbeddingFunctionConfig from lance_namespace import ( LanceNamespace, CreateNamespaceResponse, DescribeNamespaceResponse, DropNamespaceResponse, - ListNamespacesResponse, - ListTablesResponse, ) from ..pydantic import LanceModel from ..table import Table @@ -104,7 +101,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 remote connection with a header_provider. " + "Cannot serialize a LanceDB Distributed connection with a header_provider. " "Use static api_key/extra_headers or provide a worker-side " "connection factory instead." ) @@ -122,7 +119,7 @@ def _client_config_to_dict(config: ClientConfig) -> dict[str, Any]: class RemoteDBConnection(DBConnection): - """A connection to a remote LanceDB database.""" + """A connection to a LanceDB Enterprise database.""" def __init__( self, @@ -138,7 +135,7 @@ class RemoteDBConnection(DBConnection): read_consistency_interval: Optional[timedelta] = None, sql_host_override: Optional[str] = None, ): - """Connect to a remote LanceDB database.""" + """Connect to a LanceDB Enterprise database.""" if isinstance(client_config, dict): client_config = ClientConfig(**client_config) elif client_config is None: @@ -242,6 +239,26 @@ class RemoteDBConnection(DBConnection): def __repr__(self) -> str: return f"RemoteConnect(name={self.db_name})" + @property + @override + def uri(self) -> str: + return self._conn.uri + + @property + def session(self) -> Optional["Session"]: + """LanceDB Distributed connections do not expose a local cache session.""" + raise NotImplementedError( + "session is not supported by LanceDB Distributed connections" + ) + + @property + def read_consistency_interval(self) -> Optional[timedelta]: + """LanceDB Distributed connections do not expose a read consistency interval.""" + raise NotImplementedError( + "read_consistency_interval is not supported by LanceDB Distributed " + "connections" + ) + @override def serialize(self) -> str: if getattr(self, "_catalog_oauth", False): @@ -268,7 +285,7 @@ class RemoteDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> NamespaceListing: """List immediate child namespace names in the given namespace. Parameters @@ -284,12 +301,12 @@ class RemoteDBConnection(DBConnection): Returns ------- - ListNamespacesResponse + NamespaceListing Response containing namespace names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return NamespaceListing( self._conn.list_namespaces( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -373,13 +390,43 @@ class RemoteDBConnection(DBConnection): """ return LOOP.run(self._conn.describe_namespace(namespace_path=namespace_path)) + @override + def namespace_exists(self, namespace_id: List[str]) -> bool: + """Check if a namespace exists. + + ``namespace_id`` contains the namespace segments; an empty list represents + root. Returns False only if the namespace is not found. Other errors, + including permission errors, are propagated. + + Examples + -------- + >>> def check_namespace(conn): + ... return conn.namespace_exists(["analytics"]) + """ + return LOOP.run(self._conn.namespace_exists(namespace_id)) + + @override + def table_exists(self, table_id: List[str]) -> bool: + """Check if a table exists. + + ``table_id`` contains the namespace segments followed by the table name. + Returns False only if the table is not found. Other errors, including + permission errors, are propagated. + + Examples + -------- + >>> def check_table(conn): + ... return conn.table_exists(["analytics", "events"]) + """ + return LOOP.run(self._conn.table_exists(table_id)) + @override def list_tables( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: + ) -> TableListing: """List a page of tables in this database. Parameters @@ -396,12 +443,12 @@ class RemoteDBConnection(DBConnection): Returns ------- - ListTablesResponse + TableListing Response containing table names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return TableListing( self._conn.list_tables( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -487,18 +534,14 @@ class RemoteDBConnection(DBConnection): if namespace_path is None: namespace_path = [] - if storage_options is not None: - logging.info( - "storage_options is ignored for remote tables" - " (storage is managed; set storage_options on connect() instead)" + table = LOOP.run( + self._conn.open_table( + name, + namespace_path=namespace_path, + storage_options=storage_options, + index_cache_size=index_cache_size, ) - if index_cache_size is not None: - logging.info( - "index_cache_size is ignored for remote tables" - " (there is no local cache to configure)" - ) - - table = LOOP.run(self._conn.open_table(name, namespace_path=namespace_path)) + ) tbl = RemoteTable( table, self.db_name, @@ -571,13 +614,16 @@ class RemoteDBConnection(DBConnection): name: str, data: DATA = None, schema: Optional[Union[pa.Schema, LanceModel]] = None, - on_bad_vectors: str = "error", - fill_value: float = 0.0, mode: Optional[str] = None, exist_ok: bool = False, + on_bad_vectors: str = "error", + fill_value: float = 0.0, embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None, *, namespace_path: Optional[List[str]] = None, + storage_options: Optional[Dict[str, str]] = None, + data_storage_version: Optional[str] = None, + enable_v2_manifest_paths: Optional[bool] = None, ) -> Table: """Create a [Table][lancedb.table.Table] in the database. @@ -617,6 +663,12 @@ class RemoteDBConnection(DBConnection): embedding_functions: list of EmbeddingFunctionConfig, optional 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. + data_storage_version: str, optional + Not supported in LanceDB Distributed. Raises NotImplementedError. + enable_v2_manifest_paths: bool, optional + Not supported in LanceDB Distributed. Raises NotImplementedError. Returns ------- @@ -683,6 +735,15 @@ class RemoteDBConnection(DBConnection): LanceTable(table4) """ + for option, value in ( + ("data_storage_version", data_storage_version), + ("enable_v2_manifest_paths", enable_v2_manifest_paths), + ): + if value is not None: + raise NotImplementedError( + f"{option} is not supported for table creation in " + "LanceDB Distributed" + ) if exist_ok: if mode == "create": mode = "exist_ok" @@ -704,6 +765,7 @@ class RemoteDBConnection(DBConnection): on_bad_vectors=on_bad_vectors, fill_value=fill_value, embedding_functions=embedding_functions, + storage_options=storage_options, ) ) return RemoteTable( @@ -723,6 +785,8 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: from .table import RemoteTable @@ -734,6 +798,8 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ) return MaterializedView( @@ -755,6 +821,8 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: job = LOOP.run( self._conn.create_materialized_view_async( @@ -764,6 +832,8 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ) return Job(job) @@ -835,6 +905,20 @@ class RemoteDBConnection(DBConnection): job = LOOP.run(self._conn.drop_table_async(name, namespace_path=namespace_path)) return Job(job if isinstance(job, AsyncJob) else AsyncJob(job)) + @override + 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. + """ + LOOP.run(self._conn.drop_all_tables(namespace_path=namespace_path)) + + @override + def drop_database(self): + """Deprecated alias for ``drop_all_tables()``.""" + LOOP.run(self._conn.drop_database()) + @override def rename_table( self, @@ -1095,7 +1179,7 @@ class RemoteDBConnection(DBConnection): default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, ) -> SqlQuery: - """Start executing SQL through this remote connection. + """Start executing SQL through this LanceDB Distributed connection. Unqualified tables use this connection's database and the ``["public"]`` namespace by default. Fully qualified table names may @@ -1114,7 +1198,7 @@ class RemoteDBConnection(DBConnection): ) @override - def describe_query(self, query_id: UUID) -> QueryDescription: + def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription: """Describe a submitted SQL query by its connection-scoped id.""" return LOOP.run( self._conn.describe_query( diff --git a/python/python/lancedb/remote/header.py b/python/python/lancedb/remote/header.py index 206b7a7cb..9cea0eeff 100644 --- a/python/python/lancedb/remote/header.py +++ b/python/python/lancedb/remote/header.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Header providers for LanceDB remote connections. +"""Header providers for LanceDB Enterprise connections. This module provides a flexible header management framework for LanceDB remote connections, allowing users to implement custom header strategies for @@ -141,7 +141,7 @@ class OAuthProvider(HeaderProvider): # Set expiration if provided expires_in = token_data.get("expires_in") - if expires_in: + if expires_in is not None: self._token_expires_at = time.time() + expires_in else: # Token doesn't expire or expiration unknown diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index eec958799..7454b3e73 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -4,9 +4,10 @@ from datetime import timedelta import deprecation import logging -from functools import cached_property +from functools import cached_property, wraps import os from typing import ( + TYPE_CHECKING, Any, Callable, Dict, @@ -41,19 +42,12 @@ from lancedb.index import ( FTS, BTree, Bitmap, - HnswFlat, - HnswPq, - HnswSq, - IvfFlat, - IvfPq, - IvfRq, - IvfSq, LabelList, ) from lancedb.job import Job from lancedb.functions import FunctionApplication, RefreshColumnResult from lancedb.remote.db import LOOP -from lancedb.table import IndexConfigType, KNOWN_METRICS +from lancedb.table import IndexConfigType, _maybe_add_fts_error_note import pyarrow as pa from lancedb.common import DATA, VEC, VECTOR_COLUMN_NAME @@ -68,20 +62,46 @@ from ..query import ( FullTextQuery, LanceQueryBuilder, LanceTakeQueryBuilder, - LanceVectorQueryBuilder, ) from ..table import ( AsyncTable, BlobMode, Branches, + CompactionOptions, IndexStatistics, Query, Table, Tags, ) -from ..types import BaseTokenizerType +from ..types import BaseTokenizerType, ScalarIndexType from ..util import infer_vector_column_name +if TYPE_CHECKING: + import lance + import polars as pl + + +def _deprecated_keyword(old_name: str, new_name: str): + """Keep old remote-only keyword names without changing the Table signature.""" + + def decorate(method): + @wraps(method) + def wrapped(self, *args, **kwargs): + if old_name in kwargs: + if new_name in kwargs: + raise TypeError(f"Cannot specify both {old_name} and {new_name}") + warnings.warn( + f"{old_name} is deprecated; use {new_name} instead", + DeprecationWarning, + stacklevel=2, + ) + kwargs[new_name] = kwargs.pop(old_name) + return method(self, *args, **kwargs) + + return wrapped + + return decorate + class RemoteTable(Table): def __init__( @@ -106,8 +126,8 @@ class RemoteTable(Table): def _serialized_connection_state(self) -> str: if self._connection_state is None: raise RuntimeError( - "Cannot reopen this remote table because it does not carry " - "serialized connection state" + "Cannot reopen this LanceDB Distributed table because it does not " + "carry serialized connection state" ) if callable(self._connection_state): self._connection_state = self._connection_state() @@ -173,6 +193,18 @@ class RemoteTable(Table): """The name of the table""" return self._name + @property + def namespace(self) -> List[str]: + return self._namespace_path + + @deprecation.deprecated( + deprecated_in="0.33.1", + current_version=__version__, + details="Use update_field_metadata() instead.", + ) + def replace_field_metadata(self, field_name: str, new_metadata: Dict[str, str]): + LOOP.run(self._table.replace_field_metadata(field_name, new_metadata)) + def __repr__(self) -> str: return f"RemoteTable({self.db_name}.{self.name})" @@ -241,14 +273,34 @@ 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 for remote tables.""" + """to_arrow() is not supported in LanceDB Distributed.""" validate_blob_mode(blob_mode) - raise NotImplementedError("to_arrow() is not supported for remote tables.") + raise NotImplementedError( + "to_arrow() is not supported in LanceDB Distributed. " + "Use table.search().to_arrow() instead." + ) def to_pandas(self, blob_mode: BlobMode = "lazy", **kwargs): - """to_pandas() is not supported for remote tables.""" + """to_pandas() is not supported in LanceDB Distributed.""" validate_blob_mode(blob_mode) - raise NotImplementedError("to_pandas() is not supported for remote tables.") + raise NotImplementedError( + "to_pandas() is not supported in LanceDB Distributed. " + "Use table.search().to_pandas() instead." + ) + + def to_lance(self, **kwargs) -> "lance.LanceDataset": + """Direct Lance dataset access is not supported in LanceDB Distributed. + + Use ``table.search().to_arrow()`` to read query results through the server. + """ + return LOOP.run(self._table.to_lance(**kwargs)) + + 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. " + "Use table.search().to_polars() instead." + ) def checkout(self, version: Union[int, str]): result = LOOP.run(self._table.checkout(version)) @@ -279,16 +331,21 @@ 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, so the same tokenizer - model files must exist locally. + rebuilt in the client process from index metadata. In LanceDB Distributed, + 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 server's index produces. If the model files are + missing, an error naming the tokenizer is raised. """ return LOOP.run( self._table.tokenize(query, column=column, index_name=index_name) ) - def index_stats(self, index_uuid: str) -> Optional[IndexStatistics]: + @_deprecated_keyword("index_uuid", "index_name") + def index_stats(self, index_name: str) -> Optional[IndexStatistics]: """List all the stats of a specified index""" - return LOOP.run(self._table.index_stats(index_uuid)) + return LOOP.run(self._table.index_stats(index_name)) @deprecation.deprecated( deprecated_in="0.25.0", @@ -298,43 +355,38 @@ class RemoteTable(Table): def create_scalar_index( self, column: str, - index_type: Literal["BTREE", "BITMAP", "LABEL_LIST", "scalar"] = "scalar", *, - replace: bool = False, + replace: bool = True, + index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, ): - """Creates a scalar index. + """Create a scalar index on a column. .. deprecated:: 0.25.0 Use :meth:`create_index` with a BTree, Bitmap, or LabelList config instead. Example: ``table.create_index("column", config=BTree())`` - - Parameters - ---------- - column : str - The column to be indexed. Must be a boolean, integer, float, - or string column. - index_type : str - The index type of the scalar index. Must be "scalar" (BTREE), - "BTREE", "BITMAP", or "LABEL_LIST", - replace : bool - If True, replace the existing index with the new one. """ - if index_type == "scalar" or index_type == "BTREE": + if index_type == "scalar": + warnings.warn( + 'index_type="scalar" is deprecated; use "BTREE" instead', + DeprecationWarning, + stacklevel=2, + ) + index_type = "BTREE" + if index_type == "BTREE": config = BTree() elif index_type == "BITMAP": config = Bitmap() elif index_type == "LABEL_LIST": config = LabelList() else: - raise ValueError(f"Unknown index type: {index_type}") - - LOOP.run( + raise ValueError(f"Unknown index type {index_type}") + return LOOP.run( self._table.create_index( column, - config=config, replace=replace, + config=config, wait_timeout=wait_timeout, name=name, ) @@ -345,12 +397,16 @@ class RemoteTable(Table): current_version=__version__, details="Use create_index() with config=FTS() instead.", ) + @_deprecated_keyword("column", "field_names") def create_fts_index( self, - column: str, + field_names: Union[str, List[str]], *, + ordering_field_names: Optional[Union[str, List[str]]] = None, replace: bool = False, - wait_timeout: Optional[timedelta] = None, + writer_heap_size: Optional[int] = 1024 * 1024 * 1024, + use_tantivy: bool = False, + tokenizer_name: Optional[str] = None, with_position: bool = False, # tokenizer configs: base_tokenizer: BaseTokenizerType = "simple", @@ -366,6 +422,7 @@ class RemoteTable(Table): prefix_only: bool = False, block_size: int = 128, document_granularity: DocumentGranularity = DocumentGranularity.ROW, + wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, ): """Create a full-text search index on a column. @@ -374,31 +431,70 @@ class RemoteTable(Table): Use :meth:`create_index` with an FTS config instead. Example: ``table.create_index("text_column", config=FTS())`` """ + if use_tantivy: + raise ValueError( + "Tantivy-based FTS has been removed. " + "Remove use_tantivy and recreate the index with native FTS." + ) + if ordering_field_names is not None: + raise ValueError( + "ordering_field_names was only supported by the removed " + "Tantivy-based FTS implementation." + ) + if writer_heap_size != 1024 * 1024 * 1024: + raise ValueError( + "writer_heap_size was only supported by the removed " + "Tantivy-based FTS implementation." + ) + if not isinstance(field_names, str): + raise ValueError( + "Native FTS indexes can only be created on a single field " + "at a time. To search over multiple text fields, create a " + "separate FTS index for each field." + ) + + if tokenizer_name is None: + tokenizer_configs = { + "base_tokenizer": base_tokenizer, + "language": language, + "with_position": with_position, + "max_token_length": max_token_length, + "lower_case": lower_case, + "stem": stem, + "remove_stop_words": remove_stop_words, + "custom_stop_words": custom_stop_words, + "ascii_folding": ascii_folding, + "ngram_min_length": ngram_min_length, + "ngram_max_length": ngram_max_length, + "prefix_only": prefix_only, + } + else: + tokenizer_configs = self.infer_tokenizer_configs(tokenizer_name) + tokenizer_configs["custom_stop_words"] = custom_stop_words + config = FTS( - with_position=with_position, - base_tokenizer=base_tokenizer, - language=language, - max_token_length=max_token_length, - lower_case=lower_case, - stem=stem, - remove_stop_words=remove_stop_words, - custom_stop_words=custom_stop_words, - ascii_folding=ascii_folding, - ngram_min_length=ngram_min_length, - ngram_max_length=ngram_max_length, - prefix_only=prefix_only, block_size=block_size, document_granularity=document_granularity, + **tokenizer_configs, ) - LOOP.run( - self._table.create_index( - column, - config=config, - replace=replace, - wait_timeout=wait_timeout, - name=name, + + try: + LOOP.run( + self._table.create_index( + field_names, + replace=replace, + config=config, + name=name, + wait_timeout=wait_timeout, + ) ) - ) + except (ValueError, RuntimeError) as e: + _maybe_add_fts_error_note( + e, + base_tokenizer=config.base_tokenizer, + language=config.language, + ) + raise e # New unified API overload @overload @@ -408,6 +504,7 @@ class RemoteTable(Table): /, *, config: IndexConfigType, + replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., train: bool = ..., @@ -418,38 +515,56 @@ class RemoteTable(Table): def create_index( self, metric: Literal["l2", "cosine", "dot", "hamming"] = ..., - vector_column_name: str = ..., - index_cache_size: Optional[int] = ..., num_partitions: Optional[int] = ..., num_sub_vectors: Optional[int] = ..., - replace: Optional[bool] = ..., + vector_column_name: str = ..., + replace: bool = ..., accelerator: Optional[str] = ..., - index_type: Literal[ - "VECTOR", "IVF_FLAT", "IVF_SQ", "IVF_PQ", "IVF_HNSW_SQ", "IVF_HNSW_PQ" - ] = ..., - wait_timeout: Optional[timedelta] = ..., - *, + index_cache_size: Optional[int] = ..., num_bits: int = ..., + index_type: Literal[ + "IVF_FLAT", "IVF_SQ", "IVF_PQ", "IVF_RQ", "IVF_HNSW_SQ", "IVF_HNSW_PQ" + ] = ..., + max_iterations: int = ..., + sample_rate: int = ..., + m: int = ..., + ef_construction: int = ..., + *, + wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., train: bool = ..., + target_partition_size: Optional[int] = ..., ) -> None: ... def create_index( self, metric: str = "l2", - vector_column_name: str = VECTOR_COLUMN_NAME, - index_cache_size: Optional[int] = None, num_partitions: Optional[int] = None, num_sub_vectors: Optional[int] = None, - replace: Optional[bool] = None, + vector_column_name: str = VECTOR_COLUMN_NAME, + replace: bool = True, accelerator: Optional[str] = None, - index_type="vector", - wait_timeout: Optional[timedelta] = None, - *, + index_cache_size: Optional[int] = None, num_bits: int = 8, + index_type: Literal[ + "IVF_FLAT", + "IVF_SQ", + "IVF_PQ", + "IVF_RQ", + "IVF_HNSW_SQ", + "IVF_HNSW_PQ", + "IVF_HNSW_FLAT", + ] = "IVF_PQ", + max_iterations: int = 50, + sample_rate: int = 256, + m: int = 20, + ef_construction: int = 300, + *, config: Optional[IndexConfigType] = None, + wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, train: bool = True, + target_partition_size: Optional[int] = None, ): """Create an index on a column. @@ -460,6 +575,24 @@ class RemoteTable(Table): argument plus separate ``vector_column_name`` / ``num_partitions`` / etc. parameters, and emits a ``DeprecationWarning``. + Parameters + ---------- + metric : str + For new API: the column name to index. + For legacy API: the distance metric ("l2", "cosine", "dot", "hamming"). + 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. + 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. + name : str, optional + Custom name for the index. + train : bool, default True + Whether to train the index with existing data. + Examples -------- New API (recommended): @@ -485,7 +618,6 @@ class RemoteTable(Table): vector_column_name, accelerator, index_cache_size, - replace, ) if is_legacy: @@ -501,53 +633,36 @@ class RemoteTable(Table): stacklevel=2, ) + # Legacy API: first arg is the distance metric column = vector_column_name if accelerator is not None: logging.warning( - "GPU accelerator is not supported for remote tables " + "GPU accelerator is not supported in LanceDB Distributed " "and will be ignored." ) - idx_type = index_type.upper() - if idx_type == "VECTOR" or idx_type == "IVF_PQ": - config = IvfPq( - distance_type=metric, - num_partitions=num_partitions, - num_sub_vectors=num_sub_vectors, - num_bits=num_bits, - ) - elif idx_type == "IVF_RQ": - config = IvfRq( - distance_type=metric, - num_partitions=num_partitions, - num_bits=num_bits, - ) - elif idx_type == "IVF_SQ": - config = IvfSq(distance_type=metric, num_partitions=num_partitions) - elif idx_type == "IVF_HNSW_PQ": - config = HnswPq( - distance_type=metric, - num_partitions=num_partitions, - num_sub_vectors=num_sub_vectors, - num_bits=num_bits, - ) - elif idx_type == "IVF_HNSW_SQ": - config = HnswSq(distance_type=metric, num_partitions=num_partitions) - elif idx_type == "IVF_HNSW_FLAT": - config = HnswFlat(distance_type=metric, num_partitions=num_partitions) - elif idx_type == "IVF_FLAT": - config = IvfFlat(distance_type=metric, num_partitions=num_partitions) - else: - raise ValueError( - f"Unknown vector index type: {idx_type}. Valid options are" - " 'IVF_FLAT', 'IVF_PQ', 'IVF_RQ', 'IVF_SQ'," - " 'IVF_HNSW_PQ', 'IVF_HNSW_SQ', 'IVF_HNSW_FLAT'" - ) + # Build config from legacy parameters + config = self._build_vector_config_from_legacy_params( + metric=metric, + index_type="IVF_PQ" + if index_type.upper() == "VECTOR" + else index_type.upper(), + num_partitions=num_partitions, + num_sub_vectors=num_sub_vectors, + num_bits=num_bits, + max_iterations=max_iterations, + sample_rate=sample_rate, + m=m, + ef_construction=ef_construction, + target_partition_size=target_partition_size, + accelerator=None, + ) + else: column = metric - LOOP.run( + return LOOP.run( self._table.create_index( column, replace=replace, @@ -586,37 +701,6 @@ class RemoteTable(Table): ) ) - def _is_legacy_create_index_call( - self, - first_arg: str, - config: Optional[IndexConfigType], - num_partitions: Optional[int], - num_sub_vectors: Optional[int], - vector_column_name: str, - accelerator: Optional[str], - index_cache_size: Optional[int], - replace: Optional[bool], - ) -> bool: - """Detect if this is a legacy create_index call.""" - if config is not None: - return False - if any( - x is not None - for x in ( - num_partitions, - num_sub_vectors, - accelerator, - index_cache_size, - replace, - ) - ): - return True - if vector_column_name != VECTOR_COLUMN_NAME: - return True - if first_arg.lower() in KNOWN_METRICS: - return True - return False - def add( self, data: DATA, @@ -629,7 +713,7 @@ class RemoteTable(Table): ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. - It has the same API signature as the OSS version. + It has the same API signature as the LanceDB Embedded version. Parameters ---------- @@ -659,7 +743,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 for remote tables. Setting this raises. + Not supported in LanceDB Distributed. Setting this raises. Returns ------- @@ -688,9 +772,10 @@ class RemoteTable(Table): query: Union[VEC, str] = None, vector_column_name: Optional[str] = None, query_type="auto", + ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, - ) -> LanceVectorQueryBuilder: + ) -> LanceQueryBuilder: """Create a search query to find the nearest neighbors of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/) @@ -781,6 +866,7 @@ class RemoteTable(Table): query, query_type, vector_column_name=vector_column_name, + ordering_field_name=ordering_field_name, fts_columns=fts_columns or [], fast_search=fast_search, ) @@ -840,7 +926,8 @@ class RemoteTable(Table): self._table._do_merge(merge, new_data, on_bad_vectors, fill_value) ) - def delete(self, predicate: str) -> DeleteResult: + @_deprecated_keyword("predicate", "where") + def delete(self, where: Union[str, Expr]) -> DeleteResult: """Delete rows from the table. This can be used to delete a single row, many rows, all rows, or @@ -848,7 +935,7 @@ class RemoteTable(Table): Parameters ---------- - predicate: str + where: Union[str, Expr] The SQL where clause to use when deleting rows. - For example, 'x = 2' or 'x IN (1, 2, 3)'. @@ -892,7 +979,7 @@ class RemoteTable(Table): x vector _distance # doctest: +SKIP 0 2 [3.0, 4.0] 85.0 # doctest: +SKIP """ - return LOOP.run(self._table.delete(predicate)) + return LOOP.run(self._table.delete(where)) def update( self, @@ -954,22 +1041,27 @@ class RemoteTable(Table): self._table.update(where=where, updates=values, updates_sql=values_sql) ) - def cleanup_old_versions(self, *_): + def cleanup_old_versions( + self, + older_than: Optional[timedelta] = None, + *, + delete_unverified: bool = False, + ): """ - cleanup_old_versions() is a no-op for remote tables. + cleanup_old_versions() is a no-op in LanceDB Distributed. """ warnings.warn( - "cleanup_old_versions() is a no-op for remote tables.", + "cleanup_old_versions() is a no-op in LanceDB Distributed.", stacklevel=2, ) pass - def compact_files(self, *_): + def compact_files(self, *args, **kwargs): """ - compact_files() is a no-op for remote tables. + compact_files() is a no-op in LanceDB Distributed. """ warnings.warn( - "compact_files() is a no-op for remote tables.", + "compact_files() is a no-op in LanceDB Distributed.", stacklevel=2, ) pass @@ -979,12 +1071,15 @@ class RemoteTable(Table): *, cleanup_older_than: Optional[timedelta] = None, delete_unverified: bool = False, + retrain: bool = False, + compaction_options: Optional[CompactionOptions] = None, ): - """optimize() is not supported for remote tables.""" + """optimize() is not supported in LanceDB Distributed.""" return LOOP.run( self._table.optimize( cleanup_older_than=cleanup_older_than, delete_unverified=delete_unverified, + retrain=retrain, ) ) @@ -1001,8 +1096,17 @@ class RemoteTable(Table): | None = None, *, computed: Dict[str, str] | None = None, + auto_refresh_enabled: bool | None = None, + auto_refresh_interval_seconds: int | None = None, ) -> AddColumnsResult: - return LOOP.run(self._table.add_columns(transforms, computed=computed)) + return LOOP.run( + self._table.add_columns( + transforms, + computed=computed, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, + ) + ) def refresh_column(self, column: str): return LOOP.run(self._table.refresh_column(column)) @@ -1080,11 +1184,12 @@ class RemoteTable(Table): ) def close_rte_writers(self) -> None: - """No-op for remote tables (no local shard writers).""" + """No-op in LanceDB Distributed (no local shard writers).""" return LOOP.run(self._table.close_rte_writers()) - def drop_index(self, index_name: str): - return LOOP.run(self._table.drop_index(index_name)) + @_deprecated_keyword("index_name", "name") + def drop_index(self, name: str) -> None: + return LOOP.run(self._table.drop_index(name)) def prewarm_index(self, name: str) -> None: """Prewarm an index in the table. @@ -1108,7 +1213,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 on remote tables. + Currently only supported in LanceDB Distributed. This call initiates prewarming and returns once the request is accepted. It is idempotent and safe to call from multiple clients concurrently. @@ -1137,15 +1242,25 @@ class RemoteTable(Table): def uri(self) -> str: """The table URI (storage location). - For remote tables, this fetches the location from the server via describe. + In LanceDB Distributed, this fetches the location from the server via describe. """ return LOOP.run(self._table.uri()) - def take_offsets(self, offsets: list[int]) -> LanceTakeQueryBuilder: - return LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + def take_offsets( + self, offsets: list[int], *, with_row_id: bool = False + ) -> LanceTakeQueryBuilder: + builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + if with_row_id: + builder.with_row_id() + return builder - def take_row_ids(self, row_ids: list[int]) -> LanceTakeQueryBuilder: - return LanceTakeQueryBuilder(self._table.take_row_ids(row_ids)) + def take_row_ids( + self, row_ids: list[int], *, with_row_id: bool = False + ) -> LanceTakeQueryBuilder: + builder = LanceTakeQueryBuilder(self._table.take_row_ids(row_ids)) + if with_row_id: + builder.with_row_id() + return builder def uses_v2_manifest_paths(self) -> bool: return LOOP.run(self._table.uses_v2_manifest_paths()) @@ -1173,6 +1288,11 @@ class RemoteTable(Table): ) -> "list[Optional[BlobFile]]": return LOOP.run(self._table.fetch_blob_files(column, row_ids)) + def open_blob_file( + self, descriptor: Union[dict, pa.StructScalar, None] + ) -> Optional[BlobFile]: + return LOOP.run(self._table.open_blob_file(descriptor)) + def head(self, n=5) -> pa.Table: """ Return the first `n` rows of the table. diff --git a/python/python/lancedb/rerankers/base.py b/python/python/lancedb/rerankers/base.py index 4af938a1e..e1bc7f0dd 100644 --- a/python/python/lancedb/rerankers/base.py +++ b/python/python/lancedb/rerankers/base.py @@ -241,6 +241,7 @@ class Reranker(ABC): This op is slower than just keeping relevance score but can be useful for debugging. """ + combined_schema = pa.unify_schemas([vector_results.schema, fts_results.schema]) # add nulls to fts results for _distance if "_distance" not in fts_results.column_names: fts_results = fts_results.append_column( @@ -265,7 +266,9 @@ class Reranker(ABC): else: vector_results_dict[key] = value - combined = pa.Table.from_pylist(list(vector_results_dict.values())) + combined = pa.Table.from_pylist( + list(vector_results_dict.values()), schema=combined_schema + ) return combined def _keep_relevance_score(self, combined_results: pa.Table): diff --git a/python/python/lancedb/rerankers/cohere.py b/python/python/lancedb/rerankers/cohere.py index efd752c22..a1e797f15 100644 --- a/python/python/lancedb/rerankers/cohere.py +++ b/python/python/lancedb/rerankers/cohere.py @@ -62,7 +62,7 @@ class CohereReranker(Reranker): "COHERE_API_KEY not set. Either set it in your environment or \ pass it as `api_key` argument to the CohereReranker." ) - return cohere.Client(os.environ.get("COHERE_API_KEY") or self.api_key) + return cohere.Client(self.api_key or os.environ.get("COHERE_API_KEY")) def _rerank(self, result_set: pa.Table, query: str): result_set = self._handle_empty_results(result_set) diff --git a/python/python/lancedb/rerankers/mrr.py b/python/python/lancedb/rerankers/mrr.py index 81a03c9ca..38f742bb8 100644 --- a/python/python/lancedb/rerankers/mrr.py +++ b/python/python/lancedb/rerankers/mrr.py @@ -97,7 +97,12 @@ class MRRReranker(Reranker): weighted_mrr = self.weight_vector * vector_rr + self.weight_fts * fts_rr final_mrr_scores[result_id] = weighted_mrr - combined_results = self.merge_results(vector_results, fts_results) + # With return_score="all", a row found by both searches must keep its + # `_distance` and its `_score`. + if self.score == "all": + combined_results = self._merge_and_keep_scores(vector_results, fts_results) + else: + combined_results = self.merge_results(vector_results, fts_results) combined_row_ids = combined_results["_rowid"].to_pylist() relevance_scores = [final_mrr_scores[row_id] for row_id in combined_row_ids] combined_results = combined_results.append_column( diff --git a/python/python/lancedb/rerankers/openai.py b/python/python/lancedb/rerankers/openai.py index 4cbbb0822..75efbbfc7 100644 --- a/python/python/lancedb/rerankers/openai.py +++ b/python/python/lancedb/rerankers/openai.py @@ -21,7 +21,7 @@ class OpenaiReranker(Reranker): Parameters ---------- - model_name : str, default "gpt-4-turbo-preview" + model_name : str, default "gpt-5.6-sol" The name of the cross encoder model to use. column : str, default "text" The name of the column to use as input to the cross encoder model. @@ -33,7 +33,7 @@ class OpenaiReranker(Reranker): def __init__( self, - model_name: str = "gpt-4-turbo-preview", + model_name: str = "gpt-5.6-sol", column: str = "text", return_score="relevance", api_key: Optional[str] = None, @@ -54,7 +54,6 @@ class OpenaiReranker(Reranker): response = self._client.chat.completions.create( model=self.model_name, response_format={"type": "json_object"}, - temperature=0, messages=[ { "role": "system", @@ -70,15 +69,18 @@ class OpenaiReranker(Reranker): ], ) results = json.loads(response.choices[0].message.content)["documents"] - docs, scores = list( - zip(*[(result["content"], result["relevance_score"]) for result in results]) - ) # tuples - # replace the self.column column with the docs - result_set = result_set.drop(self.column) - result_set = result_set.append_column( - self.column, pa.array(docs, type=pa.string()) - ) - # add the scores + # The model returns the documents in its own order, so match each score + # back to its row by content. + scores_by_content = { + result["content"]: result["relevance_score"] for result in results + } + missing = sum(doc not in scores_by_content for doc in docs) + if missing: + raise ValueError( + f"The model returned no relevance_score for {missing} of " + f"{len(docs)} documents" + ) + scores = [scores_by_content[doc] for doc in docs] result_set = result_set.append_column( "_relevance_score", pa.array(scores, type=pa.float32()) ) @@ -129,4 +131,4 @@ class OpenaiReranker(Reranker): "OPENAI_API_KEY not set. Either set it in your environment or \ pass it as `api_key` argument to the CohereReranker." ) - return openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY") or self.api_key) + return openai.OpenAI(api_key=self.api_key or os.environ.get("OPENAI_API_KEY")) diff --git a/python/python/lancedb/rerankers/rrf.py b/python/python/lancedb/rerankers/rrf.py index 9c835a3ea..c9b54a5a7 100644 --- a/python/python/lancedb/rerankers/rrf.py +++ b/python/python/lancedb/rerankers/rrf.py @@ -54,8 +54,12 @@ class RRFReranker(Reranker): for i, result_id in enumerate(ids, 1): rrf_score_map[result_id] += 1 / (i + self.K) - # Sort the results based on RRF score - combined_results = self.merge_results(vector_results, fts_results) + # Sort the results based on RRF score. With return_score="all", a row found + # by both searches must keep its `_distance` and its `_score`. + if self.score == "all": + combined_results = self._merge_and_keep_scores(vector_results, fts_results) + else: + combined_results = self.merge_results(vector_results, fts_results) combined_row_ids = combined_results["_rowid"].to_pylist() relevance_scores = [rrf_score_map[row_id] for row_id in combined_row_ids] combined_results = combined_results.append_column( diff --git a/python/python/lancedb/rerankers/voyageai.py b/python/python/lancedb/rerankers/voyageai.py index 0f41ba927..28847564b 100644 --- a/python/python/lancedb/rerankers/voyageai.py +++ b/python/python/lancedb/rerankers/voyageai.py @@ -32,7 +32,7 @@ class VoyageAIReranker(Reranker): return_score : str, default "relevance" options are "relevance" or "all". Only "relevance" is supported for now. api_key : str, default None - The API key to use. If None, will use the OPENAI_API_KEY environment variable. + The API key to use. If None, will use the VOYAGE_API_KEY environment variable. truncation : Optional[bool], default None """ @@ -64,7 +64,7 @@ class VoyageAIReranker(Reranker): pass it as `api_key` argument to the VoyageAIReranker." ) return voyageai.Client( - api_key=os.environ.get("VOYAGE_API_KEY") or self.api_key, + api_key=self.api_key or os.environ.get("VOYAGE_API_KEY"), ) def _rerank(self, result_set: pa.Table, query: str): diff --git a/python/python/lancedb/scannable.py b/python/python/lancedb/scannable.py index baf8e0c2b..9a6f71a5d 100644 --- a/python/python/lancedb/scannable.py +++ b/python/python/lancedb/scannable.py @@ -276,6 +276,14 @@ def _from_iterable(data: Iterator) -> Scannable: _registered_modules: set[str] = set() +def _hf_batches(data): + if data._indices is None: + yield from data.data.to_batches() + else: + for table in data.with_format("arrow").iter(batch_size=1000): + yield from table.to_batches() + + def _register_optional_converters(): """Register converters for optional dependencies that are already imported.""" @@ -323,7 +331,15 @@ def _register_optional_converters(): def _from_hf_dataset(data: HFDataset) -> Scannable: table = data.data.table # Access underlying Arrow table return Scannable( - schema=table.schema, num_rows=len(data), reader=table.to_reader + schema=table.schema, + num_rows=len(data), + reader=( + table.to_reader + if data._indices is None + else lambda: pa.RecordBatchReader.from_batches( + table.schema, _hf_batches(data) + ) + ), ) @to_scannable.register(HFDatasetDict) @@ -335,7 +351,7 @@ def _register_optional_converters(): def gen(): for split_name, dataset in data.items(): - for batch in dataset.data.to_batches(): + for batch in _hf_batches(dataset): split_arr = pa.array( [split_name] * len(batch), type=pa.string() ) diff --git a/python/python/lancedb/schema.py b/python/python/lancedb/schema.py index 5edda5610..d92f7f692 100644 --- a/python/python/lancedb/schema.py +++ b/python/python/lancedb/schema.py @@ -4,8 +4,9 @@ """Schema helpers for Lance blob columns.""" +import ctypes import importlib -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING, Iterable, Optional import pyarrow as pa import pyarrow.ipc @@ -16,6 +17,7 @@ if TYPE_CHECKING: _BLOB_EXTENSION_NAME = "lance.blob.v2" _BLOB_V1_KEY = "lance-encoding:blob" _ARROW_EXT_NAME_KEY = "ARROW:extension:name" +_MAX_RUST_USIZE = ctypes.c_size_t(-1).value _BLOB_V2_STORAGE_TYPE = pa.struct( [ pa.field("data", pa.large_binary(), nullable=True), @@ -30,8 +32,8 @@ _resolved_blob_type = None class _FallbackBlobType(pa.ExtensionType): """lance.blob.v2 extension type used when pylance is not installed.""" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, _BLOB_V2_STORAGE_TYPE, _BLOB_EXTENSION_NAME) + def __init__(self, storage_type: pa.DataType = _BLOB_V2_STORAGE_TYPE) -> None: + pa.ExtensionType.__init__(self, storage_type, _BLOB_EXTENSION_NAME) def __arrow_ext_serialize__(self) -> bytes: return b"" @@ -40,7 +42,7 @@ class _FallbackBlobType(pa.ExtensionType): def __arrow_ext_deserialize__( cls, storage_type: pa.DataType, serialized: bytes ) -> "_FallbackBlobType": - return cls() + return cls(storage_type) def __reduce__(self): return type(self).__arrow_ext_deserialize__, ( @@ -181,6 +183,24 @@ def _resolve_blob_type(): return _resolved_blob_type +def _restore_blob_extensions(schema: pa.Schema) -> pa.Schema: + """Restore blob fields read before their extension type was registered.""" + unrestored = _collect_blob_paths( + schema, + lambda field: ( + not isinstance(field.type, pa.ExtensionType) + and _metadata_marks_blob_v2(field.metadata or {}) + ), + ) + if not unrestored: + return schema + + _resolve_blob_type() + # Arrow's deserializer uses the registered class and preserves nested fields, + # storage layouts, nullability, and unrelated metadata. Only the schema is read. + return pa.ipc.read_schema(schema.serialize()) + + def blob( name: str, nullable: bool = True, @@ -209,32 +229,110 @@ def blob( Maximum size in bytes of a single packed blob sidecar file before a new one is started. Must be positive. - The thresholds are forwarded to ``lance.blob_field``, which validates - them and stores them as field metadata, so pylance is required whenever - any threshold is set. When all thresholds are omitted the behavior is - unchanged. + Notes + ----- + Thresholds are validated and stored as Arrow field metadata, with the + same format as ``lance.blob_field``. They do not require pylance. + + The extension's storage is a struct with nullable fields ``data`` + (large_binary), ``uri`` (string), ``position`` (uint64), and ``size`` + (uint64). Each non-null blob must set exactly one of ``data`` and ``uri``: + + - Inline bytes use ``data``, leaving all other fields null. ``b""`` is a + valid empty blob; use a null struct for a null blob. + - External blobs use ``uri``, leaving ``data`` null. Set both ``position`` + and ``size`` to select a byte range, or leave both null for the whole + object. A range's ``size`` must be greater than zero. + + Use [blob_array][lancedb.schema.blob_array] to build inline blob arrays + for Arrow record batches. For external descriptors, build the struct + array with ``field.type.storage_type`` and wrap it with + ``pa.ExtensionArray.from_storage(field.type, storage)``. + + ``create_table(..., schema=...)`` casts plain binary values into blob + columns declared by this field, and ``table.add(...)`` does the same + using the table's schema. PyArrow's ``RecordBatch.from_pylist`` does not + perform this conversion; construct blob arrays explicitly instead. """ - if ( - inline_size_threshold is None - and dedicated_size_threshold is None - and pack_file_size_threshold is None + metadata = {} + for threshold, value, allow_zero, key in ( + ( + "inline_size_threshold", + inline_size_threshold, + True, + "lance-encoding:blob-inline-size-threshold", + ), + ( + "dedicated_size_threshold", + dedicated_size_threshold, + False, + "lance-encoding:blob-dedicated-size-threshold", + ), + ( + "pack_file_size_threshold", + pack_file_size_threshold, + False, + "lance-encoding:blob-pack-file-size-threshold", + ), ): - blob_type = _resolve_blob_type() - return pa.field(name, blob_type(), nullable=nullable) - try: - lance = importlib.import_module("lance") - except ModuleNotFoundError as err: - raise ValueError( - "Setting blob tier thresholds requires pylance to be installed" - ) from err - _resolve_blob_type() - return lance.blob_field( - name, - nullable=nullable, - inline_size_threshold=inline_size_threshold, - dedicated_size_threshold=dedicated_size_threshold, - pack_file_size_threshold=pack_file_size_threshold, - ) + if value is None: + continue + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError(f"{threshold} must be an int, got {type(value).__name__}") + if value < 0 or (value == 0 and not allow_zero): + bound = "non-negative" if allow_zero else "positive" + raise ValueError(f"{threshold} must be {bound}") + if value > _MAX_RUST_USIZE: + raise OverflowError(f"{threshold} must fit in a Rust usize") + metadata[key] = str(value) + + blob_type = _resolve_blob_type() + field = pa.field(name, blob_type(), nullable=nullable) + return field.with_metadata(metadata) if metadata else field + + +def blob_array(payloads: Iterable[Optional[bytes]]) -> pa.ExtensionArray: + """Build a Lance blob v2 extension array from inline bytes. + + Uses the same extension type as [blob][lancedb.schema.blob], with or + without pylance installed. + + Parameters + ---------- + payloads: + An iterable of ``bytes`` or ``None``. ``None`` creates a null blob; + ``b""`` creates a valid empty blob. + + Returns + ------- + pa.ExtensionArray + Inline blob values ready to use in Arrow tables or record batches. + + Raises + ------ + TypeError + If a payload is neither ``bytes`` nor ``None``. + + Examples + -------- + >>> import pyarrow as pa + >>> from lancedb.schema import blob, blob_array + >>> schema = pa.schema([blob("video")]) + >>> videos = blob_array([b"abc", None, b""]) + >>> batch = pa.RecordBatch.from_arrays([videos], schema=schema) + >>> batch.num_rows + 3 + """ + blob_type = _resolve_blob_type()() + descriptors = [] + for payload in payloads: + if payload is not None and not isinstance(payload, bytes): + raise TypeError( + f"payloads must contain bytes or None, got {type(payload).__name__}" + ) + descriptors.append(None if payload is None else {"data": payload}) + storage = pa.array(descriptors, type=blob_type.storage_type) + return pa.ExtensionArray.from_storage(blob_type, storage) def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataType: diff --git a/python/python/lancedb/sql.py b/python/python/lancedb/sql.py index 05b82b0d3..d011e25a5 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 remote database.""" +"""Handles to SQL queries running on a LanceDB Distributed database.""" from typing import Any, Mapping, Optional, Sequence, Union from uuid import UUID diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 91ca6ce28..db71840c6 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -19,6 +19,7 @@ above. """ import ctypes +import hashlib import heapq import logging import os @@ -39,6 +40,7 @@ from torch.utils.data import DataLoader, IterableDataset, get_worker_info from .permutation import ( Permutation, + PermutationBuilder, Transforms, permutation_builder, _drop_base_version, @@ -244,6 +246,20 @@ class StreamingDataset(IterableDataset): default) rows are shuffled using ``shuffle_seed`` and ``epoch``. When ``False`` rows are divided into splits sequentially in storage order, which can be useful for deterministic debugging or evaluation. + Ignored when ``split_strategy`` is provided. + split_strategy: + Escape hatch for any ``PermutationBuilder`` split strategy this class + doesn't otherwise expose a dedicated parameter for -- ``split_hash``, + ``split_calculated``, ``bootstrap_sample`` (uniform sampling with + replacement), or any strategy added later. A callable that receives a + fresh ``PermutationBuilder`` for ``table`` and returns a configured one; + it is called and ``.execute()``'d directly, taking over permutation + construction entirely. When provided, ``shuffle``, ``shuffle_seed``, + ``epoch``, and ``shuffle_clump_size`` are ignored -- the callable is + solely responsible for how rows are split and ordered. For example, + ``split_strategy=lambda b: b.bootstrap_sample(10_000, fixed=num_splits, + seed=42)`` draws 10,000 samples with replacement, divided evenly across + ``num_splits`` splits. shuffle_seed: Base seed for the random permutation. Combined with ``epoch`` so each epoch produces a different ordering. Pass ``None`` to generate @@ -379,6 +395,16 @@ class StreamingDataset(IterableDataset): capping peak memory when the consumer (e.g. a GPU training step) is slower than the transform stage. Must be greater than zero. ``None`` (the default) imposes no limit. + connection_factory: + Optional picklable function that takes the table name and returns an + open LanceDB table. When set, pickling the dataset (as DataLoader + workers do under the ``spawn`` and ``forkserver`` start methods) + replaces the table's reopen state with its name, and each worker calls + the factory with that name to reopen the table. The factory itself is + pickled too, so credentials stay out of the pickle only if the factory + loads them in the worker, for example from the environment, instead of + capturing them. ``None`` (the default) pickles the table's own reopen + state instead. worker_info_override: If set, used in place of ``torch.utils.data.get_worker_info()`` to determine the DataLoader worker assignment. Intended for unit tests @@ -393,6 +419,9 @@ class StreamingDataset(IterableDataset): *, num_splits: Optional[int] = None, shuffle: bool = True, + split_strategy: Optional[ + Callable[[PermutationBuilder], PermutationBuilder] + ] = None, shuffle_seed: Optional[int] = 0, epoch: int = 0, rank: int = 0, @@ -583,13 +612,70 @@ class StreamingDataset(IterableDataset): builder = permutation_builder(table) if filter is not None: builder = builder.filter(filter) - if shuffle: + if split_strategy is not None: + # Escape hatch: lets any PermutationBuilder split strategy drive this + # dataset (split_hash, split_calculated, bootstrap_sample, or any future + # strategy) without StreamingDataset needing a bespoke parameter for each + # one. shuffle/shuffle_seed/epoch/shuffle_clump_size are ignored in this + # path -- the caller's split_strategy is solely responsible for ordering. + self._perm_table = split_strategy(builder).execute() + # _rank_splits below assumes split ids are exactly 0..num_splits-1 with no + # gaps (every other path guarantees this by always building with + # fixed=num_splits) -- a split_strategy callable has no such guarantee, and + # a mismatch would otherwise silently drop rows (ids >= num_splits) or leave + # some ranks reading an empty split (missing ids < num_splits). + split_value_counts = ( + self._perm_table.to_arrow().column("split_id").value_counts() + ) + counts_by_split = dict( + zip( + split_value_counts.field("values").to_pylist(), + split_value_counts.field("counts").to_pylist(), + ) + ) + expected_splits = set(range(num_splits)) + if set(counts_by_split) != expected_splits: + raise ValueError( + f"split_strategy produced split ids {sorted(counts_by_split)}, " + f"but num_splits={num_splits} requires exactly " + f"{{0, ..., {num_splits - 1}}}. Pass num_splits matching the " + "strategy's own split count (e.g. `fixed=num_splits` on " + "bootstrap_sample/split_random/etc.)." + ) + # The round-robin iteration below (and in _iter_owned) assumes every + # split has the same row count -- it stops as soon as any one owned + # split is exhausted (see its own comment: "all splits exhaust + # simultaneously"). Every other path guarantees this by always building + # with fixed=num_splits; a split_strategy using ratios/counts/split_hash + # weights has no such guarantee, and unequal sizes would otherwise + # silently drop rows from the larger splits -- or, with world_size > 1 + # where each rank owns different splits, end ranks after different row + # counts and desync or hang a distributed run's end-of-epoch collectives. + if len(set(counts_by_split.values())) > 1: + raise ValueError( + f"split_strategy produced unequal split sizes " + f"{counts_by_split} (split id -> row count). Every split must " + "have the same row count. Use `fixed=num_splits` rather than " + "`ratios`/`counts`/weighted `split_hash`, which can produce " + "unequal sizes, or split unevenly-sized groups into separate " + "StreamingDatasets instead." + ) + elif shuffle: perm_seed = shuffle_seed + epoch * _EPOCH_PRIME self._perm_table = builder.split_random( fixed=num_splits, seed=perm_seed, clump_size=shuffle_clump_size ).execute() else: self._perm_table = builder.split_sequential(fixed=num_splits).execute() + # Only the split_strategy path needs a permutation fingerprint in the + # checkpoint (see `_checkpoint_snapshot`): split_random/split_sequential are + # already fully pinned by shuffle_seed/num_splits, and a fingerprint over raw + # row ids would spuriously reject an otherwise-valid resume after those row + # ids get renumbered by compaction (row ids are not stable by default). + self._uses_split_strategy = split_strategy is not None + # Lazily computed and cached by `_perm_fingerprint` -- `_perm_table` never + # changes after construction, so this is correct to compute once. + self._perm_fingerprint_cache: Optional[str] = None if self._blocks_per_epoch == "auto": self._blocks_per_epoch = self._estimate_blocks_per_epoch() @@ -1406,11 +1492,51 @@ class StreamingDataset(IterableDataset): ) return state + @property + def _perm_fingerprint(self) -> str: + """Cheap identity check for the built permutation, computed once and cached + (``_perm_table`` never changes after construction). + + Only meaningful -- and only recorded in a checkpoint -- for the + ``split_strategy`` path (see ``_checkpoint_snapshot``): ``num_splits``/ + ``shuffle_seed`` alone cannot detect a `load_state_dict` resuming saved + per-split progress against a *different* permutation than the one that + produced it, since a ``split_strategy`` callable ignores ``shuffle_seed`` + entirely -- e.g. a ``bootstrap_sample`` with no seed (or any changed + callable) can rebuild a completely different permutation on the next run + while ``shuffle_seed`` keeps its same default value and the existing check + passes anyway. ``split_random``/``split_sequential`` are already fully + pinned by ``shuffle_seed``/``num_splits`` and must *not* additionally be + fingerprinted: this hashes physical row ids, which are not stable across + compaction by default, so checking it on those paths would reject an + otherwise-valid resume after the table gets compacted between save and + load even though the seeded permutation itself is unchanged. + """ + if self._perm_fingerprint_cache is None: + arrow_tbl = self._perm_table.to_arrow() + hasher = hashlib.sha256() + hasher.update(str(arrow_tbl.num_rows).encode()) + for name in ("row_id", "split_id"): + column = arrow_tbl.column(name).combine_chunks() + hasher.update(column.to_numpy(zero_copy_only=False).tobytes()) + self._perm_fingerprint_cache = hasher.hexdigest() + return self._perm_fingerprint_cache + def _checkpoint_snapshot(self) -> dict: + # Only recorded for split_strategy: split_random/split_sequential are + # already fully pinned by shuffle_seed/num_splits below, and row ids are not + # stable across compaction by default, so fingerprinting them unconditionally + # would reject an otherwise-valid resume after the table got compacted. + perm_fingerprint = ( + {"perm_fingerprint": self._perm_fingerprint} + if (self._uses_split_strategy) + else {} + ) if self._pack_sequences is not None: return { "shuffle_seed": self._shuffle_seed, "num_splits": self._num_splits, + **perm_fingerprint, "epoch": self._epoch, "pack_sequences": self._pack_sequences, "eos_id": self._eos_id, @@ -1431,6 +1557,7 @@ class StreamingDataset(IterableDataset): return { "shuffle_seed": self._shuffle_seed, "num_splits": self._num_splits, + **perm_fingerprint, "epoch": self._epoch, "samples_consumed_per_split": samples, "positions_consumed_per_split": positions, @@ -1560,8 +1687,16 @@ class StreamingDataset(IterableDataset): Raises ``ValueError`` if ``num_splits`` or ``shuffle_seed`` differ from the checkpoint, since a different split structure or shuffle order - makes mid-epoch resumption meaningless. Packed checkpoints - pin ``pack_sequences``, ``eos_id``, ``pad_id``, + makes mid-epoch resumption meaningless. Also raises if the checkpoint + was built with ``split_strategy`` and records a permutation fingerprint + that does not match the current dataset's permutation -- this catches a + changed or non-deterministically-reseeded ``split_strategy`` that + ``num_splits``/``shuffle_seed`` alone cannot detect, since ``shuffle_seed`` + is unused on that path. Checkpoints from ``split_random``/ + ``split_sequential`` never carry this fingerprint (row ids are not stable + across compaction, so it would reject an otherwise-valid resume), and + continue to rely on ``shuffle_seed``/``num_splits`` alone as before. + Packed checkpoints pin ``pack_sequences``, ``eos_id``, ``pad_id``, ``blocks_per_epoch``, and ``epoch``. """ if state["num_splits"] != self._num_splits: @@ -1574,6 +1709,19 @@ class StreamingDataset(IterableDataset): f"shuffle_seed mismatch: checkpoint has {state['shuffle_seed']}, " f"current dataset has {self._shuffle_seed}" ) + checkpoint_fingerprint = state.get("perm_fingerprint") + if ( + checkpoint_fingerprint is not None + and checkpoint_fingerprint != self._perm_fingerprint + ): + raise ValueError( + "permutation mismatch: this checkpoint was saved against a " + "different permutation (e.g. a split_strategy that resamples " + "differently between runs, such as bootstrap_sample with no " + "seed, or a changed callable) than the current dataset built. " + "Resuming would apply saved per-split positions to the wrong " + "rows." + ) self._consumer_checkpoint_requires_uniform = False if "pack_buffers" in state or self._pack_sequences is not None: @@ -1675,6 +1823,10 @@ class StreamingDataset(IterableDataset): first = states[0] packed = "pack_buffers" in first config_keys = ["shuffle_seed", "num_splits", "epoch"] + if "perm_fingerprint" in first: + # Absent only in checkpoints saved before this key existed; skip rather + # than KeyError so old checkpoints keep merging. + config_keys.append("perm_fingerprint") if packed: config_keys.extend( ["pack_sequences", "eos_id", "pad_id", "blocks_per_epoch"] @@ -1684,6 +1836,8 @@ class StreamingDataset(IterableDataset): if ("pack_buffers" in state) != packed: raise ValueError("cannot merge packed and unpacked state dicts") for key in config_keys: + if key not in state: + continue if state[key] != first[key]: raise ValueError( f"{key} mismatch across state dicts: " diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 48d5582d1..b68f15912 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -15,24 +15,28 @@ from functools import cached_property from typing import ( TYPE_CHECKING, Any, + AsyncIterator, Callable, Dict, Iterable, + Iterator, List, Literal, Optional, Sequence, Tuple, + TypedDict, Union, overload, ) from urllib.parse import urlparse -from lancedb.scannable import _register_optional_converters, to_scannable +from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable from . import __version__ from ._blob import ( BlobFile, + _normalize_blob_descriptor, _normalize_blob_row_ids, _wrap_blob_files, strip_auto_row_ids, @@ -106,6 +110,7 @@ from .util import ( ) from .index import lang_mapping from .schema import ( + _restore_blob_extensions, blob_v2_column_paths, is_blob_v2_field, row_addressable_blob_v2_paths, @@ -119,6 +124,33 @@ def _should_push_down_query_table( return namespace_client is not None and "QueryTable" in pushdown_operations +_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 " + "omit `accelerator` (or set `accelerator=None`) to create the index on CPU." +) + + +def _validate_index_accelerator(accelerator: Any) -> None: + if not isinstance(accelerator, str) or accelerator.split(":", 1)[0] != "cuda": + return + + try: + import torch + + cuda_available = torch.cuda.is_available() + except (ImportError, RuntimeError, AssertionError) as err: + raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err + + if not cuda_available: + raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) + + try: + torch.cuda.init() + except (RuntimeError, AssertionError) as err: + raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err + + def _polars_predicate_pushdown_barrier(frame: Any) -> Any: """Return a Polars frame unchanged while blocking predicate pushdown.""" return frame @@ -235,10 +267,8 @@ if TYPE_CHECKING: OnBadVectorsType, AddMode, CreateMode, - VectorIndexType, ScalarIndexType, BaseTokenizerType, - DistanceType, ) # Type alias for index configuration objects @@ -257,6 +287,91 @@ IndexConfigType = Union[ FTS, ] + +class CompactionOptions(TypedDict, total=False): + """Options that control file compaction during table optimization. + + Unspecified options use Lance's defaults. + + Compaction planning is row based. Lowering ``target_rows_per_fragment`` + based on the expected row size can bound later compaction passes once + oversized fragments have been rewritten. It does not split an existing + fragment, so the first pass over an oversized fragment is not subject to + that bound. ``max_bytes_per_file`` limits output file size, not compaction + memory. Source budgets keep whole planned tasks; if the first task exceeds + a budget, that run performs no compaction work. + + Examples + -------- + Derive a steady-state row target from the expected row size: + + >>> desired_fragment_bytes = 750 * 1024 * 1024 + >>> average_row_bytes = 1_500_000 + >>> options: CompactionOptions = { + ... "target_rows_per_fragment": max( + ... 1, desired_fragment_bytes // average_row_bytes + ... ), + ... } + >>> await table.optimize(compaction_options=options) # doctest: +SKIP + """ + + target_rows_per_fragment: int + """Target rows per fragment; existing oversized fragments are not split.""" + + max_rows_per_group: int + """Maximum number of rows per row group (default: 1,024).""" + + max_bytes_per_file: Optional[int] + """Maximum output data-file size; this does not bound compaction memory.""" + + materialize_deletions: bool + """Whether to rewrite fragments containing deleted rows (default: True).""" + + materialize_deletions_threshold: float + """Minimum deleted-row fraction that makes a fragment eligible (default: 0.1).""" + + num_threads: Optional[int] + """Number of compaction tasks to run in parallel.""" + + batch_size: Optional[int] + """Number of rows per input scan batch.""" + + io_buffer_size: Optional[int] + """Maximum number of bytes queued in the input scan I/O buffer.""" + + defer_index_remap: bool + """Whether to defer index remapping during compaction (default: False).""" + + index_remap_mode: Literal["direct", "compact"] + """How to construct the old-to-new row-address mapping.""" + + compaction_mode: Optional[ + Literal["reencode", "try_binary_copy", "force_binary_copy"] + ] + """Whether compaction re-encodes data or uses binary copying.""" + + binary_copy_read_batch_bytes: Optional[int] + """Number of bytes read per batch during binary-copy compaction.""" + + max_source_fragments: Optional[int] + """Maximum number of source fragments compacted in one run.""" + + max_source_rows: Optional[int] + """Maximum live source rows per run, applied to whole planned tasks.""" + + max_source_bytes: Optional[int] + """Maximum source bytes per run, applied to whole planned tasks.""" + + excluded_fragment_ids: List[int] + """Fragment IDs to leave unchanged and use as planning boundaries.""" + + max_overlays_per_fragment: Optional[int] + """Maximum overlays before a fragment is fully compacted.""" + + data_storage_version: str + """Data-file version or release selector for compacted output.""" + + # Known distance metrics for legacy API detection KNOWN_METRICS = {"l2", "cosine", "dot", "hamming"} @@ -373,7 +488,7 @@ def _into_pyarrow_reader( if _check_for_hugging_face(data): if isinstance(data, datasets.Dataset): schema = data.features.arrow_schema - return pa.RecordBatchReader.from_batches(schema, data.data.to_batches()) + return pa.RecordBatchReader.from_batches(schema, _hf_batches(data)) elif isinstance(data, datasets.dataset_dict.DatasetDict): schema = _schema_from_hf(data, None) if "split" not in schema.names: @@ -442,7 +557,7 @@ def _into_pyarrow_reader( ): return data.collect().to_arrow().to_reader() elif isinstance(data, Iterable): - return _iterator_to_reader(data) + return _iterator_to_reader(data, schema) else: raise TypeError( f"Unknown data type {type(data)}. " @@ -452,10 +567,19 @@ def _into_pyarrow_reader( ) -def _iterator_to_reader(data: Iterable) -> pa.RecordBatchReader: +def _iterator_to_reader( + data: Iterable, schema: Optional[pa.Schema] = None +) -> pa.RecordBatchReader: # Each batch is treated as it's own reader, mainly so we can # re-use the _into_pyarrow_reader logic. - first = _into_pyarrow_reader(next(data)) + data = iter(data) + try: + first_batch = next(data) + except StopIteration: + if schema is None: + raise ValueError("Cannot create table from empty iterable without a schema") + return pa.RecordBatchReader.from_batches(schema, []) + first = _into_pyarrow_reader(first_batch) schema = first.schema def gen(): @@ -508,10 +632,11 @@ def _sanitize_data( metadata : Optional[dict], default None The embedding metadata to add to the schema. on_bad_vectors : Literal["error", "drop", "fill", "null"], default "error" - What to do if any of the vectors are not the same size or contains NaNs. + How to handle vectors with incorrect sizes, NaNs, or null elements. fill_value : float, default 0.0 The value to use when filling vectors. Only used if on_bad_vectors="fill". - All entries in the vector will be set to this value. + NaN or null elements and missing trailing elements are replaced with this + value. Valid elements are preserved. """ # At this point, the table might not match the schema we are targeting: # 1. There might be embedding columns missing that will be added @@ -1168,7 +1293,7 @@ def _to_batches_with_split(data): with an extra `split` column """ for key, dataset in data.items(): - for batch in dataset.data.to_batches(): + for batch in _hf_batches(dataset): table = pa.Table.from_batches([batch]) if "split" not in table.column_names: table = table.append_column( @@ -1320,13 +1445,23 @@ class Table(ABC): @abstractmethod def name(self) -> str: """The name of this Table""" - raise NotImplementedError + raise NotImplementedError("name is not supported for this table type") + + @property + def namespace(self) -> List[str]: + """Return the namespace path of the table (empty for the root namespace).""" + return [] + + @property + def id(self) -> str: + """Return the full identifier of the table (namespace$name).""" + return "$".join(self.namespace + [self.name]) @property @abstractmethod def version(self) -> int: """The version of this Table""" - raise NotImplementedError + raise NotImplementedError("version is not supported for this table type") @property @abstractmethod @@ -1335,7 +1470,7 @@ class Table(ABC): of this Table """ - raise NotImplementedError + raise NotImplementedError("schema is not supported for this table type") @property @abstractmethod @@ -1364,7 +1499,7 @@ class Table(ABC): tags = table.tags.list() """ - raise NotImplementedError + raise NotImplementedError("tags is not supported for this table type") @property def branches(self) -> "Branches": @@ -1373,11 +1508,11 @@ class Table(ABC): Branches are isolated, writable lines of history forked from another branch (or version). Writes on a branch do not affect ``main``. """ - raise NotImplementedError + raise NotImplementedError("branches is not supported for this table type") def current_branch(self) -> Optional[str]: """The branch this table handle is scoped to, or ``None`` for ``main``.""" - raise NotImplementedError + raise NotImplementedError("current_branch is not supported for this table type") def __len__(self) -> int: """The number of rows in this Table""" @@ -1400,7 +1535,7 @@ class Table(ABC): filter: str, optional A SQL where clause to filter the rows to count. """ - raise NotImplementedError + raise NotImplementedError("count_rows is not supported for this table type") def to_pandas(self, blob_mode: BlobMode = "lazy", **kwargs) -> "pandas.DataFrame": """Return the table as a pandas DataFrame. @@ -1435,20 +1570,33 @@ class Table(ABC): ------- pa.Table """ - raise NotImplementedError + raise NotImplementedError("to_arrow is not supported for this table type") def to_lance(self, **kwargs) -> lance.LanceDataset: - """Return the table as a lance.LanceDataset. + """Return a LanceDB Embedded table as a lance.LanceDataset. + + LanceDB Distributed tables cannot be opened as Lance datasets by the + client. Use + ``table.search().to_arrow()`` to read them through the server. Returns ------- lance.LanceDataset """ - raise NotImplementedError + raise NotImplementedError("to_lance is not supported for this table type") - def to_polars(self, **kwargs) -> "pl.LazyFrame": + 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 + results to a Polars DataFrame. + + Parameters + ---------- + batch_size: int, optional + Passed to Polars as the maximum row count for scanned PyArrow + record batches. + Note ---- The Polars streaming engine is not supported because it does not currently @@ -1459,7 +1607,194 @@ class Table(ABC): ------- polars.LazyFrame """ - raise NotImplementedError + raise NotImplementedError("to_polars is not supported for this table type") + + def _is_legacy_create_index_call( + self, + first_arg: str, + config: Optional[IndexConfigType], + num_partitions: Optional[int], + num_sub_vectors: Optional[int], + vector_column_name: str, + accelerator: Optional[str], + index_cache_size: Optional[int], + ) -> bool: + """Detect if this is a legacy create_index call.""" + # If config is provided, it's definitely the new API + if config is not None: + return False + + # If old-style parameters were explicitly set, it's legacy + if any( + x is not None + for x in (num_partitions, num_sub_vectors, accelerator, index_cache_size) + ): + return True + + # If vector_column_name differs from default, it's legacy + if vector_column_name != VECTOR_COLUMN_NAME: + return True + + # If first arg is a known metric, assume legacy + if first_arg.lower() in KNOWN_METRICS: + return True + + # Otherwise assume new API + return False + + def _build_vector_config_from_legacy_params( + self, + metric: str, + index_type: str, + num_partitions: Optional[int], + num_sub_vectors: Optional[int], + num_bits: int, + max_iterations: int, + sample_rate: int, + m: int, + ef_construction: int, + target_partition_size: Optional[int], + accelerator: Optional[str], + ) -> IndexConfigType: + """Build an index config object from legacy parameters.""" + if index_type == "IVF_FLAT": + return IvfFlat( + distance_type=metric, + num_partitions=num_partitions, + max_iterations=max_iterations, + sample_rate=sample_rate, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_SQ": + return IvfSq( + distance_type=metric, + num_partitions=num_partitions, + max_iterations=max_iterations, + sample_rate=sample_rate, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_PQ": + return IvfPq( + distance_type=metric, + num_partitions=num_partitions, + num_sub_vectors=num_sub_vectors, + num_bits=num_bits, + max_iterations=max_iterations, + sample_rate=sample_rate, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_RQ": + return IvfRq( + distance_type=metric, + num_partitions=num_partitions, + num_bits=num_bits, + max_iterations=max_iterations, + sample_rate=sample_rate, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_HNSW_PQ": + return HnswPq( + distance_type=metric, + num_partitions=num_partitions, + num_sub_vectors=num_sub_vectors, + num_bits=num_bits, + max_iterations=max_iterations, + sample_rate=sample_rate, + m=m, + ef_construction=ef_construction, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_HNSW_SQ": + return HnswSq( + distance_type=metric, + num_partitions=num_partitions, + max_iterations=max_iterations, + sample_rate=sample_rate, + m=m, + ef_construction=ef_construction, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_HNSW_FLAT": + return HnswFlat( + distance_type=metric, + num_partitions=num_partitions, + max_iterations=max_iterations, + sample_rate=sample_rate, + m=m, + ef_construction=ef_construction, + target_partition_size=target_partition_size, + ) + else: + raise ValueError(f"Unknown index type {index_type}") + + @staticmethod + def infer_tokenizer_configs(tokenizer_name: str) -> dict: + if tokenizer_name == "default": + return { + "base_tokenizer": "simple", + "language": "English", + "max_token_length": 40, + "lower_case": True, + "stem": False, + "remove_stop_words": False, + "ascii_folding": False, + "ngram_min_length": 3, + "ngram_max_length": 3, + "prefix_only": False, + } + elif tokenizer_name == "raw": + return { + "base_tokenizer": "raw", + "language": "English", + "max_token_length": None, + "lower_case": False, + "stem": False, + "remove_stop_words": False, + "ascii_folding": False, + "ngram_min_length": 3, + "ngram_max_length": 3, + "prefix_only": False, + } + elif tokenizer_name == "whitespace": + return { + "base_tokenizer": "whitespace", + "language": "English", + "max_token_length": None, + "lower_case": False, + "stem": False, + "remove_stop_words": False, + "ascii_folding": False, + "ngram_min_length": 3, + "ngram_max_length": 3, + "prefix_only": False, + } + + # or it's with language stemming with pattern like "en_stem" + if len(tokenizer_name) != 7: + raise ValueError(f"Invalid tokenizer name {tokenizer_name}") + lang = tokenizer_name[:2] + if tokenizer_name[-5:] != "_stem": + raise ValueError(f"Invalid tokenizer name {tokenizer_name}") + if lang not in lang_mapping: + raise ValueError(f"Invalid language code {lang}") + return { + "base_tokenizer": "simple", + "language": lang_mapping[lang], + "max_token_length": 40, + "lower_case": True, + "stem": True, + "remove_stop_words": False, + "ascii_folding": False, + "ngram_min_length": 3, + "ngram_max_length": 3, + "prefix_only": False, + } # New unified API overload @overload @@ -1486,14 +1821,16 @@ class Table(ABC): replace: bool = ..., accelerator: Optional[str] = ..., index_cache_size: Optional[int] = ..., - *, - index_type: VectorIndexType = ..., - wait_timeout: Optional[timedelta] = ..., num_bits: int = ..., + index_type: Literal[ + "IVF_FLAT", "IVF_SQ", "IVF_PQ", "IVF_RQ", "IVF_HNSW_SQ", "IVF_HNSW_PQ" + ] = ..., max_iterations: int = ..., sample_rate: int = ..., m: int = ..., ef_construction: int = ..., + *, + wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., train: bool = ..., target_partition_size: Optional[int] = ..., @@ -1501,22 +1838,30 @@ class Table(ABC): def create_index( self, - metric: DistanceType = "l2", + metric: str = "l2", num_partitions: Optional[int] = None, num_sub_vectors: Optional[int] = None, vector_column_name: str = VECTOR_COLUMN_NAME, replace: bool = True, accelerator: Optional[str] = None, index_cache_size: Optional[int] = None, - *, - index_type: VectorIndexType = "IVF_PQ", - wait_timeout: Optional[timedelta] = None, num_bits: int = 8, + index_type: Literal[ + "IVF_FLAT", + "IVF_SQ", + "IVF_PQ", + "IVF_RQ", + "IVF_HNSW_SQ", + "IVF_HNSW_PQ", + "IVF_HNSW_FLAT", + ] = "IVF_PQ", max_iterations: int = 50, sample_rate: int = 256, m: int = 20, ef_construction: int = 300, + *, config: Optional[IndexConfigType] = None, + wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, train: bool = True, target_partition_size: Optional[int] = None, @@ -1564,7 +1909,7 @@ class Table(ABC): ... "l2", vector_column_name="vector" ... ) """ - raise NotImplementedError + raise NotImplementedError("create_index is not supported for this table type") def create_index_async( self, @@ -1582,7 +1927,9 @@ class Table(ABC): be complete when returned; callers must not assume the index exists until :meth:`Job.wait` returns. """ - raise NotImplementedError + raise NotImplementedError( + "create_index_async is not supported for this table type" + ) def drop_index(self, name: str) -> None: """ @@ -1602,7 +1949,7 @@ class Table(ABC): Use [list_indices][lancedb.table.Table.list_indices] to find the names of the indices. """ - raise NotImplementedError + raise NotImplementedError("drop_index is not supported for this table type") def wait_for_index( self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300) @@ -1619,14 +1966,14 @@ class Table(ABC): timeout: timedelta Timeout to wait for asynchronous indexing. The default is 5 minutes. """ - raise NotImplementedError + raise NotImplementedError("wait_for_index is not supported for this table type") @abstractmethod def stats(self) -> TableStatistics: """ Retrieve table and fragment statistics. """ - raise NotImplementedError + raise NotImplementedError("stats is not supported for this table type") @abstractmethod def create_scalar_index( @@ -1691,7 +2038,9 @@ class Table(ABC): ``my_col = 0 OR not_indexed = 1`` will not be able to use any scalar index on ``my_col``. """ - raise NotImplementedError + raise NotImplementedError( + "create_scalar_index is not supported for this table type" + ) def create_fts_index( self, @@ -1817,7 +2166,9 @@ class Table(ABC): ``LANCE_LANGUAGE_MODEL_HOME`` to override the default platform data directory under ``lance/language_models``. """ - raise NotImplementedError + raise NotImplementedError( + "create_fts_index is not supported for this table type" + ) @abstractmethod def add( @@ -1832,6 +2183,10 @@ class Table(ABC): ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. + Plain binary values are cast into blob columns using the table's schema. + To construct Arrow record batches explicitly, use + [blob_array][lancedb.schema.blob_array]. + Parameters ---------- data: DATA @@ -1847,8 +2202,8 @@ class Table(ABC): "append" and "overwrite". Overwrite adopts explicitly declared blob layouts, while inferred bytes retain the existing blob v2 fields. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. - One of "error", "drop", "fill". + How to handle vectors with incorrect sizes, NaNs, or null elements. + One of "error", "drop", "fill", "null". fill_value: float, default 0. The value to use when filling vectors. Only used if on_bad_vectors="fill". progress: bool, callable, or tqdm-like, optional @@ -1891,7 +2246,7 @@ class Table(ABC): AddResult An object containing the new version number of the table after adding data. """ - raise NotImplementedError + raise NotImplementedError("add is not supported for this table type") def merge_insert(self, on: Union[str, Iterable[str]]) -> LanceMergeInsertBuilder: """ @@ -1967,6 +2322,7 @@ class Table(ABC): query_type: QueryType = "auto", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceQueryBuilder: """Create a search query to find the nearest neighbors of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/) @@ -2043,7 +2399,7 @@ class Table(ABC): - and also the "_distance" column which is the distance between the query vector and the returned vector. """ - raise NotImplementedError + raise NotImplementedError("search is not supported for this table type") @abstractmethod def take_offsets( @@ -2067,11 +2423,14 @@ class Table(ABC): ---------- offsets: list[int] The offsets to take. + with_row_id: bool, default False + If True, include the "_rowid" column in the results. Returns ------- - pa.RecordBatch - A record batch containing the rows at the given offsets. + LanceTakeQueryBuilder + A query builder that can be executed to get the rows at the given + offsets. """ def __getitems__(self, offsets: list[int]) -> pa.RecordBatch: @@ -2152,16 +2511,18 @@ class Table(ABC): ---------- row_ids: list[int] The row ids to take. + with_row_id: bool, default False + If True, include the "_rowid" column in the results. Returns ------- - AsyncTakeQuery - A query object that can be executed to get the rows. + LanceTakeQueryBuilder + A query builder that can be executed to get the rows. """ @abstractmethod def blob_columns(self) -> list[str]: - """Names of blob v2 columns that can be fetched by row id. + """Names of blob v1 and v2 columns that can be fetched by row id. Struct-nested blobs use dotted paths. Blobs inside lists are omitted because a row id does not identify an individual list element. @@ -2175,6 +2536,7 @@ class Table(ABC): ) -> pa.LargeBinaryArray: """Materialize full blob bytes for ``column`` at the given rows. + LanceDB Embedded supports both legacy blob v1 and blob v2 columns. The result has the same length and order as ``row_ids``. Null blobs produce null slots; valid empty blobs produce ``b""``. @@ -2186,7 +2548,7 @@ class Table(ABC): Blobs inside lists cannot be fetched by row id yet. - Remote servers limit each request to 1024 row IDs and 64 MiB of blob + LanceDB Distributed 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`. @@ -2198,8 +2560,9 @@ class Table(ABC): column: str, requests: Sequence[Sequence[int]], ) -> pa.LargeBinaryArray: - """Materialize row-specific byte ranges from a blob v2 column. + """Materialize row-specific byte ranges from a blob column. + LanceDB Embedded supports both legacy blob v1 and blob v2 columns. Each request is a three-item ``(row_id, offset, length)`` sequence. Requests may be repeated or reordered, including multiple ranges for the same blob. @@ -2212,7 +2575,7 @@ class Table(ABC): results are returned. Row IDs can be obtained from a query with ``with_row_id(True)``. - Remote tables read the requested ranges through version-pinned blob + LanceDB Distributed reads the requested ranges through version-pinned blob handles using HTTP byte-range requests. """ @@ -2224,11 +2587,12 @@ class Table(ABC): ) -> "list[Optional[BlobFile]]": """Open lazy, seekable :class:`~lancedb._blob.BlobFile` handles. + LanceDB Embedded supports both legacy blob v1 and blob v2 columns. Prefer this over :meth:`fetch_blobs` for large payloads. ``row_ids`` is 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``. Remote tables require LanceDB Cloud server 0.5.0 or newer. + ``None``. LanceDB Distributed requires server version 0.5.0 or newer. ``_rowid`` values stay valid after compaction when the table has stable row ids. @@ -2236,6 +2600,44 @@ class Table(ABC): handles are returned. """ + @abstractmethod + def open_blob_file( + self, descriptor: Union[dict, pa.StructScalar, None] + ) -> Optional[BlobFile]: + """Open a seekable file from a SQL ``blob_descriptor`` result. + + Accepts the descriptor dictionary or an Arrow struct scalar. Its source + pins the table version, branch, column and row identity, so opening does + not change this table's checkout. Null descriptors return ``None``. + Payload bytes load only when the returned handle is read. An external + blob with an unspecified size may require a metadata request on opening. + + ```python + rows = db.execute_query( + "SELECT blob_descriptor(video) AS video FROM videos" + ).read_all() + with videos.open_blob_file(rows["video"][0]) as video: + header = video.read(4096) + ``` + """ + + def open_blob_files(self, descriptors: Iterable) -> Iterator[Optional[BlobFile]]: + """Iterate over lazy files from descriptor dictionaries or Arrow scalars. + + Accepts an Arrow array/chunked array or any iterable. Opens each handle + as iteration advances, preserving input order and nulls as ``None``. + Close each non-null handle after use, normally with a ``with`` block. + + ```python + for video in videos.open_blob_files(rows["video"]): + if video is not None: + with video: + header = video.read(4096) + ``` + """ + for descriptor in descriptors: + yield self.open_blob_file(descriptor) + @abstractmethod def _execute_query( self, @@ -2324,7 +2726,7 @@ class Table(ABC): x vector 0 3 [5.0, 6.0] """ - raise NotImplementedError + raise NotImplementedError("delete is not supported for this table type") @abstractmethod def update( @@ -2391,7 +2793,7 @@ class Table(ABC): 1 4 [5.0, 6.0] 2 3 [10.0, 10.0] """ - raise NotImplementedError + raise NotImplementedError("update is not supported for this table type") @abstractmethod def cleanup_old_versions( @@ -2427,8 +2829,8 @@ class Table(ABC): Notes ----- - This function is not available in LanceDb Cloud (since LanceDB - Cloud manages cleanup for you automatically) + This function is not available in LanceDB Distributed, which manages + cleanup for you automatically. """ @abstractmethod @@ -2449,8 +2851,8 @@ class Table(ABC): Notes ----- - This function is not available in LanceDB Cloud (since LanceDB - Cloud manages compaction for you automatically) + This function is not available in LanceDB Distributed, which manages + compaction for you automatically. """ @abstractmethod @@ -2460,6 +2862,7 @@ class Table(ABC): cleanup_older_than: Optional[timedelta] = None, delete_unverified: bool = False, retrain: bool = False, + compaction_options: Optional[CompactionOptions] = None, ): """ Optimize the on-disk data and indices for better performance. @@ -2499,6 +2902,11 @@ class Table(ABC): retrain: bool, default False This parameter is no longer used and is deprecated. + compaction_options: CompactionOptions, optional + Options that control file compaction. For large rows, derive a lower + ``target_rows_per_fragment`` from the expected row size to bound later + passes. This does not cap the first pass over an existing oversized + fragment; see [CompactionOptions][lancedb.table.CompactionOptions]. Notes ----- @@ -2530,8 +2938,12 @@ 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. For remote tables, - this means the same tokenizer model files must also exist locally. + rebuilt in the client process from index metadata. In LanceDB Distributed, + 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 server's index produces. If the model files are + missing, an error naming the tokenizer is raised. """ @abstractmethod @@ -2561,6 +2973,8 @@ class Table(ABC): | None = None, *, computed: Dict[str, str] | None = None, + auto_refresh_enabled: bool | None = None, + auto_refresh_interval_seconds: int | None = None, ): """ Add new columns with defined values. @@ -2580,9 +2994,13 @@ class Table(ABC): or named-struct result in the named table column. A bare named-struct application expands its ordered result fields as one atomic binding; aliases come from ``rename(columns=...)``. - Function columns are supported only on LanceDB Cloud and - Enterprise. + Function columns are supported only in LanceDB + Distributed. 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. + A mapping from output column names to SQL expressions derives each output field from its expression. A direct projection of a Blob v2 field inherits Blob v2 semantics; other expressions derive their @@ -2600,11 +3018,21 @@ class Table(ABC): While a declaration reads a column, that column cannot be renamed, retyped or dropped. - On LanceDB Cloud and Enterprise the expression is planned by the + In LanceDB Distributed 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``. + auto_refresh_enabled: bool, optional + Enable automatic refresh for each declared computed output. Defaults + to True. LanceDB Embedded stores this option; scheduling requires a + server. + auto_refresh_interval_seconds: int, optional + Positive minimum interval after a successful refresh, in seconds. + When omitted, the server determines when to refresh. Applies to every + computed output in this call. + Scheduling options require computed or Function columns. + Returns ------- AddColumnsResult @@ -2615,11 +3043,11 @@ class Table(ABC): >>> import lancedb >>> db = lancedb.connect("./.lancedb") >>> table = db.create_table("computed_demo", [{"x": 1}, {"x": 2}]) - >>> table.add_columns(computed={"doubled": "x * 2"}) + >>> table.add_columns(computed={"doubled": "x * 2"}) # doctest: +SKIP AddColumnsResult(version=2) - >>> table.refresh_column("doubled") + >>> table.refresh_column("doubled") # doctest: +SKIP RefreshColumnResult(rows_filled=2, version=4) - >>> table.to_arrow().sort_by("x").to_pandas() + >>> table.to_arrow().sort_by("x").to_pandas() # doctest: +SKIP x doubled 0 1 2 1 2 4 @@ -2630,12 +3058,16 @@ class Table(ABC): """ Fill the rows of a computed column that hold no value yet. + Local refresh requires the ``experimental-functions`` Cargo feature + in a source build. Published packages leave it disabled. + Declared with ``add_columns(computed=...)``, a column starts empty and gets its values here. 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. - Local tables only: a remote refresh runs as a server job, through + LanceDB Embedded only. In LanceDB Distributed, a refresh runs as a + server job, through [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Parameters @@ -2656,11 +3088,15 @@ class Table(ABC): 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. + 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. On local tables the job runs in-process; on - LanceDB Cloud and Enterprise it is the server's backfill job. + than failing the job. In LanceDB Embedded the job runs in-process; in + LanceDB Distributed it is the server's backfill job. Returns ------- @@ -2673,13 +3109,13 @@ class Table(ABC): >>> import lancedb >>> db = lancedb.connect("./.lancedb") >>> table = db.create_table("computed_job_demo", [{"x": 1}, {"x": 2}]) - >>> table.add_columns(computed={"doubled": "x * 2"}) + >>> table.add_columns(computed={"doubled": "x * 2"}) # doctest: +SKIP AddColumnsResult(version=2) - >>> job = table.refresh_column_async("doubled") - >>> result = job.wait() - >>> result.rows_assigned + >>> job = table.refresh_column_async("doubled") # doctest: +SKIP + >>> result = job.wait() # doctest: +SKIP + >>> result.rows_assigned # doctest: +SKIP 2 - >>> job.status() + >>> job.status() # doctest: +SKIP 'finished' """ @@ -2696,7 +3132,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 Cloud and Enterprise only; reading errors + detail was capped. LanceDB Distributed only; reading errors needs read access to the table, since a message carries the value that failed. @@ -2782,8 +3218,6 @@ class Table(ABC): - "lancedb:description": for a human-readable description of a field. - ``"lancedb:tag:"`` for a user-defined key-value tag, where the suffix names the tag category; e.g. "lancedb:tag:model": "clip". - - "lancedb:logical-column" for a column grouping; e.g. "feature_v1" - and "feature_v2" might be in the same logical column. - "lancedb:status" for status options ("production", "candidate", "deprecated", "archived") to designate the current life cycle state of this column. @@ -2794,6 +3228,29 @@ class Table(ABC): version: the new table version after the update. """ + @deprecation.deprecated( + deprecated_in="0.33.1", + current_version=__version__, + details="Use update_field_metadata() instead.", + ) + def replace_field_metadata(self, field_name: str, new_metadata: Dict[str, str]): + """Replace all metadata of a field in the schema. + + .. deprecated:: 0.33.1 + Use [update_field_metadata][lancedb.table.Table.update_field_metadata] + with ``replace=True`` instead. + + Parameters + ---------- + field_name: str + The name of the field whose metadata is replaced. + new_metadata: dict + The new metadata, replacing all existing keys. + """ + self.update_field_metadata( + {"path": field_name, "metadata": new_metadata, "replace": True} + ) + @abstractmethod def drop_columns(self, columns: Iterable[str]) -> DropColumnsResult: """ @@ -3003,13 +3460,6 @@ class LanceTable(Table): """Return the namespace path of the table.""" return self._namespace_path - @property - def id(self) -> str: - """Return the full identifier of the table (namespace$name).""" - if self._namespace_path: - return "$".join(self._namespace_path + [self.name]) - return self.name - @classmethod async def from_inner(cls, tbl: LanceDBTable): from .db import AsyncConnection, LanceDBConnection @@ -3131,11 +3581,21 @@ class LanceTable(Table): """Get the current version of the table""" return LOOP.run(self._table.version()) - def take_offsets(self, offsets: list[int]) -> LanceTakeQueryBuilder: - return LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + def take_offsets( + self, offsets: list[int], *, with_row_id: bool = False + ) -> LanceTakeQueryBuilder: + builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + if with_row_id: + builder.with_row_id() + return builder - def take_row_ids(self, row_ids: list[int]) -> LanceTakeQueryBuilder: - return LanceTakeQueryBuilder(self._table.take_row_ids(row_ids)) + def take_row_ids( + self, row_ids: list[int], *, with_row_id: bool = False + ) -> LanceTakeQueryBuilder: + builder = LanceTakeQueryBuilder(self._table.take_row_ids(row_ids)) + if with_row_id: + builder.with_row_id() + return builder def blob_columns(self) -> list[str]: return LOOP.run(self._table.blob_columns()) @@ -3161,6 +3621,11 @@ class LanceTable(Table): ) -> "list[Optional[BlobFile]]": return LOOP.run(self._table.fetch_blob_files(column, row_ids)) + def open_blob_file( + self, descriptor: Union[dict, pa.StructScalar, None] + ) -> Optional[BlobFile]: + return LOOP.run(self._table.open_blob_file(descriptor)) + @property def tags(self) -> Tags: """Tag management for the table. @@ -3589,7 +4054,9 @@ class LanceTable(Table): # Handle accelerator through pylance if accelerator is not None: - self.to_lance().create_index( + dataset = self.to_lance() + _validate_index_accelerator(accelerator) + dataset.create_index( column=column, index_type=index_type, metric=metric, @@ -3614,6 +4081,8 @@ class LanceTable(Table): acc = getattr(config, "accelerator", None) if acc is not None: # Dispatch to pylance for GPU acceleration + dataset = self.to_lance() + _validate_index_accelerator(acc) index_type_map = { "IvfFlat": "IVF_FLAT", "IvfSq": "IVF_SQ", @@ -3625,7 +4094,12 @@ class LanceTable(Table): cfg_type = type(config).__name__ lance_index_type = index_type_map.get(cfg_type, "IVF_PQ") - self.to_lance().create_index( + quantization_kwargs = {} + num_bits = getattr(config, "num_bits", 8) + if num_bits is not None: + quantization_kwargs["num_bits"] = num_bits + + dataset.create_index( column=column, index_type=lance_index_type, metric=getattr(config, "distance_type", "l2"), @@ -3633,12 +4107,12 @@ class LanceTable(Table): num_sub_vectors=getattr(config, "num_sub_vectors", None), replace=replace, accelerator=acc, - num_bits=getattr(config, "num_bits", 8), m=getattr(config, "m", 20), ef_construction=getattr(config, "ef_construction", 300), target_partition_size=getattr( config, "target_partition_size", None ), + **quantization_kwargs, ) self.checkout_latest() return @@ -3682,130 +4156,6 @@ class LanceTable(Table): ) ) - def _is_legacy_create_index_call( - self, - first_arg: str, - config: Optional[IndexConfigType], - num_partitions: Optional[int], - num_sub_vectors: Optional[int], - vector_column_name: str, - accelerator: Optional[str], - index_cache_size: Optional[int], - ) -> bool: - """Detect if this is a legacy create_index call.""" - # If config is provided, it's definitely the new API - if config is not None: - return False - - # If old-style parameters were explicitly set, it's legacy - if any( - x is not None - for x in (num_partitions, num_sub_vectors, accelerator, index_cache_size) - ): - return True - - # If vector_column_name differs from default, it's legacy - if vector_column_name != VECTOR_COLUMN_NAME: - return True - - # If first arg is a known metric, assume legacy - if first_arg.lower() in KNOWN_METRICS: - return True - - # Otherwise assume new API - return False - - def _build_vector_config_from_legacy_params( - self, - metric: str, - index_type: str, - num_partitions: Optional[int], - num_sub_vectors: Optional[int], - num_bits: int, - max_iterations: int, - sample_rate: int, - m: int, - ef_construction: int, - target_partition_size: Optional[int], - accelerator: Optional[str], - ) -> IndexConfigType: - """Build an index config object from legacy parameters.""" - if index_type == "IVF_FLAT": - return IvfFlat( - distance_type=metric, - num_partitions=num_partitions, - max_iterations=max_iterations, - sample_rate=sample_rate, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_SQ": - return IvfSq( - distance_type=metric, - num_partitions=num_partitions, - max_iterations=max_iterations, - sample_rate=sample_rate, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_PQ": - return IvfPq( - distance_type=metric, - num_partitions=num_partitions, - num_sub_vectors=num_sub_vectors, - num_bits=num_bits, - max_iterations=max_iterations, - sample_rate=sample_rate, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_RQ": - return IvfRq( - distance_type=metric, - num_partitions=num_partitions, - num_bits=num_bits, - max_iterations=max_iterations, - sample_rate=sample_rate, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_HNSW_PQ": - return HnswPq( - distance_type=metric, - num_partitions=num_partitions, - num_sub_vectors=num_sub_vectors, - num_bits=num_bits, - max_iterations=max_iterations, - sample_rate=sample_rate, - m=m, - ef_construction=ef_construction, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_HNSW_SQ": - return HnswSq( - distance_type=metric, - num_partitions=num_partitions, - max_iterations=max_iterations, - sample_rate=sample_rate, - m=m, - ef_construction=ef_construction, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_HNSW_FLAT": - return HnswFlat( - distance_type=metric, - num_partitions=num_partitions, - max_iterations=max_iterations, - sample_rate=sample_rate, - m=m, - ef_construction=ef_construction, - target_partition_size=target_partition_size, - ) - else: - raise ValueError(f"Unknown index type {index_type}") - def drop_index(self, name: str) -> None: """ Drops an index from the table @@ -3845,7 +4195,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 on remote tables. + Currently only supported in LanceDB Distributed. This call initiates prewarming and returns once the request is accepted. It is idempotent and safe to call from multiple clients concurrently. @@ -3916,6 +4266,7 @@ class LanceTable(Table): *, replace: bool = True, index_type: ScalarIndexType = "BTREE", + wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, ): """Create a scalar index on a column. @@ -3924,6 +4275,13 @@ class LanceTable(Table): Use :meth:`create_index` with a BTree, Bitmap, or LabelList config instead. Example: ``table.create_index("column", config=BTree())`` """ + if index_type == "scalar": + warnings.warn( + 'index_type="scalar" is deprecated; use "BTREE" instead', + DeprecationWarning, + stacklevel=2, + ) + index_type = "BTREE" if index_type == "BTREE": config = BTree() elif index_type == "BITMAP": @@ -3933,7 +4291,13 @@ class LanceTable(Table): else: raise ValueError(f"Unknown index type {index_type}") return LOOP.run( - self._table.create_index(column, replace=replace, config=config, name=name) + self._table.create_index( + column, + replace=replace, + config=config, + wait_timeout=wait_timeout, + name=name, + ) ) @deprecation.deprecated( @@ -3965,6 +4329,7 @@ class LanceTable(Table): prefix_only: bool = False, block_size: int = 128, document_granularity: DocumentGranularity = DocumentGranularity.ROW, + wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, ): """Create a full-text search index on a column. @@ -4029,6 +4394,7 @@ class LanceTable(Table): replace=replace, config=config, name=name, + wait_timeout=wait_timeout, ) ) except (ValueError, RuntimeError) as e: @@ -4039,69 +4405,6 @@ class LanceTable(Table): ) raise e - @staticmethod - def infer_tokenizer_configs(tokenizer_name: str) -> dict: - if tokenizer_name == "default": - return { - "base_tokenizer": "simple", - "language": "English", - "max_token_length": 40, - "lower_case": True, - "stem": False, - "remove_stop_words": False, - "ascii_folding": False, - "ngram_min_length": 3, - "ngram_max_length": 3, - "prefix_only": False, - } - elif tokenizer_name == "raw": - return { - "base_tokenizer": "raw", - "language": "English", - "max_token_length": None, - "lower_case": False, - "stem": False, - "remove_stop_words": False, - "ascii_folding": False, - "ngram_min_length": 3, - "ngram_max_length": 3, - "prefix_only": False, - } - elif tokenizer_name == "whitespace": - return { - "base_tokenizer": "whitespace", - "language": "English", - "max_token_length": None, - "lower_case": False, - "stem": False, - "remove_stop_words": False, - "ascii_folding": False, - "ngram_min_length": 3, - "ngram_max_length": 3, - "prefix_only": False, - } - - # or it's with language stemming with pattern like "en_stem" - if len(tokenizer_name) != 7: - raise ValueError(f"Invalid tokenizer name {tokenizer_name}") - lang = tokenizer_name[:2] - if tokenizer_name[-5:] != "_stem": - raise ValueError(f"Invalid tokenizer name {tokenizer_name}") - if lang not in lang_mapping: - raise ValueError(f"Invalid language code {lang}") - return { - "base_tokenizer": "simple", - "language": lang_mapping[lang], - "max_token_length": 40, - "lower_case": True, - "stem": True, - "remove_stop_words": False, - "ascii_folding": False, - "ngram_min_length": 3, - "ngram_max_length": 3, - "prefix_only": False, - } - def add( self, data: DATA, @@ -4126,7 +4429,7 @@ class LanceTable(Table): "append" and "overwrite". Overwrite adopts explicitly declared blob layouts, while inferred bytes retain the existing blob v2 fields. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. + How to handle vectors with incorrect sizes, NaNs, or null elements. One of "error", "drop", "fill", "null". fill_value: float, default 0. The value to use when filling vectors. Only used if on_bad_vectors="fill". @@ -4141,7 +4444,7 @@ class LanceTable(Table): using too much memory. allow_external_blob_outside_bases: bool, default False Allow blob URIs outside registered bases. See :meth:`Table.add`. - Local tables only. + LanceDB Embedded only. Returns ------- @@ -4252,6 +4555,7 @@ class LanceTable(Table): query_type: Literal["vector"] = "vector", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceVectorQueryBuilder: ... @overload @@ -4262,6 +4566,7 @@ class LanceTable(Table): query_type: Literal["fts"] = "fts", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceFtsQueryBuilder: ... @overload @@ -4274,6 +4579,7 @@ class LanceTable(Table): query_type: Literal["hybrid"] = "hybrid", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceHybridQueryBuilder: ... @overload @@ -4284,6 +4590,7 @@ class LanceTable(Table): query_type: QueryType = "auto", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceEmptyQueryBuilder: ... def search( @@ -4295,6 +4602,7 @@ class LanceTable(Table): query_type: QueryType = "auto", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceQueryBuilder: """Create a search query to find the nearest neighbors of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/) @@ -4379,6 +4687,7 @@ class LanceTable(Table): vector_column_name=vector_column_name, ordering_field_name=ordering_field_name, fts_columns=fts_columns or [], + fast_search=fast_search, ) @classmethod @@ -4443,7 +4752,7 @@ class LanceTable(Table): otherwise just open the table, it will not add the provided data but will validate against any schema that's specified. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. + How to handle vectors with incorrect sizes, NaNs, or null elements. One of "error", "drop", "fill", "null". fill_value: float, default 0. The value to use when filling vectors. Only used if on_bad_vectors="fill". @@ -4696,6 +5005,7 @@ class LanceTable(Table): cleanup_older_than: Optional[timedelta] = None, delete_unverified: bool = False, retrain: bool = False, + compaction_options: Optional[CompactionOptions] = None, ): """ Optimize the on-disk data and indices for better performance. @@ -4735,6 +5045,11 @@ class LanceTable(Table): retrain: bool, default False This parameter is no longer used and is deprecated. + compaction_options: CompactionOptions, optional + Options that control file compaction. For large rows, derive a lower + ``target_rows_per_fragment`` from the expected row size to bound later + passes. This does not cap the first pass over an existing oversized + fragment; see [CompactionOptions][lancedb.table.CompactionOptions]. Notes ----- @@ -4748,6 +5063,7 @@ class LanceTable(Table): self._table._do_optimize( _optimize_cleanup_since_ms(cleanup_older_than, retrain), delete_unverified, + compaction_options, ) ) @@ -4770,8 +5086,12 @@ 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. For remote tables, - this means the same tokenizer model files must also exist locally. + rebuilt in the client process from index metadata. In LanceDB Distributed, + 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 server's index produces. If the model files are + missing, an error naming the tokenizer is raised. """ return LOOP.run( self._table.tokenize(query, column=column, index_name=index_name) @@ -4803,8 +5123,17 @@ class LanceTable(Table): | None = None, *, computed: Dict[str, str] | None = None, + auto_refresh_enabled: bool | None = None, + auto_refresh_interval_seconds: int | None = None, ) -> AddColumnsResult: - return LOOP.run(self._table.add_columns(transforms, computed=computed)) + return LOOP.run( + self._table.add_columns( + transforms, + computed=computed, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, + ) + ) def refresh_column(self, column: str) -> "RefreshColumnResult": """Fill a computed column's unfilled rows and recompute those whose @@ -5119,7 +5448,7 @@ def _handle_bad_vector_column( vector_column_name: str The name of the vector column. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. + How to handle vectors with incorrect sizes, NaNs, or null elements. One of "error", "drop", "fill", "null". fill_value: float, default 0.0 The value to use when filling vectors. Only used if on_bad_vectors="fill". @@ -5138,7 +5467,8 @@ def _handle_bad_vector_column( data = data.set_column(position, vector_column_name, vec_arr) if expected_value_type is not None and ( - pa.types.is_integer(vec_arr.type.value_type) + pa.types.is_null(vec_arr.type.value_type) + or pa.types.is_integer(vec_arr.type.value_type) or pa.types.is_unsigned_integer(vec_arr.type.value_type) ): vec_arr = pa.array(vec_arr.to_pylist(), type=pa.list_(expected_value_type)) @@ -5182,7 +5512,7 @@ def _handle_bad_vector_column( ) else: raise ValueError( - f"Vector column '{vector_column_name}' has NaNs. " + f"Vector column '{vector_column_name}' has NaNs or null values. " "Set on_bad_vectors='drop' to remove them, " "set on_bad_vectors='fill' and fill_value= to replace them, " "or set on_bad_vectors='null' to replace them with null." @@ -5218,29 +5548,11 @@ def _fill_bad_vector_values( arr = arr.combine_chunks() # A fixed-size slice truncates long vectors and pads short vectors with nulls. - # Slice an array marking the original child nulls in parallel so padding nulls - # can be distinguished from null values that were already present. + # Both padding and existing null elements need to be filled. sliced = pc.list_slice(arr, 0, dim, return_fixed_size_list=True) - child_nulls = pc.is_null(arr.values) - parent_nulls = pc.is_null(arr) - if pa.types.is_list(arr.type): - original_child_nulls = pa.ListArray.from_arrays( - arr.offsets, child_nulls, mask=parent_nulls - ) - elif pa.types.is_large_list(arr.type): - original_child_nulls = pa.LargeListArray.from_arrays( - arr.offsets, child_nulls, mask=parent_nulls - ) - else: - original_child_nulls = pa.FixedSizeListArray.from_arrays( - child_nulls, arr.type.list_size, mask=parent_nulls - ) - sliced_child_nulls = pc.list_slice( - original_child_nulls, 0, dim, return_fixed_size_list=True - ) - needs_fill = pc.is_null(sliced_child_nulls.values) values = sliced.values + needs_fill = pc.is_null(values) if pa.types.is_floating(values.type): values_for_nan_check = ( values.cast(pa.float32()) if pa.types.is_float16(values.type) else values @@ -5254,6 +5566,7 @@ def _fill_bad_vector_values( def has_nan_values(arr: Union[pa.ListArray, pa.ChunkedArray]) -> pa.BooleanArray: + """Find vectors with NaN or null components, including pandas-converted NaNs.""" if isinstance(arr, pa.ChunkedArray): values = pa.chunked_array([chunk.flatten() for chunk in arr.chunks]) else: @@ -5264,7 +5577,15 @@ def has_nan_values(arr: Union[pa.ListArray, pa.ChunkedArray]) -> pa.BooleanArray values_has_nan = pc.is_nan(values.cast(pa.float32())) else: values_has_nan = pc.is_nan(values) + # Pandas represents NaN components as Arrow nulls. is_nan returns null + # for these values, so count them as invalid before filtering parent indices. + values_has_nan = pc.fill_null(values_has_nan, True) values_indices = pc.list_parent_indices(arr) + if arr.null_count: + # Match flatten(), which excludes child spans under null parent lists. + values_indices = pc.filter( + values_indices, pc.take(pc.is_valid(arr), values_indices) + ) has_nan_indices = pc.unique(pc.filter(values_indices, values_has_nan)) indices = pa.array(range(len(arr)), type=pa.uint32()) return pc.is_in(indices, has_nan_indices) @@ -5315,6 +5636,12 @@ def _infer_target_schema( # Use the most common length of the list as the dimensions dim = _modal_list_size(peeked.column(i)) + if dim is None: + # Every list entry is null (e.g. embeddings not computed yet), + # so the dimension is unknowable. Leave the column as a + # variable-length list instead of guessing a fixed size. + continue + # Determine target type based on value type if pa.types.is_floating(field.type.value_type): target_type = pa.list_(pa.float32(), dim) @@ -5347,6 +5674,7 @@ def _infer_target_schema( field.name, # preserve original field name target_type, nullable=field.nullable, + metadata=field.metadata, ) schema = schema.set(i, new_field) @@ -5354,9 +5682,14 @@ def _infer_target_schema( return schema, reader -def _modal_list_size(arr: Union[pa.ListArray, pa.ChunkedArray]) -> int: - # Use the most common length of the list as the dimensions - return pc.mode(pc.list_value_length(arr))[0].as_py()["mode"] +def _modal_list_size(arr: Union[pa.ListArray, pa.ChunkedArray]) -> Optional[int]: + # Use the most common length of the list as the dimensions. pyarrow's + # `mode` skips nulls, so an all-null column yields an empty result; return + # None in that case so the caller can keep a variable-length list. + modes = pc.mode(pc.list_value_length(arr)) + if len(modes) == 0: + return None + return modes[0].as_py()["mode"] def _infer_vector_dim(arr: Union[pa.Array, pa.ChunkedArray]) -> Optional[int]: @@ -5564,12 +5897,12 @@ class AsyncTable: via [`set_unenforced_primary_key`]; bucket sharding additionally requires it to be the single column being bucketed. - By default the RTE maintains every index on the table, resolved - here — a snapshot, so an index created afterwards needs the spec unset - and set again. This fails if one cannot be maintained; name the set - with ``with_maintained_indexes`` to install anyway. That pins an exact - set (a still-building index is rejected, not omitted); ``[]`` maintains - none. + By default the RTE maintains every index on the table, re-read as the + table changes, so an index created later is maintained too; one of a + kind the RTE cannot mirror is skipped. Name the set with + ``with_maintained_indexes`` to pin it instead: each name must already + exist and be maintainable (a still-building index is rejected, not + omitted); ``[]`` maintains none. Parameters ---------- @@ -5588,7 +5921,8 @@ class AsyncTable: """Remove the RTEWriteSpec from this table. Reverts to the standard `merge_insert` write path. Errors if no spec - is currently set. + is currently set, or if the RTE still holds rows that have not been + merged into the base table, since removing it would drop them. """ await self._inner.disable_rte() @@ -5695,10 +6029,10 @@ class AsyncTable: async def schema(self) -> pa.Schema: """The [Arrow Schema](https://arrow.apache.org/docs/python/api/datatypes.html#) - of this Table + of this Table. Blob v2 fields retain their Arrow extension type. """ - return await self._inner.schema() + return _restore_blob_extensions(await self._inner.schema()) async def embedding_functions(self) -> Dict[str, EmbeddingFunctionConfig]: """ @@ -5747,9 +6081,10 @@ class AsyncTable: return AsyncQuery(self._inner.query(), self) async def to_lance(self, **kwargs) -> lance.LanceDataset: - """Return the Lance dataset backing a local table. + """Return the Lance dataset backing a LanceDB Embedded table. - Remote tables cannot be opened as Lance datasets by the client. Use + LanceDB Distributed 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. @@ -5770,7 +6105,7 @@ class AsyncTable: """ if not self._inner._is_native(): raise NotImplementedError( - "to_lance() is not supported for remote tables; " + "to_lance() is not supported in LanceDB Distributed; " "query the server instead" ) @@ -5803,7 +6138,7 @@ class AsyncTable: Parameters ---------- blob_mode: str, default "lazy" - Controls how Lance blob columns are returned. Remote tables support + Controls how Lance blob columns are returned. LanceDB Distributed supports "descriptions"; "bytes" and "lazy" are not yet supported. **kwargs Forwarded to PyArrow / Lance pandas conversion. @@ -6047,7 +6382,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 on remote tables. + Currently only supported in LanceDB Distributed. This call initiates prewarming and returns once the request is accepted. It is idempotent and safe to call from multiple clients concurrently. @@ -6091,8 +6426,8 @@ class AsyncTable: """ Get the table URI (storage location). - For remote tables, this fetches the location from the server via describe. - For local tables, this returns the dataset URI. + In LanceDB Distributed, this fetches the location from the server via describe. + In LanceDB Embedded, this returns the dataset URI. Returns ------- @@ -6145,6 +6480,10 @@ class AsyncTable: ) -> AddResult: """Add more data to the [AsyncTable][lancedb.table.AsyncTable]. + Plain binary values are cast into blob columns using the table's schema. + To construct Arrow record batches explicitly, use + [blob_array][lancedb.schema.blob_array]. + Parameters ---------- data: DATA @@ -6160,7 +6499,7 @@ class AsyncTable: "append" and "overwrite". Overwrite adopts explicitly declared blob layouts, while inferred bytes retain the existing blob v2 fields. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. + How to handle vectors with incorrect sizes, NaNs, or null elements. One of "error", "drop", "fill", "null". fill_value: float, default 0. The value to use when filling vectors. Only used if on_bad_vectors="fill". @@ -6175,7 +6514,7 @@ class AsyncTable: using too much memory. allow_external_blob_outside_bases: bool, default False Allow blob URIs outside registered bases. See :meth:`Table.add`. - Local tables only. + LanceDB Embedded only. """ schema = await self.schema() @@ -6193,8 +6532,12 @@ class AsyncTable: if mode == "overwrite": # For overwrite, apply the same preprocessing as create_table # so vector columns are inferred as FixedSizeList. - data, _ = sanitize_create_table( - data, None, on_bad_vectors=on_bad_vectors, fill_value=fill_value + data, _ = await asyncio.to_thread( + sanitize_create_table, + data, + None, + on_bad_vectors=on_bad_vectors, + fill_value=fill_value, ) if blob_v2_column_paths(schema): # Plain bytes cannot be inferred as blob v2. Keep matching blob @@ -6204,7 +6547,8 @@ class AsyncTable: elif on_bad_vectors != "error" or ( schema.metadata is not None and b"embedding_functions" in schema.metadata ): - data = _sanitize_data( + data = await asyncio.to_thread( + _sanitize_data, data, schema, metadata=schema.metadata, @@ -6213,7 +6557,10 @@ class AsyncTable: allow_subschema=True, ) _register_optional_converters() - data = to_scannable(data) + # Converting an iterator peeks at its first item. A synchronous query in + # that iterator schedules work on LOOP, so peeking on LOOP's own thread + # would deadlock waiting for itself. + data = await asyncio.to_thread(to_scannable, data) progress, owns = _normalize_progress(progress) try: return await self._inner.add( @@ -6852,6 +7199,8 @@ class AsyncTable: | None = None, *, computed: dict[str, str] | None = None, + auto_refresh_enabled: bool | None = None, + auto_refresh_interval_seconds: int | None = None, ) -> AddColumnsResult: """ Add new columns with defined values. @@ -6869,9 +7218,13 @@ class AsyncTable: or named-struct result in the named table column. A bare named-struct application expands its ordered result fields as one atomic binding; aliases come from ``rename(columns=...)``. - Function columns are supported only on LanceDB Cloud and - Enterprise. + Function columns are supported only in LanceDB + Distributed. 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. + A mapping from output column names to SQL expressions derives each output field from its expression. A direct projection of a Blob v2 field inherits Blob v2 semantics; other expressions derive their @@ -6888,15 +7241,49 @@ class AsyncTable: While a declaration reads a column, that column cannot be renamed, retyped or dropped. - On LanceDB Cloud and Enterprise the expression is planned by + In LanceDB Distributed 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. + 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 + to refresh. Unchanged inputs do + not force recomputation. Applies to every declared computed output. + These options cannot be used with one-time transforms or ordinary + all-null columns. + + Examples + -------- + >>> await table.add_columns( # doctest: +SKIP + ... computed={"total": "price * quantity"}, + ... auto_refresh_enabled=True, + ... auto_refresh_interval_seconds=300, + ... ) + Returns ------- AddColumnsResult version: the new version number of the table after adding columns. """ + if auto_refresh_enabled is not None and type(auto_refresh_enabled) is not bool: + raise ValueError("auto_refresh_enabled must be a boolean") + if auto_refresh_interval_seconds is not None and ( + type(auto_refresh_interval_seconds) is not int + or not 0 < auto_refresh_interval_seconds <= (2**64 - 1) // 1000 + ): + raise ValueError( + "auto_refresh_interval_seconds must be a positive integer " + "no greater than u64::MAX / 1000" + ) + options_supplied = ( + auto_refresh_enabled is not None + or auto_refresh_interval_seconds is not None + ) function_application = None function_output_name = None if isinstance(transforms, FunctionApplication): @@ -6920,7 +7307,10 @@ class AsyncTable: ) function_application._ensure_declarable() return await self._inner.add_function_columns( - function_application.to_canonical_json(), function_output_name + function_application.to_canonical_json(), + function_output_name, + auto_refresh_enabled, + auto_refresh_interval_seconds, ) if isinstance(transforms, pa.Field): @@ -6934,7 +7324,15 @@ class AsyncTable: raise ValueError( "add_columns cannot take both transforms and computed columns" ) - return await self._inner.add_computed_columns(list(computed.items())) + return await self._inner.add_computed_columns( + list(computed.items()), + auto_refresh_enabled, + auto_refresh_interval_seconds, + ) + if options_supplied: + raise ValueError( + "automatic refresh options require computed or Function columns" + ) if transforms is None: raise ValueError("add_columns requires transforms or computed columns") if isinstance(transforms, pa.Schema): @@ -6946,12 +7344,16 @@ class AsyncTable: """ Fill the rows of a computed column that hold no value yet. + Local refresh requires the ``experimental-functions`` Cargo feature + in a source build. Published packages leave it disabled. + Declared with ``add_columns(computed=...)``, a column starts empty and gets its values here. 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. - Local tables only: a remote refresh runs as a server job, through + LanceDB Embedded only. In LanceDB Distributed, a refresh runs as a + server job, through [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Parameters @@ -6978,7 +7380,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 Cloud and Enterprise only; reading errors + detail was capped. LanceDB Distributed only; reading errors needs read access to the table, since a message carries the value that failed. @@ -7016,11 +7418,15 @@ class AsyncTable: 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. + 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. On local tables the job runs - in-process; on LanceDB Cloud and Enterprise it is the server's + rather than failing the job. In LanceDB Embedded the job runs + in-process; in LanceDB Distributed it is the server's backfill job. Returns @@ -7041,7 +7447,7 @@ class AsyncTable: ... result = await job.wait() ... assert result.rows_assigned == 1 ... return await job.status() - >>> asyncio.run(refresh_in_background()) + >>> asyncio.run(refresh_in_background()) # doctest: +SKIP 'finished' """ return _typed_job( @@ -7185,7 +7591,9 @@ class AsyncTable: """ await self._inner.restore(version) - def take_offsets(self, offsets: list[int]) -> AsyncTakeQuery: + def take_offsets( + self, offsets: list[int], *, with_row_id: bool = False + ) -> AsyncTakeQuery: """ Take a list of offsets from the table. @@ -7203,15 +7611,23 @@ class AsyncTable: ---------- offsets: list[int] The offsets to take. + with_row_id: bool, default False + If True, include the "_rowid" column in the results. Returns ------- - pa.RecordBatch - A record batch containing the rows at the given offsets. + AsyncTakeQuery + A query object that can be executed to get the rows at the given + offsets. """ - return AsyncTakeQuery(self._inner.take_offsets(offsets), self) + query = AsyncTakeQuery(self._inner.take_offsets(offsets), self) + if with_row_id: + query.with_row_id() + return query - def take_row_ids(self, row_ids: list[int]) -> AsyncTakeQuery: + def take_row_ids( + self, row_ids: list[int], *, with_row_id: bool = False + ) -> AsyncTakeQuery: """ Take a list of row ids from the table. @@ -7232,13 +7648,18 @@ class AsyncTable: ---------- row_ids: list[int] The row ids to take. + with_row_id: bool, default False + If True, include the "_rowid" column in the results. Returns ------- AsyncTakeQuery A query object that can be executed to get the rows. """ - return AsyncTakeQuery(self._inner.take_row_ids(row_ids), self) + query = AsyncTakeQuery(self._inner.take_row_ids(row_ids), self) + if with_row_id: + query.with_row_id() + return query async def blob_columns(self) -> list[str]: return await self._inner.blob_columns() @@ -7269,6 +7690,36 @@ class AsyncTable: ) return _wrap_blob_files(handles) + async def open_blob_file( + self, descriptor: Union[dict, pa.StructScalar, None] + ) -> Optional[BlobFile]: + """Open a snapshot-bound descriptor as a seekable file. + + See [Table.open_blob_file][lancedb.table.Table.open_blob_file]. + """ + descriptor = _normalize_blob_descriptor(descriptor) + if descriptor is None: + return None + return BlobFile(await self._inner.open_blob_file(json.dumps(descriptor))) + + async def open_blob_files( + self, descriptors: Iterable + ) -> AsyncIterator[Optional[BlobFile]]: + """Asynchronously iterate over files in descriptor order, preserving nulls. + + Use ``async for file in table.open_blob_files(descriptors)``. Each + non-null file must be closed after use. + + ```python + async for video in videos.open_blob_files(rows["video"]): + if video is not None: + with video: + payload = await video.aread() + ``` + """ + for descriptor in descriptors: + yield await self.open_blob_file(descriptor) + @property def tags(self) -> AsyncTags: """Tag management for the dataset. @@ -7306,6 +7757,7 @@ class AsyncTable: cleanup_older_than: Optional[timedelta] = None, delete_unverified: bool = False, retrain=False, + compaction_options: Optional[CompactionOptions] = None, ) -> OptimizeStats: """ Optimize the on-disk data and indices for better performance. @@ -7345,6 +7797,11 @@ class AsyncTable: retrain: bool, default False This parameter is no longer used and is deprecated. + compaction_options: CompactionOptions, optional + Options that control file compaction. For large rows, derive a lower + ``target_rows_per_fragment`` from the expected row size to bound later + passes. This does not cap the first pass over an existing oversized + fragment; see [CompactionOptions][lancedb.table.CompactionOptions]. Notes ----- @@ -7357,14 +7814,19 @@ class AsyncTable: return await self._do_optimize( _optimize_cleanup_since_ms(cleanup_older_than, retrain), delete_unverified, + compaction_options, ) async def _do_optimize( - self, cleanup_since_ms: Optional[int], delete_unverified: bool + self, + cleanup_since_ms: Optional[int], + delete_unverified: bool, + compaction_options: Optional[CompactionOptions] = None, ) -> OptimizeStats: return await self._inner.optimize( cleanup_since_ms=cleanup_since_ms, delete_unverified=delete_unverified, + compaction_options=compaction_options, ) async def list_indices(self) -> Iterable[IndexConfig]: @@ -7386,8 +7848,12 @@ 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. For remote tables, - this means the same tokenizer model files must also exist locally. + rebuilt in the client process from index metadata. In LanceDB Distributed, + 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 server's index produces. If the model files are + missing, an error naming the tokenizer is raised. """ return await self._inner.tokenize(query, column=column, index_name=index_name) diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py index d4533887b..c37edcc6a 100644 --- a/python/python/lancedb/util.py +++ b/python/python/lancedb/util.py @@ -9,7 +9,7 @@ import math import os import pathlib import warnings -from datetime import date, datetime +from datetime import date, datetime, time, timedelta from decimal import Decimal from functools import singledispatch from typing import Tuple, Union, Optional, Any, List @@ -34,20 +34,20 @@ def safe_import_adlfs(): adlfs = safe_import_adlfs() -def get_uri_scheme(uri: str) -> str: +def get_uri_scheme(uri: Union[str, pathlib.Path]) -> str: """ Get the scheme of a URI. If the URI does not have a scheme, assume it is a file URI. Parameters ---------- - uri : str + uri : str or pathlib.Path The URI to parse. Returns ------- str: The scheme of the URI. """ - parsed = urlparse(uri) + parsed = urlparse(str(uri)) scheme = parsed.scheme if not scheme: scheme = "file" @@ -61,25 +61,26 @@ def get_uri_scheme(uri: str) -> str: return scheme -def get_uri_location(uri: str) -> str: +def get_uri_location(uri: Union[str, pathlib.Path]) -> str: """ Get the location of a URI. If the parameter is not a url, assumes it is just a path Parameters ---------- - uri : str + uri : str or pathlib.Path The URI to parse. Returns ------- str: Location part of the URL, without scheme """ - parsed = urlparse(uri) + uri_str = str(uri) + parsed = urlparse(uri_str) if len(parsed.scheme) == 1: # Windows drive names are parsed as the scheme # e.g. "c:\path" -> ParseResult(scheme="c", netloc="", path="/path", ...) # So we add special handling here for schemes that are a single character - return uri + return uri_str if not parsed.netloc: return parsed.path @@ -309,7 +310,16 @@ def _query_vector_dim(query: Optional[Any]) -> Optional[int]: if query.ndim == 0: return None return query.shape[-1] - if isinstance(query, list) and query: + if isinstance(query, (pa.Array, pa.ChunkedArray)): + if len(query) == 0: + return None + if pa.types.is_fixed_size_list(query.type): + return query.type.list_size + if pa.types.is_list(query.type) or pa.types.is_large_list(query.type): + first = query[0].as_py() + return len(first) if first is not None else None + return len(query) + if isinstance(query, (list, tuple)) and query: first = query[0] if isinstance(first, (list, tuple, np.ndarray)): return len(first) @@ -415,8 +425,31 @@ def _(value: date): return f"'{value.isoformat()}'" +@value_to_sql.register(time) +def _(value: time): + if value.utcoffset() is not None: + raise ValueError( + "time values with a timezone cannot be converted to SQL, " + "because Arrow time columns do not store one" + ) + # A plain string literal can be assigned to a time column but not compared with one. + return f"arrow_cast('{value.isoformat()}', 'Time64(Microsecond)')" + + +@value_to_sql.register(timedelta) +def _(value: timedelta): + # Lance does not accept INTERVAL literals, so cast the exact count of the + # smallest unit. pandas.Timedelta, a timedelta subclass, keeps nanoseconds. + nanoseconds = getattr(value, "value", None) + if isinstance(nanoseconds, int): + return f"arrow_cast({nanoseconds}, 'Duration(Nanosecond)')" + microseconds = value // timedelta(microseconds=1) + return f"arrow_cast({microseconds}, 'Duration(Microsecond)')" + + @value_to_sql.register(list) -def _(value: list): +@value_to_sql.register(tuple) +def _(value: Union[list, tuple]): return "[" + ", ".join(map(value_to_sql, value)) + "]" @@ -441,6 +474,35 @@ def _(value: pa.Scalar): return value_to_sql(value.as_py()) +_ARROW_TIME_UNITS = { + "s": "Second", + "ms": "Millisecond", + "us": "Microsecond", + "ns": "Nanosecond", +} + + +@value_to_sql.register(pa.DurationScalar) +@value_to_sql.register(pa.Time64Scalar) +def _(value: Union[pa.DurationScalar, pa.Time64Scalar]): + # Cast the raw count in the scalar's own unit: as_py() would round a + # nanosecond value to the microseconds of a Python timedelta or time. + if not value.is_valid: + return value_to_sql(None) + kind = "Duration" if pa.types.is_duration(value.type) else "Time64" + unit = _ARROW_TIME_UNITS[value.type.unit] + return f"arrow_cast({value.value}, '{kind}({unit})')" + + +@value_to_sql.register(pa.MapScalar) +def _(value: pa.MapScalar): + if not value.is_valid: + return value_to_sql(None) + keys = value_to_sql(list(value.values.field(0))) + values = value_to_sql(list(value.values.field(1))) + return f"map({keys}, {values})" + + @value_to_sql.register(np.ndarray) def _(value: np.ndarray): return value_to_sql(value.tolist()) @@ -461,6 +523,15 @@ def _(value: np.floating): return value_to_sql(float(value)) +@value_to_sql.register(np.datetime64) +def _(value: np.datetime64): + if np.isnat(value): + return value_to_sql(None) + if np.datetime_data(value.dtype)[0] in ("ps", "fs", "as"): + raise ValueError("SQL timestamps cannot preserve sub-nanosecond precision") + return value_to_sql(str(np.datetime_as_string(value, unit="ns", timezone="UTC"))) + + def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted diff --git a/python/python/tests/conftest.py b/python/python/tests/conftest.py index 8567a9830..86c4f00bb 100644 --- a/python/python/tests/conftest.py +++ b/python/python/tests/conftest.py @@ -9,6 +9,21 @@ import pytest import pytest_asyncio +def pytest_configure(config): + config.addinivalue_line( + "markers", "experimental_functions: requires the experimental-functions build" + ) + + +def pytest_collection_modifyitems(items): + if lancedb._lancedb._experimental_functions_enabled: + return + skip = pytest.mark.skip(reason="requires the experimental-functions Cargo feature") + for item in items: + if item.get_closest_marker("experimental_functions"): + item.add_marker(skip) + + def pandas_string_type(): """Return the PyArrow string type that pandas uses for string columns. diff --git a/python/python/tests/docs/test_basic.py b/python/python/tests/docs/test_basic.py index 35d7aac10..ef68114aa 100644 --- a/python/python/tests/docs/test_basic.py +++ b/python/python/tests/docs/test_basic.py @@ -91,19 +91,13 @@ def test_quickstart(tmp_path): } ) # --8<-- [end:alter_columns_vector] - # Change it back since we can get a panic with fp16 - tbl.alter_columns( - { - "path": "vector", - "data_type": pa.list_(pa.float32(), list_size=2), - } - ) # --8<-- [start:drop_columns] tbl.drop_columns(["dbl_price"]) # --8<-- [end:drop_columns] # --8<-- [start:create_index] tbl.create_index(num_sub_vectors=1) # --8<-- [end:create_index] + tbl.search([100, 100]).limit(2).to_pandas() # --8<-- [start:delete_rows] tbl.delete("item = 'fizz'") # --8<-- [end:delete_rows] @@ -185,13 +179,6 @@ async def test_quickstart_async(tmp_path): } ) # --8<-- [end:alter_columns_async_vector] - # Change it back since we can get a panic with fp16 - await tbl.alter_columns( - { - "path": "vector", - "data_type": pa.list_(pa.float32(), list_size=2), - } - ) # --8<-- [start:drop_columns_async] await tbl.drop_columns(["dbl_price"]) # --8<-- [end:drop_columns_async] @@ -200,6 +187,7 @@ async def test_quickstart_async(tmp_path): # --8<-- [start:create_index_async] await tbl.create_index("vector") # --8<-- [end:create_index_async] + await tbl.vector_search([100, 100]).limit(2).to_pandas() # --8<-- [start:delete_rows_async] await tbl.delete("item = 'fizz'") # --8<-- [end:delete_rows_async] diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index ec1b8b27e..b1da5472a 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +import ctypes import io import subprocess import sys @@ -14,6 +15,7 @@ import pytest from lance.blob import Blob, BlobType as LanceBlobType import lancedb +from lancedb import schema as schema_module from lancedb._blob import ( _set_blob_column, blob_v2_projection_sources, @@ -139,6 +141,41 @@ def test_blob_without_thresholds_has_no_threshold_metadata(): assert not any(b"threshold" in key for key in metadata) +@pytest.mark.parametrize("nullable", [False, True]) +@pytest.mark.parametrize( + "thresholds", + [ + {}, + {"inline_size_threshold": 0}, + {"inline_size_threshold": 8192}, + {"dedicated_size_threshold": 1 << 20}, + {"pack_file_size_threshold": 1 << 26}, + { + "inline_size_threshold": 8192, + "dedicated_size_threshold": 1 << 20, + "pack_file_size_threshold": 1 << 26, + }, + { + "inline_size_threshold": ctypes.c_size_t(-1).value, + "dedicated_size_threshold": ctypes.c_size_t(-1).value, + "pack_file_size_threshold": ctypes.c_size_t(-1).value, + }, + ], +) +def test_blob_thresholds_match_pylance(monkeypatch, nullable, thresholds): + expected = lance.blob_field("payload", nullable=nullable, **thresholds) + actual = lancedb.blob("payload", nullable=nullable, **thresholds) + assert type(actual.type) is LanceBlobType + assert actual.equals(expected, check_metadata=True) + + # Both extension classes must encode the same Arrow field on the wire. + monkeypatch.setattr( + schema_module, "_resolve_blob_type", lambda: schema_module._FallbackBlobType + ) + fallback = lancedb.blob("payload", nullable=nullable, **thresholds) + assert pa.schema([fallback]).serialize() == pa.schema([expected]).serialize() + + def test_blob_thresholds_are_validated(): with pytest.raises(ValueError, match="inline_size_threshold must be non-negative"): lancedb.blob("payload", inline_size_threshold=-1) @@ -194,6 +231,78 @@ def test_blob_type_works_without_pylance(): assert result.returncode == 0, result.stderr +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("with_pylance", [False, True]) +def test_local_schema_restores_blob_extensions(tmp_path, use_async, with_pylance): + db = lancedb.connect(tmp_path) + db.create_table( + "images", + schema=pa.schema( + [ + pa.field("id", pa.int64()), + lancedb.blob("image", nullable=False, inline_size_threshold=8192), + ], + metadata={"schema-key": "schema-value"}, + ), + ) + + # Reopening must restore the type before blob() or pylance registers it in + # the reader process, including when pylance is not installed. + script = textwrap.dedent( + """\ + import asyncio + import importlib.abc + import sys + import pyarrow as pa + + if sys.argv[3] == "False": + class NoLance(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == "lance" or fullname.startswith("lance."): + raise ModuleNotFoundError(fullname, name="lance") + sys.meta_path.insert(0, NoLance()) + import lancedb + + assert "lance.blob" not in sys.modules + + async def read_schema(): + db = await lancedb.connect_async(sys.argv[1]) + table = await db.open_table("images") + return await table.schema() + + if sys.argv[2] == "True": + schema = asyncio.run(read_schema()) + else: + schema = lancedb.connect(sys.argv[1]).open_table("images").schema + + image = schema.field("image") + assert isinstance(image.type, pa.ExtensionType), image + assert image.type == lancedb.blob("x").type + assert type(image.type) is lancedb.BlobType + assert not image.nullable + assert image.metadata == { + b"lance-encoding:blob-inline-size-threshold": b"8192" + } + assert schema.field("id") == pa.field("id", pa.int64()) + assert schema.metadata == {b"schema-key": b"schema-value"} + """ + ) + result = subprocess.run( + [ + sys.executable, + "-c", + script, + str(tmp_path), + str(use_async), + str(with_pylance), + ], + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stderr + + def test_blob_resolves_pylance_type_without_eager_import(): script = textwrap.dedent( """\ @@ -806,8 +915,7 @@ def test_to_pandas_does_not_drop_fragment_selection_on_fallback(): table.search().with_row_address(True).to_pandas(blob_mode="descriptions") -@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes"]) -def test_to_pandas_reports_lance_dataset_failures(tmp_path, blob_mode): +def test_to_pandas_reports_lance_dataset_failures(tmp_path): table = lancedb.connect(tmp_path).create_table( "dataset_failure", schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), @@ -819,7 +927,59 @@ def test_to_pandas_reports_lance_dataset_failures(tmp_path, blob_mode): table.to_lance = reject_credentials with pytest.raises(PermissionError, match="storage credentials rejected"): - table.search().to_pandas(blob_mode=blob_mode) + table.search().to_pandas(blob_mode="lazy") + + +@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes"]) +@pytest.mark.parametrize("with_row_id", [None, True, False]) +def test_to_batches_blob_modes(tmp_path, monkeypatch, blob_mode, with_row_id): + table = _nested_blob_table(lancedb.connect(tmp_path), "batch_blob_modes") + query = table.search().select({"renamed": "info"}) + if with_row_id is not None: + query.with_row_id(with_row_id) + fetched = [] + fetch_blobs = table.fetch_blobs + + def fetch(column, row_ids): + fetched.append(row_ids) + return fetch_blobs(column, row_ids) + + monkeypatch.setattr(table, "fetch_blobs", fetch) + reader = query.to_batches(batch_size=1, blob_mode=blob_mode) + assert fetched == [] + first = reader.read_next_batch() + assert first.schema == reader.schema + assert len(fetched) == (1 if blob_mode == "bytes" else 0) + batches = [first, *reader] + assert all(batch.schema == reader.schema for batch in batches) + assert all(batch.num_rows == 1 for batch in batches) + assert len(fetched) == (3 if blob_mode == "bytes" else 0) + if blob_mode == "bytes": + assert [row["renamed"] for batch in batches for row in batch.to_pylist()] == [ + {"name": "first", "blob": b"hello"}, + {"name": "second", "blob": None}, + None, + ] + if blob_mode != "lazy": + assert ("_rowid" in reader.schema.names) == (with_row_id is True) + assert "_lance_row_id" not in str(reader.schema) + else: + assert "_rowid" in reader.schema.names + + +@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes"]) +def test_empty_to_batches_blob_schema(blob_mode): + table = _blob_table("empty_blob_batches", [{"id": 1, "image": b"one"}]) + query = table.search().where("id < 0") + reader = query.to_batches(blob_mode=blob_mode) + assert reader.schema == query.to_arrow(blob_mode=blob_mode).schema + assert reader.read_all().num_rows == 0 + + +def test_to_batches_validates_blob_mode(): + table = _blob_table("invalid_batch_blob_mode", [{"id": 1, "image": b"one"}]) + with pytest.raises(ValueError, match="blob_mode must be one of"): + table.search().to_batches(blob_mode="handles") def test_to_pandas_keeps_to_arrow_overrides_without_blob_mode(): @@ -857,6 +1017,12 @@ def test_take_queries_honor_blob_mode(): ] description = table.take_row_ids([0]).to_list(blob_mode="descriptions")[0]["image"] assert "_lance_row_id" not in description + batches = table.take_row_ids([0]).to_batches(blob_mode="bytes") + assert batches.read_all().to_pylist() == [{"id": 1, "image": b"one"}] + batches = table.take_row_ids([0]).to_batches(blob_mode="descriptions") + assert "_rowid" not in batches.schema.names + assert "_lance_row_id" not in str(batches.schema) + assert batches.read_all().num_rows == 1 def test_bytes_mode_follows_swapped_blob_aliases(): @@ -902,6 +1068,8 @@ def test_bytes_mode_refused_under_namespace_query_pushdown(tmp_path): table.search().to_list(blob_mode="bytes") with pytest.raises(NotImplementedError, match="stable table snapshot"): table.take_row_ids([0]).to_list(blob_mode="bytes") + with pytest.raises(NotImplementedError, match="stable table snapshot"): + table.search().to_batches(blob_mode="bytes") descriptor = table.to_arrow(blob_mode="descriptions")["image"].to_pylist()[0] assert "_lance_row_id" not in descriptor @@ -923,6 +1091,8 @@ async def test_async_bytes_mode_refused_under_namespace_query_pushdown(tmp_path) await table.to_arrow(blob_mode="bytes") with pytest.raises(NotImplementedError, match="stable table snapshot"): await table.query().to_list(blob_mode="bytes") + with pytest.raises(NotImplementedError, match="stable table snapshot"): + await table.query().to_batches(blob_mode="bytes") def test_fetch_blobs_round_trip(): @@ -1197,12 +1367,13 @@ def test_merge_insert_bytes_after_reopen_without_touching_blob_type(tmp_path): script = textwrap.dedent( f"""\ import lancedb + import pyarrow as pa db = lancedb.connect({str(tmp_path)!r}) table = db.open_table("images") image_type = table.schema.field("image").type - if type(image_type).__name__ != "StructType": - raise SystemExit(f"expected StructType, got {{type(image_type)}}") + if not isinstance(image_type, pa.ExtensionType): + raise SystemExit(f"expected ExtensionType, got {{type(image_type)}}") result = ( table.merge_insert("id") .when_matched_update_all() @@ -1241,12 +1412,13 @@ def test_merge_insert_bytes_after_reopen_without_pylance(tmp_path): script = _HIDE_LANCE_BLOB + textwrap.dedent( f"""\ import lancedb + import pyarrow as pa db = lancedb.connect({str(tmp_path)!r}) table = db.open_table("images") image_type = table.schema.field("image").type - if type(image_type).__name__ != "StructType": - raise SystemExit(f"expected StructType, got {{type(image_type)}}") + if not isinstance(image_type, pa.ExtensionType): + raise SystemExit(f"expected ExtensionType, got {{type(image_type)}}") result = ( table.merge_insert("id") .when_matched_update_all() @@ -1276,7 +1448,7 @@ def test_merge_insert_bytes_after_reopen_without_pylance(tmp_path): assert result.returncode == 0, result.stderr -def test_merge_insert_blob_array_into_reopened_unregistered_table(tmp_path): +def test_merge_insert_blob_array_into_reopened_table(tmp_path): db = lancedb.connect(tmp_path) schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) table = db.create_table("images", schema=schema) @@ -1290,10 +1462,8 @@ def test_merge_insert_blob_array_into_reopened_unregistered_table(tmp_path): db = lancedb.connect({str(tmp_path)!r}) table = db.open_table("images") image_type = table.schema.field("image").type - if type(image_type).__name__ != "StructType": - raise SystemExit( - f"expected StructType before lance import, got {{type(image_type)}}" - ) + if not isinstance(image_type, pa.ExtensionType): + raise SystemExit(f"expected ExtensionType, got {{type(image_type)}}") import lance @@ -1866,10 +2036,74 @@ def test_legacy_v1_query_omits_auto_row_id(): assert "_rowid" not in hits.column_names -def test_fetch_blobs_rejects_legacy_v1_column(): +def test_fetch_legacy_v1_blobs(): table = _legacy_v1_table("legacy_fetch") - with pytest.raises(ValueError, match="legacy blob column.*blob v2"): - table.fetch_blobs("legacy", [0]) + table.add( + [ + {"id": 2, "legacy": None}, + {"id": 3, "legacy": b""}, + {"id": 4, "legacy": b"another fragment"}, + ] + ) + hits = table.search().select(["id", "legacy"]).with_row_id(True).to_arrow() + assert pa.types.is_struct(hits["legacy"].type) + by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist())) + row_ids = [by_id[i] for i in [4, 2, 1, 3, 4]] + expected = [b"another fragment", None, b"old", b"", b"another fragment"] + assert table.fetch_blobs("legacy", row_ids).to_pylist() == expected + assert table.blob_columns() == ["legacy"] + assert table.fetch_blobs("legacy", hits).to_pylist() == [ + b"old", + None, + b"", + b"another fragment", + ] + assert table.fetch_blobs("legacy", []).to_pylist() == [] + assert table.fetch_blob_files("legacy", []) == [] + + handles = table.fetch_blob_files("legacy", row_ids) + assert len(handles) == len(expected) + for handle, payload in zip(handles, expected): + if payload is None: + assert handle is None + else: + with handle: + assert handle.size() == len(payload) + assert handle.read(2) == payload[:2] + assert handle.seek(0) == 0 + assert handle.read() == payload + + assert table.fetch_blob_ranges( + "legacy", [(by_id[4], 8, 8), (by_id[2], 0, 1), (by_id[3], 0, 0)] + ).to_pylist() == [b"fragment", None, b""] + + table.delete("id = 2") + for fetch in [table.fetch_blobs, table.fetch_blob_files]: + with pytest.raises(ValueError, match="row ids but some do not exist"): + fetch("legacy", [by_id[1], by_id[2]]) + + +@pytest.mark.asyncio +async def test_async_fetch_legacy_v1_blobs(tmp_path): + table = _legacy_v1_table("legacy_async_source") + # Open a dataset written by Lance independently of the LanceDB connection. + lance.write_dataset( + pa.Table.from_pylist( + [{"id": 1, "legacy": b"old"}, {"id": 2, "legacy": None}], + schema=table.schema, + ), + tmp_path / "legacy.lance", + data_storage_version="2.0", + ) + db = await lancedb.connect_async(tmp_path) + table = await db.open_table("legacy") + assert await table.blob_columns() == ["legacy"] + hits = await table.query().with_row_id().to_arrow() + assert (await table.fetch_blobs("legacy", hits)).to_pylist() == [b"old", None] + handles = await table.fetch_blob_files("legacy", hits) + assert handles[0].read() == b"old" + handles[0].close() + assert handles[1] is None @pytest.mark.asyncio @@ -1975,6 +2209,10 @@ def test_blob_mode_for_every_query_shape(shape, blob_mode, with_row_id): assert all("_lance_row_id" not in image for image in images.values()) df = query.to_pandas(blob_mode=blob_mode) assert dict(zip(df["id"], df["image"])) == images + if shape in ("scan", "vector"): + reader = query.to_batches(batch_size=1, blob_mode=blob_mode) + assert reader.schema == hits.schema + assert reader.read_all().equals(hits) @pytest.mark.asyncio @@ -2001,6 +2239,48 @@ async def test_async_blob_bytes_for_every_query_shape(shape): assert dict(zip(df["id"], df["image"])) == {1: b"alpha", 2: b"beta"} +@pytest.mark.asyncio +@pytest.mark.parametrize("shape", ["scan", "vector", "fts", "hybrid"]) +@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes"]) +async def test_async_to_batches_blob_modes(shape, blob_mode, monkeypatch): + db = await lancedb.connect_async("memory:///") + table = await _hybrid_blob_table_async(db) + query = table.query() + if shape in ("vector", "hybrid"): + query = query.nearest_to([1.0, 0.0]) + if shape in ("fts", "hybrid"): + query = query.nearest_to_text("hello") + if shape == "scan": + query = query.where("id < 3") + query = query.select({"id": "id", "payload": "image"}).limit(2) + fetched = [] + fetch_blobs = table.fetch_blobs + + async def fetch(column, row_ids): + fetched.append(row_ids) + return await fetch_blobs(column, row_ids) + + monkeypatch.setattr(table, "fetch_blobs", fetch) + reader = await query.to_batches(max_batch_length=1, blob_mode=blob_mode) + assert fetched == [] + first = await reader.__anext__() + assert len(fetched) == (1 if blob_mode == "bytes" else 0) + batches = [first, *[batch async for batch in reader]] + assert all(batch.num_rows == 1 for batch in batches) + assert all(batch.schema == reader.schema for batch in batches) + if blob_mode == "bytes": + assert len(fetched) == 2 + assert { + row["id"]: row["payload"] for b in batches for row in b.to_pylist() + } == { + 1: b"alpha", + 2: b"beta", + } + if blob_mode != "lazy": + assert "_rowid" not in reader.schema.names + assert "_lance_row_id" not in str(reader.schema) + + class _KeepAllScoresReranker(Reranker): """Rebuilds the merged table like model rerankers with return_score="all".""" @@ -2659,3 +2939,135 @@ def test_create_table_with_python_blob_dict_and_object(): b"from-dict", b"from-blob", ] + + +def _openable_descriptors(table, *, by_address): + hits = ( + table.search() + .select(["id", "image", "_rowaddr"]) + .with_row_id(True) + .limit(100) + .to_arrow(blob_mode="descriptions") + ) + version = table.version + committed_at = next( + item["timestamp"] + for item in table.list_versions() + if item["version"] == version + ) + descriptors = {} + for row in hits.to_pylist(): + descriptor = row["image"] + if descriptor is not None and descriptor.get("kind") is not None: + descriptor = dict(descriptor) + descriptor["source"] = { + "uri": table.to_lance().uri, + "version": version, + "committed_at_micros": round(committed_at.timestamp() * 1_000_000), + "branch": None, + "column": "image", + "row_reference": row["_rowaddr" if by_address else "_rowid"], + "row_is_address": by_address, + } + else: + descriptor = None + descriptors[row["id"]] = descriptor + return descriptors + + +@pytest.mark.parametrize("by_address", [False, True]) +def test_open_blob_files_preserve_snapshot_order_nulls_and_empty_values( + tmp_path, by_address +): + db = lancedb.connect(str(tmp_path)) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + table = db.create_table("videos", schema=schema) + table.add( + [ + {"id": 1, "image": b"alpha"}, + {"id": 2, "image": None}, + {"id": 3, "image": b"beta"}, + {"id": 4, "image": b""}, + ] + ) + descriptors = _openable_descriptors(table, by_address=by_address) + table.add([{"id": 1, "image": b"replacement"}], mode="overwrite") + latest_version = table.version + values = pa.array( + [descriptors[3], descriptors[2], descriptors[1], descriptors[3], descriptors[4]] + ) + files = table.open_blob_files( + pa.chunked_array([values.slice(0, 2), values.slice(2)]) + ) + assert iter(files) is files + actual = [] + for file in files: + if file is None: + actual.append(None) + else: + with file: + actual.append(file.read()) + assert file.closed + assert actual == [b"beta", None, b"alpha", b"beta", b""] + with table.open_blob_file(descriptors[1]) as file: + file.seek(2) + assert file.read_range(0, 2) == b"al" + assert file.tell() == 2 + assert file.read(2) == b"ph" + assert table.version == latest_version + assert table.open_blob_file(pa.scalar(None, type=values.type)) is None + other = db.create_table("other", schema=schema) + with pytest.raises(ValueError, match="different table"): + other.open_blob_file(descriptors[1]) + stale = dict(descriptors[1], source=dict(descriptors[1]["source"])) + stale["source"]["committed_at_micros"] += 1 + with pytest.raises(ValueError, match="snapshot has been replaced"): + table.open_blob_file(stale) + raw = {key: value for key, value in descriptors[1].items() if key != "source"} + with pytest.raises(ValueError, match="source"): + table.open_blob_file(raw) + with pytest.raises(TypeError, match="descriptor"): + table.open_blob_file("not a descriptor") + + +def test_open_blob_files_does_not_open_ahead(monkeypatch): + table = _blob_table("lazy_descriptor_iteration", [{"id": 1, "image": b"x"}]) + opened = [] + + def open_file(descriptor): + opened.append(descriptor) + return descriptor + + monkeypatch.setattr(table, "open_blob_file", open_file) + files = table.open_blob_files(iter([1, None, 2])) + assert opened == [] + assert next(files) == 1 + assert opened == [1] + assert list(files) == [None, 2] + assert opened == [1, None, 2] + + +@pytest.mark.asyncio +async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path): + db = lancedb.connect(str(tmp_path)) + table = db.create_table( + "videos", + schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), + ) + table.add([{"id": 1, "image": b"alpha"}, {"id": 2, "image": None}]) + descriptors = _openable_descriptors(table, by_address=True) + async_db = await lancedb.connect_async(str(tmp_path)) + videos = await async_db.open_table("videos") + file = await videos.open_blob_file(pa.scalar(descriptors[1])) + with file: + assert file.read(2) == b"al" + actual = [] + async for file in videos.open_blob_files( + [descriptors[2], descriptors[1], descriptors[1]] + ): + if file is None: + actual.append(None) + else: + with file: + actual.append(await file.aread()) + assert actual == [None, b"alpha", b"alpha"] diff --git a/python/python/tests/test_blob_array.py b/python/python/tests/test_blob_array.py new file mode 100644 index 000000000..9eb8221f0 --- /dev/null +++ b/python/python/tests/test_blob_array.py @@ -0,0 +1,85 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import subprocess +import sys +import textwrap + +import pytest + + +@pytest.mark.parametrize("with_pylance", [False, True]) +def test_blob_array(with_pylance): + # Use fresh processes so each extension class can own Arrow's registry. + script = textwrap.dedent( + """\ + import importlib.abc + import sys + + if sys.argv[1] == "False": + class MissingLance(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == "lance" or fullname.startswith("lance."): + raise ModuleNotFoundError(fullname, name="lance") + sys.meta_path.insert(0, MissingLance()) + + import lancedb + import pyarrow as pa + from lancedb.schema import blob, blob_array + + if sys.argv[1] == "True": + from lance.blob import BlobType + else: + from lancedb.schema import _FallbackBlobType as BlobType + + schema = pa.schema([blob("video")]) + payloads = [b"abc", None, b"", b"\\x00\\xff"] + for values in ([], [None, None], payloads): + for source in (values, iter(values)): + array = blob_array(source) + assert isinstance(array, pa.ExtensionArray) + assert type(array.type) is BlobType + assert array.type == schema.field("video").type + assert array.null_count == values.count(None) + assert array.storage.to_pylist() == [ + None if value is None else { + "data": value, "uri": None, "position": None, "size": None + } + for value in values + ] + batch = pa.RecordBatch.from_arrays([array], schema=schema) + with pa.BufferOutputStream() as sink: + with pa.ipc.new_stream(sink, schema) as writer: + writer.write_batch(batch) + restored = pa.ipc.open_stream(sink.getvalue()).read_next_batch() + assert restored.equals(batch) + + for invalid in ("file:///video", {"data": b"abc"}, 123): + try: + blob_array([invalid]) + except TypeError as error: + assert "bytes or None" in str(error) + else: + raise AssertionError(f"accepted unsupported payload: {invalid!r}") + + # Batch iterators are the ingestion path that needs explicit arrays. + batches = [ + pa.RecordBatch.from_arrays([blob_array([value])], schema=schema) + for value in payloads + ] + table = lancedb.connect("memory:///").create_table( + "videos", data=iter(batches[:2]), schema=schema + ) + table.add(iter(batches[2:])) + row_ids = table.search().with_row_id(True).to_arrow()["_rowid"] + assert table.fetch_blobs("video", row_ids).to_pylist() == payloads + if sys.argv[1] == "False": + assert "lance" not in sys.modules + """ + ) + result = subprocess.run( + [sys.executable, "-c", script, str(with_pylance)], + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr diff --git a/python/python/tests/test_blob_query_without_pylance.py b/python/python/tests/test_blob_query_without_pylance.py new file mode 100644 index 000000000..cd9fd73ee --- /dev/null +++ b/python/python/tests/test_blob_query_without_pylance.py @@ -0,0 +1,94 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import subprocess +import sys +import textwrap + +import pytest + + +@pytest.mark.parametrize("api", ["sync", "async"]) +@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"]) +def test_blob_query_without_pylance(tmp_path, api, result): + script = """\ +import importlib.abc +import sys + +class MissingLance(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == "lance" or fullname.startswith("lance."): + raise ModuleNotFoundError(fullname, name="lance") + +sys.meta_path.insert(0, MissingLance()) +""" + textwrap.dedent( + """\ + import asyncio + import lancedb + import pyarrow as pa + + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")]) + rows = [{"id": 1, "video": b"one"}, {"id": 2, "video": None}, + {"id": 3, "video": b"three"}] + + def check(data): + assert data == [{"filename": 2, "payload": None}, + {"filename": 3, "payload": b"three"}], data + + async def main(): + if sys.argv[2] == "async": + db = await lancedb.connect_async(sys.argv[1]) + table = await db.create_table("videos", schema=schema) + await table.add(rows) + query = table.query() + else: + db = lancedb.connect(sys.argv[1]) + table = db.create_table("videos", schema=schema) + table.add(rows) + query = table.search() + query = query.select({"filename": "id", "payload": "video"}).offset(1) + if sys.argv[3] == "pandas": + frame = query.to_pandas(blob_mode="bytes", split_blocks=True) + if sys.argv[2] == "async": + frame = await frame + check(frame.to_dict("records")) + frame = table.to_pandas(blob_mode="bytes") + if sys.argv[2] == "async": + frame = await frame + assert frame.to_dict("records") == rows + elif sys.argv[3] == "batches": + if sys.argv[2] == "async": + reader = await query.to_batches( + max_batch_length=1, blob_mode="bytes") + batches = [batch async for batch in reader] + else: + reader = query.to_batches(batch_size=1, blob_mode="bytes") + batches = list(reader) + assert reader.schema.field("payload").type == pa.large_binary() + assert all(batch.num_rows <= 1 for batch in batches) + assert all(batch.schema == reader.schema for batch in batches) + check([row for batch in batches for row in batch.to_pylist()]) + else: + try: + frame = query.to_pandas() + if sys.argv[2] == "async": + await frame + except RuntimeError as error: + message = str(error) + assert "pip install pylance" in message, message + assert ".." not in message, message + assert "Use a plain scan query" not in message, message + assert "but The" not in message, message + else: + raise AssertionError("lazy handles should require pylance") + assert "lance" not in sys.modules + + asyncio.run(main()) + """ + ) + completed = subprocess.run( + [sys.executable, "-c", script, str(tmp_path), api, result], + capture_output=True, + text=True, + ) + assert completed.returncode == 0, completed.stderr diff --git a/python/python/tests/test_blob_reader.py b/python/python/tests/test_blob_reader.py new file mode 100644 index 000000000..dd12409af --- /dev/null +++ b/python/python/tests/test_blob_reader.py @@ -0,0 +1,59 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import io + +import pytest + +from lancedb import BlobReader + + +def test_reader_is_lazy_and_seekable(): + requests = [] + size = 64 * 1024 * 1024 + + def read_range(offset, length): + requests.append((offset, length)) + return bytes((index % 251 for index in range(offset, offset + length))) + + with BlobReader(read_range, size) as reader: + assert requests == [] + assert reader.size() == size + reader.seek(-4, io.SEEK_END) + assert reader.read(10) == bytes(index % 251 for index in range(size - 4, size)) + assert reader.read(1) == b"" + assert requests == [(size - 4, 4)] + assert reader.read_range(1, 3) == b"\x01\x02\x03" + assert reader.tell() == size + reader.seek(2) + target = bytearray(3) + assert reader.readinto(target) == 3 + assert target == b"\x02\x03\x04" + reader.seek(-1, io.SEEK_CUR) + assert reader.tell() == 4 + with pytest.raises(ValueError, match="closed"): + reader.read(1) + + +def test_reader_supports_buffered_io_and_bounds_range_requests(): + requests = [] + payload = b"x" * (3 * 1024 * 1024 + 7) + + def read_range(offset, length): + requests.append((offset, length)) + return payload[offset : offset + length] + + with io.BufferedReader(BlobReader(read_range, len(payload))) as reader: + assert reader.read() == payload + assert requests + assert all(length <= 1024 * 1024 for _, length in requests) + + +def test_reader_rejects_invalid_ranges_and_short_reads(): + reader = BlobReader(lambda offset, length: b"", 10) + with pytest.raises(ValueError): + reader.seek(-1) + with pytest.raises(ValueError): + reader.read_range(-1, 1) + with pytest.raises(OSError, match="payload length"): + reader.read(1) diff --git a/python/python/tests/test_catalog.py b/python/python/tests/test_catalog.py index b2036b7a6..95b03c6e7 100644 --- a/python/python/tests/test_catalog.py +++ b/python/python/tests/test_catalog.py @@ -3,13 +3,13 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json -from threading import Thread import pytest import lancedb from lancedb.db import AsyncConnection, DBConnection from lancedb.remote.errors import HttpError +from utils import start_server_thread @pytest.fixture @@ -38,8 +38,7 @@ def catalog_server(): do_POST = handle_request with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: - thread = Thread(target=server.serve_forever, daemon=True) - thread.start() + thread = start_server_thread(server, daemon=True) try: yield f"http://127.0.0.1:{server.server_port}", requests, responses finally: @@ -86,12 +85,12 @@ def test_catalog_sync_scope_and_serialization(catalog_server): connection.execute_query_async("SELECT 1") assert restored.table_names() == [] assert list(catalog.list_databases()) == ["team/search"] - catalog.drop_database("team/search", ignore_missing=True) + catalog.drop_database("team/search", ignore_missing=True, cascade=True) assert requests[0][0] == "/v1/namespace/team%2Fsearch/create" assert requests[0][2] == {"mode": "ExistOk"} assert requests[1][0] == "/v1/namespace/team%2Fsearch/describe" assert requests[4][0] == "/v1/namespace/$/list" - assert requests[5][2] == {"mode": "Skip", "behavior": "Restrict"} + assert requests[5][2] == {"mode": "Skip", "behavior": "Cascade"} for i, (_, headers, _) in enumerate(requests): headers = {key.lower(): value for key, value in headers.items()} assert headers.get("x-lancedb-database") == ( diff --git a/python/python/tests/test_closed_table_query.py b/python/python/tests/test_closed_table_query.py new file mode 100644 index 000000000..2ff3a8e98 --- /dev/null +++ b/python/python/tests/test_closed_table_query.py @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest +from lancedb.db import AsyncConnection + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", ["count_rows", "query", "head"]) +async def test_closed_table_queries_raise_runtime_error( + mem_db_async: AsyncConnection, operation +): + table = await mem_db_async.create_table("closed_query", data=[{"id": 0}]) + assert (await table.query().to_arrow()).to_pylist() == [{"id": 0}] + table.close() + table.close() + assert not table.is_open() + + with pytest.raises(RuntimeError, match="Table closed_query is closed"): + if operation == "query": + table.query() + else: + await getattr(table, operation)() + + +@pytest.mark.asyncio +async def test_open_table_queries(mem_db_async: AsyncConnection): + table = await mem_db_async.create_table("open_query", data=[{"id": 0}]) + assert await table.count_rows() == 1 + assert (await table.query().to_arrow()).to_pylist() == [{"id": 0}] + assert (await table.head()).to_pylist() == [{"id": 0}] + table.close() diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 7d37910a3..64bf928c0 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -86,6 +86,7 @@ def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeyp assert members["uri"] == str(tmp_path) assert members["read_consistency_interval"] is None + assert members["session"] is None assert repr(db) == f"LanceDBConnection(uri={str(tmp_path)!r})" assert repr(table) == f"LanceTable(name='test', _conn={db!r})" @@ -105,6 +106,8 @@ def test_read_consistency_interval_does_not_use_background_loop(tmp_path, monkey assert db.read_consistency_interval == consistency_interval assert db_from_inner.read_consistency_interval == consistency_interval + assert db.session is None + assert db_from_inner.session is None def test_ingest_pd(tmp_path): @@ -1146,6 +1149,24 @@ def test_local_namespace_operations(tmp_path): assert db.list_namespaces().namespaces == [] +@pytest.mark.asyncio +async def test_local_async_namespace_exists(tmp_path): + db = await lancedb.connect_async(tmp_path) + await db.create_namespace(["existing"]) + await db.create_namespace(["existing", "nested"]) + + assert await db.namespace_exists([]) is True + assert await db.namespace_exists(["existing"]) is True + assert await db.namespace_exists(["existing", "nested"]) is True + assert await db.namespace_exists(["missing"]) is False + assert await db.namespace_exists(["existing", "missing"]) is False + assert await db.namespace_exists(["missing", "nested"]) is False + + await db.drop_namespace(["existing", "nested"]) + assert await db.namespace_exists(["existing", "nested"]) is False + assert await db.namespace_exists(["existing"]) is True + + def test_local_sync_namespace_uses_rust_without_python_client(tmp_path, monkeypatch): """Sync local namespace operations should avoid the Python namespace client.""" db = lancedb.connect(tmp_path) diff --git a/python/python/tests/test_duckdb.py b/python/python/tests/test_duckdb.py index a307149ea..a24933210 100644 --- a/python/python/tests/test_duckdb.py +++ b/python/python/tests/test_duckdb.py @@ -22,3 +22,19 @@ def test_basic_query(tmp_path): results = duck_conn.sql("SELECT SUM(y) FROM adapter").fetchall() assert results[0][0] == 26 + + +def test_query_with_filter(tmp_path): + data = pa.table({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) + conn = lancedb.connect(tmp_path) + tbl = conn.create_table("test", data) + + adapter = PyarrowDatasetAdapter(tbl) # noqa: F841 + + duck_conn = duckdb.connect() + + results = duck_conn.sql("SELECT SUM(y) FROM adapter WHERE x > 2").fetchall() + assert results[0][0] == 15 + + results = duck_conn.sql("SELECT y FROM adapter WHERE x > 2 ORDER BY y").fetchall() + assert results == [(7,), (8,)] diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index 9d18752f1..5eb3f095c 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -3297,3 +3297,230 @@ def test_streaming_dataset_over_remote_table(): assert len(server.scans) == 1, "the permutation is built with one row-id scan" assert server.takes, "rows must be fetched with row-id takes" assert_server_safe_row_id_requests(server) + + +# --------------------------------------------------------------------------- +# split_strategy escape hatch +# --------------------------------------------------------------------------- + + +def test_split_strategy_bootstrap_sample(lance_table): + """split_strategy lets StreamingDataset use bootstrap_sample directly, producing + more rows than the base table has (sampling with replacement).""" + num_samples = 4 * NUM_ROWS + ds = StreamingDataset( + lance_table, + split_strategy=lambda b: b.bootstrap_sample( + num_samples, fixed=NUM_SPLITS, seed=SHUFFLE_SEED + ), + num_splits=NUM_SPLITS, + ) + ids = [row["id"] for row in ds] + + assert len(ids) == num_samples + # 4x oversampling a small table must produce at least one repeat. + assert len(set(ids)) < len(ids) + assert set(ids).issubset(set(range(NUM_ROWS))) + + +def test_split_strategy_matches_direct_permutation_builder_use(lance_table): + """StreamingDataset(split_strategy=...), read single-process (no DataLoader + workers, so this one process owns every split and round-robins across all of + them), must yield exactly what calling the same strategy directly on a + PermutationBuilder would read, interleaved one row per split per cycle. + + Reads each split via __getitems__ (explicit indices), not plain iteration: + Permutation's sequential __iter__ returns empty for a permutation with repeated + row_ids (confirmed directly -- len() is correct, __getitems__ returns the right + rows, but `for row in perm` yields nothing). That's a pre-existing limitation of + Permutation's iterator, unrelated to Bootstrap sampling's correctness: it doesn't + affect StreamingDataset or this benchmark, since both only ever read via + explicit-index batched fetches (take_offsets/__getitems__), never the plain + iterator -- flagged separately, not fixed here (out of scope for this change). + """ + from lancedb.permutation import Permutation, permutation_builder + + def strategy(builder): + return builder.bootstrap_sample(2 * NUM_ROWS, fixed=NUM_SPLITS, seed=1) + + direct_perm_tbl = strategy(permutation_builder(lance_table)).execute() + expected_by_split = [] + for split in range(NUM_SPLITS): + perm = Permutation.from_tables(lance_table, direct_perm_tbl, split=split) + rows = perm.__getitems__(list(range(len(perm)))) + expected_by_split.append([row["id"] for row in rows]) + samples_per_split = len(expected_by_split[0]) + expected = [ + expected_by_split[split][cycle] + for cycle in range(samples_per_split) + for split in range(NUM_SPLITS) + ] + + ds = StreamingDataset(lance_table, split_strategy=strategy, num_splits=NUM_SPLITS) + actual = [row["id"] for row in ds] + assert actual == expected + + +def test_split_strategy_is_reproducible_across_instances(lance_table): + def strategy(builder): + return builder.bootstrap_sample(3 * NUM_ROWS, fixed=NUM_SPLITS, seed=99) + + ds1 = StreamingDataset(lance_table, split_strategy=strategy, num_splits=NUM_SPLITS) + ds2 = StreamingDataset(lance_table, split_strategy=strategy, num_splits=NUM_SPLITS) + + assert [row["id"] for row in ds1] == [row["id"] for row in ds2] + + +def test_split_strategy_num_splits_mismatch_raises(lance_table): + """StreamingDataset(split_strategy=...) must reject a strategy whose split + count doesn't match num_splits. `_rank_splits` assumes split ids are exactly + 0..num_splits-1 with no gaps; a mismatch would otherwise silently drop rows + (split ids >= num_splits) or leave some ranks reading an empty split (missing + ids < num_splits).""" + with pytest.raises(ValueError, match="num_splits"): + StreamingDataset( + lance_table, + split_strategy=lambda b: b.bootstrap_sample( + 2 * NUM_ROWS, fixed=NUM_SPLITS, seed=SHUFFLE_SEED + ), + num_splits=NUM_SPLITS + 1, # the strategy above always builds NUM_SPLITS + ) + + +def test_split_strategy_unequal_split_sizes_raises(lance_table): + """StreamingDataset(split_strategy=...) must reject a strategy whose splits + all exist (ids 0..num_splits-1) but aren't the same size. The round-robin + iteration (see _iter_owned) assumes every owned split has the same row count + and stops as soon as any one is exhausted -- `ratios`/`counts` (unlike + `fixed`) can produce unequal split sizes, which would otherwise silently + drop rows from the larger splits.""" + with pytest.raises(ValueError, match="unequal split sizes"): + StreamingDataset( + lance_table, + split_strategy=lambda b: b.bootstrap_sample( + 100, ratios=[0.7, 0.3], seed=SHUFFLE_SEED + ), + num_splits=2, + ) + + +def test_split_strategy_permutation_mismatch_on_resume_raises(lance_table): + """load_state_dict must reject resuming against a different permutation than + the one that produced the checkpoint. num_splits/shuffle_seed alone can't catch + this for split_strategy, since that path ignores shuffle_seed entirely: a + bootstrap_sample reseeded differently resamples completely differently while + shuffle_seed keeps whatever value the caller passed either way, so the + pre-existing checks would pass despite the mismatch.""" + + def strategy(seed): + return lambda b: b.bootstrap_sample(2 * NUM_ROWS, fixed=NUM_SPLITS, seed=seed) + + ds1 = StreamingDataset( + lance_table, + split_strategy=strategy(1), + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + ) + it = iter(ds1) + for _ in range(NUM_SPLITS): # one full cycle: every split advances uniformly + next(it) + checkpoint = ds1.state_dict() + + ds2 = StreamingDataset( + lance_table, + split_strategy=strategy(2), # different seed -> a different permutation + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, # unchanged -- irrelevant on this path + ) + with pytest.raises(ValueError, match="permutation mismatch"): + ds2.load_state_dict(checkpoint) + + +def test_split_strategy_resume_with_matching_permutation_succeeds(lance_table): + """The common case: resuming against the same split_strategy (same seed) must + work exactly like the non-split_strategy checkpoint/resume path, continuing + from exactly the same position with no gaps or repeats.""" + + def strategy(b): + return b.bootstrap_sample(2 * NUM_ROWS, fixed=NUM_SPLITS, seed=7) + + ds1 = StreamingDataset( + lance_table, + split_strategy=strategy, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + ) + it = iter(ds1) + for _ in range(NUM_SPLITS): + next(it) + checkpoint = ds1.state_dict() + remaining_original = [row["id"] for row in it] + + ds2 = StreamingDataset( + lance_table, + split_strategy=strategy, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + ) + ds2.load_state_dict(checkpoint) # must not raise + remaining_resumed = [row["id"] for row in ds2] + + assert remaining_original == remaining_resumed + + +def test_default_checkpoint_omits_perm_fingerprint(lance_table): + """split_random/split_sequential checkpoints must not carry a + perm_fingerprint -- see test_default_checkpoint_resumes_after_compaction for + why checking one on this path would be wrong, not just unnecessary.""" + ds = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED) + assert "perm_fingerprint" not in ds.state_dict() + + +def test_split_strategy_checkpoint_includes_perm_fingerprint(lance_table): + ds = StreamingDataset( + lance_table, + split_strategy=lambda b: b.bootstrap_sample( + 2 * NUM_ROWS, fixed=NUM_SPLITS, seed=SHUFFLE_SEED + ), + num_splits=NUM_SPLITS, + ) + assert "perm_fingerprint" in ds.state_dict() + + +def test_default_checkpoint_resumes_after_compaction(lance_table): + """split_random/split_sequential checkpoints must resume normally even after + the table is compacted between save and load. Lance row ids are not stable + across compaction by default (confirmed empirically: a 2-fragment table's + row ids differ before and after `optimize()`), so fingerprinting raw row ids + 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.""" + 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) + it = iter(ds) + for _ in range(NUM_SPLITS): + next(it) + checkpoint = ds.state_dict() + assert "perm_fingerprint" not in checkpoint + + before_compaction = set( + lance_table.to_lance() + .to_table(columns=[], with_row_id=True)["_rowid"] + .to_pylist() + ) + lance_table.optimize() + after_compaction = set( + lance_table.to_lance() + .to_table(columns=[], with_row_id=True)["_rowid"] + .to_pylist() + ) + assert before_compaction != after_compaction, ( + "test setup didn't actually renumber row ids -- fix the fixture, not " + "the assertion below" + ) + + ds_resumed = StreamingDataset( + lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED + ) + ds_resumed.load_state_dict(checkpoint) # must not raise diff --git a/python/python/tests/test_embedding_field_metadata.py b/python/python/tests/test_embedding_field_metadata.py new file mode 100644 index 000000000..68754ee35 --- /dev/null +++ b/python/python/tests/test_embedding_field_metadata.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import copy + +import lancedb +import pytest +from lancedb.embeddings.base import TextEmbeddingFunction +from lancedb.embeddings.registry import get_registry +from lancedb.pydantic import LanceModel, Vector + + +class LocalEmbedding(TextEmbeddingFunction): + def ndims(self): + return 2 + + def generate_embeddings(self, texts): + return [[1.0, 0.0] if text == "alpha" else [0.0, 1.0] for text in texts] + + +@pytest.mark.parametrize( + "method,tag", + [("SourceField", "source_column_for"), ("VectorField", "vector_column_for")], +) +@pytest.mark.parametrize("extra", [None, {}, {"x-purpose": "retrieval"}]) +def test_embedding_field_preserves_extra_metadata(method, tag, extra): + function = LocalEmbedding.create(max_retries=0) + original = copy.deepcopy(extra) + field = getattr(function, method)(json_schema_extra=extra) + assert extra == original + assert field.json_schema_extra[tag] is function + for key, value in (extra or {}).items(): + assert field.json_schema_extra[key] == value + + +@pytest.mark.parametrize( + "method,tag", + [("SourceField", "source_column_for"), ("VectorField", "vector_column_for")], +) +def test_extra_metadata_cannot_replace_embedding_identity(method, tag): + function = LocalEmbedding.create(max_retries=0) + supplied = {tag: "caller value", "x-purpose": "retrieval"} + field = getattr(function, method)(json_schema_extra=supplied) + assert supplied[tag] == "caller value" + assert field.json_schema_extra[tag] is function + assert field.json_schema_extra["x-purpose"] == "retrieval" + + +@pytest.mark.parametrize("method", ["SourceField", "VectorField"]) +def test_embedding_field_preserves_other_field_arguments(method): + function = LocalEmbedding.create(max_retries=0) + field = getattr(function, method)(title="Custom title", description="Custom field") + assert field.title == "Custom title" + assert field.description == "Custom field" + + +def test_extra_metadata_preserves_schema_and_local_embedding(tmp_path, monkeypatch): + registry = get_registry() + monkeypatch.setattr(registry, "_functions", registry._functions.copy()) + registry.register("test-embedding-field-extra")(LocalEmbedding) + function = LocalEmbedding.create(max_retries=0) + + class Row(LanceModel): + text: str = function.SourceField(json_schema_extra={"x-purpose": "source"}) + vector: Vector(2) = function.VectorField( + json_schema_extra={"x-purpose": "embedding"} + ) + + json_schema = Row.model_json_schema() + assert json_schema["properties"]["text"]["x-purpose"] == "source" + assert json_schema["properties"]["vector"]["x-purpose"] == "embedding" + configs = Row.parse_embedding_functions() + assert len(configs) == 1 + assert configs[0].function is function + assert configs[0].source_column == "text" + assert configs[0].vector_column == "vector" + db = lancedb.connect(tmp_path) + table = db.create_table( + "rows", schema=Row, data=[{"text": "alpha"}, {"text": "beta"}] + ) + assert table.search("alpha").limit(1).to_list()[0]["text"] == "alpha" + reopened = lancedb.connect(tmp_path).open_table("rows") + assert isinstance(reopened.embedding_functions["vector"].function, LocalEmbedding) + assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha" diff --git a/python/python/tests/test_embedding_registry.py b/python/python/tests/test_embedding_registry.py new file mode 100644 index 000000000..07c10bd7e --- /dev/null +++ b/python/python/tests/test_embedding_registry.py @@ -0,0 +1,88 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import lancedb +import pytest +from lancedb.embeddings.base import TextEmbeddingFunction +from lancedb.embeddings.registry import EmbeddingFunctionRegistry, get_registry +from lancedb.pydantic import LanceModel, Vector + + +class FirstEmbedding(TextEmbeddingFunction): + def ndims(self): + return 2 + + def generate_embeddings(self, texts): + return [[1.0, 0.0] if text == "alpha" else [0.0, 1.0] for text in texts] + + +class SecondEmbedding(FirstEmbedding): + def generate_embeddings(self, texts): + return [[0.0, 1.0] if text == "alpha" else [1.0, 0.0] for text in texts] + + +@pytest.mark.parametrize( + "first_alias,second_alias,second_class", + [ + ("shared", "shared", SecondEmbedding), + (None, "FirstEmbedding", SecondEmbedding), + ("SecondEmbedding", None, SecondEmbedding), + (None, None, FirstEmbedding), + ("", "", FirstEmbedding), + ], +) +def test_duplicate_registration_preserves_original( + first_alias, second_alias, second_class +): + registry = EmbeddingFunctionRegistry() + registry.register(first_alias)(FirstEmbedding) + key = first_alias or "FirstEmbedding" + original_alias = FirstEmbedding.__embedding_function_registry_alias__ + second_attributes = dict(second_class.__dict__) + with pytest.raises(KeyError, match=f"{key} was already registered"): + registry.register(second_alias)(second_class) + assert registry.get(key) is FirstEmbedding + assert FirstEmbedding.__embedding_function_registry_alias__ == original_alias + assert dict(second_class.__dict__) == second_attributes + + +def test_class_name_does_not_collide_with_distinct_alias(): + registry = EmbeddingFunctionRegistry() + registry.register()(FirstEmbedding) + same_name = type("FirstEmbedding", (SecondEmbedding,), {}) + registry.register("separate")(same_name) + assert registry.get("FirstEmbedding") is FirstEmbedding + assert registry.get("separate") is same_name + + +def test_same_class_explicit_alias_registration_is_idempotent(): + registry = EmbeddingFunctionRegistry() + assert registry.register("shared")(FirstEmbedding) is FirstEmbedding + attributes = dict(FirstEmbedding.__dict__) + assert registry.register("shared")(FirstEmbedding) is FirstEmbedding + assert registry.get("shared") is FirstEmbedding + assert dict(FirstEmbedding.__dict__) == attributes + + +def test_alias_collision_does_not_change_persisted_table(tmp_path, monkeypatch): + registry = get_registry() + monkeypatch.setattr(registry, "_functions", registry._functions.copy()) + alias = "test-alias-collision-persisted-table" + registry.register(alias)(FirstEmbedding) + function = FirstEmbedding.create(max_retries=0) + + class Row(LanceModel): + text: str = function.SourceField() + vector: Vector(2) = function.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table( + "rows", schema=Row, data=[{"text": "alpha"}, {"text": "beta"}] + ) + assert table.search("alpha").limit(1).to_list()[0]["text"] == "alpha" + assert registry.register(alias)(FirstEmbedding) is FirstEmbedding + with pytest.raises(KeyError, match=f"{alias} was already registered"): + registry.register(alias)(SecondEmbedding) + reopened = lancedb.connect(tmp_path).open_table("rows") + assert isinstance(reopened.embedding_functions["vector"].function, FirstEmbedding) + assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha" diff --git a/python/python/tests/test_embedding_registry_listing.py b/python/python/tests/test_embedding_registry_listing.py new file mode 100644 index 000000000..4f7189a7b --- /dev/null +++ b/python/python/tests/test_embedding_registry_listing.py @@ -0,0 +1,55 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from lancedb.embeddings import EmbeddingFunctionRegistry, TextEmbeddingFunction + + +class ExampleEmbedding(TextEmbeddingFunction): + def ndims(self): + return 2 + + def generate_embeddings(self, texts): + return [[1.0, 0.0] for _ in texts] + + +class OtherEmbedding(ExampleEmbedding): + pass + + +def test_list_functions_empty_registry(): + registry = EmbeddingFunctionRegistry() + assert registry.list_functions() == [] + + +def test_list_functions_names_and_registration_order(): + registry = EmbeddingFunctionRegistry() + registry.register("custom-embedding")(ExampleEmbedding) + registry.register()(OtherEmbedding) + + assert registry.list_functions() == ["custom-embedding", "OtherEmbedding"] + assert [registry.get(name) for name in registry.list_functions()] == [ + ExampleEmbedding, + OtherEmbedding, + ] + + +def test_list_functions_returns_independent_snapshot(): + registry = EmbeddingFunctionRegistry() + registry.register("first")(ExampleEmbedding) + names = registry.list_functions() + names.append("not-registered") + assert registry.list_functions() == ["first"] + + registry.register("second")(OtherEmbedding) + assert names == ["first", "not-registered"] + assert registry.list_functions() == ["first", "second"] + + +def test_list_functions_after_reset(): + registry = EmbeddingFunctionRegistry() + registry.register("custom-embedding")(ExampleEmbedding) + names = registry.list_functions() + registry.reset() + + assert registry.list_functions() == [] + assert names == ["custom-embedding"] diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 9434033e1..32503c04f 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -23,6 +23,12 @@ from lancedb.embeddings.utils import retry from lancedb.pydantic import LanceModel, Vector +@pytest.fixture(autouse=True) +def isolated_embedding_registry(monkeypatch): + registry = get_registry() + monkeypatch.setattr(registry, "_functions", registry._functions.copy()) + + def mock_embed_func(input_data): return [np.random.randn(128).tolist() for _ in range(len(input_data))] @@ -64,6 +70,37 @@ def test_embedding_function(tmp_path): assert np.allclose(actual, expected) +def test_embedding_function_registered_without_alias(tmp_path): + registry = EmbeddingFunctionRegistry.get_instance() + + @registry.register() + class NoAliasEmbeddingFunction(TextEmbeddingFunction): + def ndims(self): + return 2 + + def generate_embeddings(self, texts): + return [np.array([1.0, 2.0]) for _ in texts] + + assert registry.get("NoAliasEmbeddingFunction") is NoAliasEmbeddingFunction + + func = NoAliasEmbeddingFunction.create() + + class Schema(LanceModel): + text: str = func.SourceField() + vector: Vector(2) = func.VectorField() + + db = lancedb.connect(tmp_path) + db.create_table("test", schema=Schema) + + # The class name is written to the table metadata, so the function can be + # resolved again when the table is reopened. + table = lancedb.connect(tmp_path).open_table("test") + table.add([{"text": "hello"}]) + conf = table.embedding_functions["vector"] + assert isinstance(conf.function, NoAliasEmbeddingFunction) + assert table.to_arrow()["vector"].to_pylist() == [[1.0, 2.0]] + + def test_instructor_ndims_uses_instruction(): instructor = get_registry().get("instructor").create() model = MagicMock() @@ -596,6 +633,363 @@ def test_openai_no_retry_on_401(mock_sleep): assert mock_sleep.call_count == 0 +class _HttpStatusError(Exception): + """Stand-in for provider SDK errors (openai, cohere, ...) with a status code.""" + + def __init__(self, status_code, message="error"): + super().__init__(message) + self.status_code = status_code + + +class _ResponseStatusError(Exception): + """Stand-in for requests/httpx errors, which expose `response.status_code`.""" + + def __init__(self, status_code): + super().__init__(f"HTTP {status_code}") + self.response = MagicMock(status_code=status_code) + + +def _run_with_retry(side_effect, **kwargs): + """Run a function through the retry helper with a mocked `time.sleep`. + + Returns (mock_func, sleeps, error). + """ + from lancedb.embeddings.utils import retry_with_exponential_backoff + + mock_func = MagicMock(side_effect=side_effect) + sleeps = [] + error = None + with patch("time.sleep", side_effect=sleeps.append): + try: + retry_with_exponential_backoff(mock_func, **kwargs)() + except Exception as e: + error = e + return mock_func, sleeps, error + + +@pytest.mark.parametrize("status", [400, 401, 403, 404, 405, 410, 413, 422]) +@pytest.mark.parametrize("make_error", [_HttpStatusError, _ResponseStatusError]) +def test_retry_does_not_retry_permanent_http_errors(status, make_error): + err = make_error(status) + mock_func, sleeps, error = _run_with_retry(err, max_retries=7) + + assert error is err + assert mock_func.call_count == 1 + assert sleeps == [] + + +@pytest.mark.parametrize("status", [408, 409, 429, 500, 502, 503, 504]) +@pytest.mark.parametrize("make_error", [_HttpStatusError, _ResponseStatusError]) +def test_retry_retries_transient_http_errors(status, make_error): + mock_func, sleeps, error = _run_with_retry( + [make_error(status), make_error(status), "result"], max_retries=7 + ) + + assert error is None + assert mock_func.call_count == 3 + assert len(sleeps) == 2 + + +@pytest.mark.parametrize( + "exc", + [ + ConnectionError("connection reset"), + TimeoutError("timed out"), + OSError("network is unreachable"), + ValueError("custom embedding function failure"), + RuntimeError("boom"), + Exception("plain exception"), + ], +) +def test_retry_retries_errors_without_http_status(exc): + mock_func, sleeps, error = _run_with_retry([exc, exc, "result"], max_retries=7) + + assert error is None + assert mock_func.call_count == 3 + assert len(sleeps) == 2 + + +def test_retry_error_status_attributes_of_other_types_are_ignored(): + # `code` is a string for openai errors ("model_not_found"), and arbitrary + # exceptions may carry unrelated numeric attributes. Neither is an HTTP status. + class WeirdError(Exception): + code = "model_not_found" + status_code = None + + class ExitCodeError(Exception): + code = 2 + + for exc in (WeirdError("a"), ExitCodeError("b")): + mock_func, sleeps, error = _run_with_retry(exc, max_retries=2) + assert mock_func.call_count == 3 + assert len(sleeps) == 2 + + +def test_retry_botocore_style_errors(): + # botocore ClientError exposes `response["ResponseMetadata"]["HTTPStatusCode"]`. + # Bedrock reports throttling with a 400, which must stay retryable. + class ClientError(Exception): + def __init__(self, status, code): + super().__init__(code) + self.response = { + "ResponseMetadata": {"HTTPStatusCode": status}, + "Error": {"Code": code}, + } + + throttled = ClientError(400, "ThrottlingException") + mock_func, sleeps, error = _run_with_retry([throttled, "result"], max_retries=3) + assert error is None + assert mock_func.call_count == 2 + + invalid = ClientError(400, "ValidationException") + mock_func, sleeps, error = _run_with_retry(invalid, max_retries=3) + assert error is invalid + assert mock_func.call_count == 1 + assert sleeps == [] + + +def test_retry_authentication_error_by_name_not_retried(): + class AuthenticationError(Exception): + pass + + mock_func, sleeps, error = _run_with_retry(AuthenticationError("bad key")) + assert isinstance(error, AuthenticationError) + assert mock_func.call_count == 1 + assert sleeps == [] + + +def test_retry_gives_up_after_max_retries_with_original_error_attached(): + original = _HttpStatusError(503, "overloaded") + mock_func, sleeps, error = _run_with_retry(original, max_retries=3) + + assert mock_func.call_count == 4 + assert len(sleeps) == 3 + assert "Maximum number of retries (3) exceeded" in str(error) + assert error.args[1] is original + assert error.__cause__ is original + + +def test_retry_delay_is_capped_by_max_delay(): + # Default settings (7 retries, 60s cap): the old implementation could sleep for + # up to ~47 minutes in a single retry and hours in total. + exc = _HttpStatusError(503) + for seed in range(50): + import random + + random.seed(seed) + _, sleeps, _ = _run_with_retry(exc) + assert len(sleeps) == 7 + assert max(sleeps) <= 60 + assert sum(sleeps) <= 7 * 60 + + # Custom cap + _, sleeps, _ = _run_with_retry(exc, max_retries=10, max_delay=5) + assert len(sleeps) == 10 + assert max(sleeps) <= 5 + + +def test_retry_delay_without_jitter_is_exact_exponential_then_capped(): + _, sleeps, _ = _run_with_retry( + _HttpStatusError(500), + initial_delay=1, + exponential_base=2, + jitter=False, + max_retries=8, + max_delay=30, + ) + assert sleeps == [2, 4, 8, 16, 30, 30, 30, 30] + + +def test_retry_jitter_is_bounded(): + # Each wait is within [delay / 2, delay], where delay grows by exponential_base + # per retry (no random factor is compounded across retries). + exc = _HttpStatusError(500) + for seed in range(50): + import random + + random.seed(seed) + _, sleeps, _ = _run_with_retry(exc, max_retries=8, max_delay=100) + for i, slept in enumerate(sleeps): + delay = min(2 ** (i + 1), 100) + assert delay / 2 <= slept <= delay + + # Extremes of the random source map to the ends of the range + with patch("random.random", return_value=0.0): + _, sleeps, _ = _run_with_retry(exc, max_retries=3) + assert sleeps == [1, 2, 4] + with patch("random.random", return_value=1.0): + _, sleeps, _ = _run_with_retry(exc, max_retries=3) + assert sleeps == [2, 4, 8] + + +def test_retry_large_max_retries_does_not_overflow(): + _, sleeps, _ = _run_with_retry(_HttpStatusError(503), max_retries=1500) + assert len(sleeps) == 1500 + assert max(sleeps) <= 60 + + +def _register_failing_embedding(name, error): + """Register an embedding function that always raises `error`. + + Returns the class and a list that records every call. The function is + re-created from table metadata, so the call count has to live outside of it. + """ + calls = [] + + @register(name) + class FailingEmbeddingFunction(TextEmbeddingFunction): + def ndims(self): + return 4 + + def generate_embeddings(self, texts): + calls.append(len(texts)) + raise error + + return FailingEmbeddingFunction, calls + + +@pytest.mark.parametrize("status", [400, 404, 422]) +def test_permanent_embedding_error_is_not_retried(tmp_path, status): + """A permanent provider error (e.g. a misspelled model name) must surface + immediately from both `table.add` and `table.search` instead of being retried + with minutes of backoff.""" + error = _HttpStatusError(status, "The model `typo-embed` does not exist") + cls, calls = _register_failing_embedding(f"failing-embedding-{status}", error) + func = cls.create() # default max_retries=7 + + class Schema(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table("t", schema=Schema) + + with patch("time.sleep") as mock_sleep: + with pytest.raises(Exception, match="The model `typo-embed` does not exist"): + table.add([{"text": "hello"}]) + assert len(calls) == 1 + + with pytest.raises(_HttpStatusError, match="does not exist"): + table.search("hello").limit(1).to_list() + assert len(calls) == 2 + + mock_sleep.assert_not_called() + + +def test_transient_embedding_error_is_retried_in_table_add(tmp_path): + cls, calls = _register_failing_embedding( + "failing-embedding-503", _HttpStatusError(503) + ) + func = cls.create(max_retries=2) + + class Schema(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table("t", schema=Schema) + + with patch("time.sleep") as mock_sleep: + with pytest.raises(Exception, match="Maximum number of retries"): + table.add([{"text": "hello"}]) + + assert len(calls) == 3 + assert mock_sleep.call_count == 2 + assert all(call.args[0] <= 60 for call in mock_sleep.call_args_list) + + +@patch("time.sleep") +@pytest.mark.parametrize( + "error", + [ + pytest.param("missing_key", id="missing-api-key"), + pytest.param(ImportError("No module named 'voyageai'"), id="missing-package"), + ], +) +def test_no_retry_on_deterministic_errors(mock_sleep, error): + from lancedb.embeddings.utils import ( + api_key_not_found_help, + retry_with_exponential_backoff, + ) + + def func(): + if error == "missing_key": + api_key_not_found_help("voyageai") + raise error + + mock_func = MagicMock(side_effect=func) + wrapped_func = retry_with_exponential_backoff(mock_func, max_retries=3) + + with pytest.raises((ValueError, ImportError)): + wrapped_func() + + assert mock_func.call_count == 1 + assert mock_sleep.call_count == 0 + + +@patch("time.sleep") +def test_retry_on_wrapped_provider_error(mock_sleep): + """Providers such as Bedrock wrap throttling in a plain ValueError.""" + from lancedb.embeddings.utils import retry_with_exponential_backoff + + mock_func = MagicMock( + side_effect=[ + ValueError("Error raised by boto3 client: ThrottlingException"), + [0.1], + ] + ) + wrapped_func = retry_with_exponential_backoff(mock_func, max_retries=3) + + assert wrapped_func() == [0.1] + assert mock_func.call_count == 2 + assert mock_sleep.call_count == 1 + + +def test_openai_bad_request_partial_batch_recovery(): + # Regression test for issue #1677 + + # Fake exception types, avoids requiring the optional openai/httpx deps + class FakeBadRequestError(Exception): + pass + + class FakeAuthenticationError(Exception): + pass + + fake_openai_module = MagicMock() + fake_openai_module.BadRequestError = FakeBadRequestError + fake_openai_module.AuthenticationError = FakeAuthenticationError + + registry = get_registry() + model = registry.get("openai").create(name="text-embedding-ada-002") + + def fake_create(input, model=None, **kwargs): + # Full batch always rejected + if len(input) > 1: + raise FakeBadRequestError("bad request") + if input[0] == "bad text": + raise FakeBadRequestError("bad request") + embedding = MagicMock() + embedding.embedding = [0.1, 0.2, 0.3] + result = MagicMock() + result.data = [embedding] + return result + + mock_client = MagicMock() + mock_client.embeddings.create.side_effect = fake_create + + with ( + patch( + "lancedb.embeddings.openai.attempt_import_or_raise", + return_value=fake_openai_module, + ), + patch.object(type(model), "_openai_client", new_callable=lambda: mock_client), + ): + embeddings = model.generate_embeddings(["good text", "bad text"]) + + assert embeddings[0] == [0.1, 0.2, 0.3] + assert embeddings[1] is None + + def test_ollama_embeddings_pickle(): """OllamaEmbeddings must pickle even after the cached client is created.""" registry = get_registry() @@ -645,6 +1039,39 @@ def test_open_clip_opens_percent_encoded_file_uri(tmp_path): assert image.size == (4, 4) +def test_open_clip_model_in_eval_mode(): + """ + open_clip.create_model_and_transforms returns the model in training mode, + which leaves dropout, stochastic depth and batch norm in their training + behaviour. OpenCLIP must switch the model to eval mode before embedding. + """ + from lancedb.embeddings.open_clip import OpenClipEmbeddings + + class FakeModel: + training = True + + def to(self, device): + return self + + def eval(self): + self.training = False + return self + + open_clip = MagicMock() + open_clip.create_model_and_transforms.return_value = (FakeModel(), None, None) + + with patch( + "lancedb.embeddings.open_clip.attempt_import_or_raise", + return_value=open_clip, + ): + func = OpenClipEmbeddings(name="ViTamin-B", pretrained="datacomp1b") + + open_clip.create_model_and_transforms.assert_called_once_with( + "ViTamin-B", pretrained="datacomp1b" + ) + assert func._model.training is False + + def test_jina_generate_image_input_dict_local_path(tmp_path): """ JinaEmbeddings._generate_image_input_dict must accept a local image path @@ -663,3 +1090,38 @@ def test_jina_generate_image_input_dict_local_path(tmp_path): image_dict = JinaEmbeddings._generate_image_input_dict(image) assert "image" in image_dict assert isinstance(image_dict["image"], str) and len(image_dict["image"]) > 0 + + +def test_jina_embeddings_use_their_own_api_key(monkeypatch): + """Each JinaEmbeddings instance must send its own API key.""" + pytest.importorskip("requests") + monkeypatch.delenv("JINA_API_KEY", raising=False) + registry = get_registry() + registry.set_var("jina_key_a", "key-a") + registry.set_var("jina_key_b", "key-b") + func_a = registry.get("jina").create(api_key="$var:jina_key_a") + func_b = registry.get("jina").create(api_key="$var:jina_key_b") + + sent = [] + + def fake_post(session, url, json=None, **kwargs): + sent.append(session.headers["Authorization"]) + response = MagicMock() + response.json.return_value = {"data": [{"index": 0, "embedding": [0.0]}]} + return response + + with patch("requests.Session.post", fake_post): + func_a.compute_source_embeddings(["hello"]) + func_b.compute_source_embeddings(["hello"]) + + assert sent == ["Bearer key-a", "Bearer key-b"] + + +def test_cohere_default_model_is_not_a_retired_v2_model(): + # Cohere retired embed-english-v2.0, embed-english-light-v2.0 and + # embed-multilingual-v2.0 on April 4, 2026. + cohere = get_registry().get("cohere").create() + + assert cohere.name == "embed-multilingual-v3.0" + assert "v2.0" not in cohere.name + assert cohere.ndims() == 1024 diff --git a/python/python/tests/test_embeddings_slow.py b/python/python/tests/test_embeddings_slow.py index b584598c7..4de85070f 100644 --- a/python/python/tests/test_embeddings_slow.py +++ b/python/python/tests/test_embeddings_slow.py @@ -272,7 +272,7 @@ def test_cohere_embedding_function(): cohere = ( get_registry() .get("cohere") - .create(name="embed-multilingual-v2.0", max_retries=0) + .create(name="embed-multilingual-v3.0", max_retries=0) ) class TextModel(LanceModel): diff --git a/python/python/tests/test_errors.py b/python/python/tests/test_errors.py index 338b6a0d7..0e362e5d8 100644 --- a/python/python/tests/test_errors.py +++ b/python/python/tests/test_errors.py @@ -3,7 +3,28 @@ import pickle +import pytest + +from lancedb.db import DBConnection from lancedb.remote.errors import HttpError, LanceDBClientError, RetryError +from lancedb.table import Table + + +@pytest.mark.parametrize( + "base, method", + [ + (Table, "to_lance"), + (Table, "to_polars"), + (DBConnection, "drop_all_tables"), + (DBConnection, "drop_database"), + ], +) +def test_base_unsupported_methods_have_messages(base, method): + with pytest.raises(NotImplementedError) as exc_info: + getattr(base, method)(None) + message = str(exc_info.value) + assert method in message + assert "not supported" in message def test_pickle_lancedb_client_error(): diff --git a/python/python/tests/test_experimental_functions.py b/python/python/tests/test_experimental_functions.py new file mode 100644 index 000000000..81de84606 --- /dev/null +++ b/python/python/tests/test_experimental_functions.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import lancedb +import pytest + +pytestmark = pytest.mark.skipif( + lancedb._lancedb._experimental_functions_enabled, + reason="tests the default build without experimental-functions", +) + + +@pytest.mark.parametrize("namespace", [False, True]) +def test_default_build_rejects_local_functions(tmp_path, namespace): + db = ( + lancedb.connect_namespace("dir", {"root": str(tmp_path)}) + if namespace + else lancedb.connect(tmp_path) + ) + table = db.create_table("source", [{"x": 1}, {"x": 2}]) + version = table.version + operations = [ + lambda: table.add_columns(computed={"doubled": "x * 2"}), + lambda: table.refresh_column("x"), + lambda: table.refresh_column_async("x"), + lambda: db.create_materialized_view("blocked", "source"), + lambda: db.create_materialized_view("blocked", "source", with_no_data=True), + lambda: db.create_materialized_view_async("blocked", "source"), + ] + for operation in operations: + with pytest.raises(NotImplementedError, match="experimental-functions"): + operation() + assert table.version == version + assert db.table_names() == ["source"] + table.add_columns({"eager": "x * 2"}) + assert table.to_arrow()["eager"].to_pylist() == [2, 4] + + +@pytest.mark.asyncio +async def test_async_default_build_rejects_local_functions(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("source", [{"x": 1}, {"x": 2}]) + version = await table.version() + operations = [ + lambda: table.add_columns(computed={"doubled": "x * 2"}), + lambda: table.refresh_column("x"), + lambda: table.refresh_column_async("x"), + lambda: db.create_materialized_view("blocked", "source"), + lambda: db.create_materialized_view("blocked", "source", with_no_data=True), + lambda: db.create_materialized_view_async("blocked", "source"), + ] + for operation in operations: + with pytest.raises(NotImplementedError, match="experimental-functions"): + await operation() + assert await table.version() == version + assert await db.table_names() == ["source"] + await table.add_columns({"eager": "x * 2"}) + assert (await table.query().to_arrow())["eager"].to_pylist() == [2, 4] diff --git a/python/python/tests/test_expr.py b/python/python/tests/test_expr.py index 0f49231f1..5d81b10c3 100644 --- a/python/python/tests/test_expr.py +++ b/python/python/tests/test_expr.py @@ -11,6 +11,7 @@ import pytest import lancedb from lancedb.expr import Expr, col, func, lit +from lancedb.index import FTS # ── unit tests for Expr construction ───────────────────────────────────────── @@ -80,6 +81,67 @@ class TestExprConstruction: e = lit(d) assert isinstance(e, Expr) + @pytest.mark.parametrize( + "value, decimal_type", + [ + ("1E-7", pa.decimal128(12, 7)), + ("-1.23E-7", pa.decimal128(12, 9)), + ("1E+3", pa.decimal128(12, 0)), + ("-1.23E+5", pa.decimal128(12, 0)), + ("0E-7", pa.decimal128(12, 7)), + ("-0E+3", pa.decimal128(12, 0)), + ("1E-38", pa.decimal128(38, 38)), + ("1E+37", pa.decimal128(38, 0)), + ("1.234567890123456789012345678901234567E+37", pa.decimal128(38, 0)), + ("0E+128", pa.decimal128(1, 0)), + ], + ) + def test_lit_decimal_exponent_query(self, tmp_path, value, decimal_type): + expected = Decimal(value) + table = lancedb.connect(tmp_path).create_table( + "decimals", + pa.table( + { + "id": [1, 2], + # Arrow's Python ingestion rejects 0E+128 even though its + # numeric value is representable. Store canonical zero to + # exercise the expression literal independently of ingestion. + "price": pa.array( + [Decimal(0) if expected.is_zero() else expected, None], + type=decimal_type, + ), + } + ), + ) + predicate = col("price") == lit(expected) + result = table.search().where(predicate).to_arrow() + assert result["id"].to_pylist() == [1] + assert result["price"].to_pylist() == [expected] + # Exercise the SQL serializer and parser as well as the typed query path. + sql_result = table.search().where(predicate.to_sql()).to_arrow() + assert sql_result["id"].to_pylist() == [1] + assert sql_result["price"].to_pylist() == [expected] + + @pytest.mark.parametrize( + "value", + [ + "NaN", + "sNaN", + "Infinity", + "-Infinity", + "1E-39", + "1E+38", + "1E+129", + "1E+1000000000", + "0E+129", + "12345678901234567890123456789012345678E+1", + "9" * 39, + ], + ) + def test_lit_decimal_unrepresentable_raises(self, value): + with pytest.raises(ValueError): + lit(Decimal(value)) + class TestExprOperators: def test_eq_operator(self): @@ -322,6 +384,68 @@ class TestExprRepr: {e: 1} +class TestExprTruthiness: + """``bool(Expr)`` must raise instead of silently keeping one operand.""" + + def test_bool_raises(self): + with pytest.raises(TypeError, match="truth value of an Expr is ambiguous"): + bool(col("x") == 1) + + def test_bool_error_points_to_operators(self): + with pytest.raises(TypeError, match=r"'&'.*'\|'.*'~'"): + bool(col("x") > 1) + + def test_and_raises(self): + with pytest.raises(TypeError, match="ambiguous"): + (col("id") > 7) and (col("g") == 0) # noqa: B015 + + def test_or_raises(self): + with pytest.raises(TypeError, match="ambiguous"): + (col("id") > 7) or (col("g") == 0) # noqa: B015 + + def test_not_raises(self): + with pytest.raises(TypeError, match="ambiguous"): + not (col("id") > 7) # noqa: B015 + + def test_chained_comparison_raises(self): + with pytest.raises(TypeError, match="ambiguous"): + lit(2) < col("id") < lit(5) # noqa: B015 + with pytest.raises(TypeError, match="ambiguous"): + 2 < col("id") < 5 # noqa: B015 + + def test_if_raises(self): + with pytest.raises(TypeError, match="ambiguous"): + if col("x"): + pass + + def test_membership_in_list_raises(self): + # list membership evaluates ``item == expr`` and calls bool() on the + # result, which used to be silently (and wrongly) True. + with pytest.raises(TypeError, match="ambiguous"): + col("x") in [1, 2, 3] # noqa: B015 + + def test_any_all_raise(self): + with pytest.raises(TypeError, match="ambiguous"): + any([col("x") > 1]) + with pytest.raises(TypeError, match="ambiguous"): + all([col("x") > 1]) + + def test_operators_still_combine(self): + a, b = col("id") > 7, col("g") == 0 + assert (a & b).to_sql() == "((id > 7) AND (g = 0))" + assert (a | b).to_sql() == "((id > 7) OR (g = 0))" + assert (~a).to_sql() == "NOT (id > 7)" + assert ((lit(2) < col("id")) & (col("id") < lit(5))).to_sql() == ( + "((2 < id) AND (id < 5))" + ) + + def test_identity_and_isinstance_checks_do_not_use_truthiness(self): + e = col("x") == 1 + assert e is not None + assert isinstance(e, Expr) + assert e is e + + class TestExprReflexive: def test_reflexive_eq(self): e = 1 == col("x") @@ -730,3 +854,121 @@ class TestExprDatetimeTimezoneIntegration: sql = lit(ts).to_sql() # Must encode 10:00 wall clock, not 10:00+local_offset. assert "2024-07-01 10:00:00" in sql + + +# ── where(Expr) must never rely on the truthiness of the filter ────────────── + + +@pytest.fixture +def search_table(tmp_path): + db = lancedb.connect(str(tmp_path)) + data = pa.table( + { + "id": list(range(12)), + "g": [i % 2 for i in range(12)], + "text": ["keep" if i < 9 else "other" for i in range(12)], + "vector": pa.FixedSizeListArray.from_arrays( + pa.array([float(i) for i in range(12) for _ in range(2)], pa.float32()), + 2, + ), + } + ) + table = db.create_table("search", data) + table.create_index("text", config=FTS()) + return table + + +def _ids(rows): + return sorted(r["id"] for r in rows) + + +class TestExprWhereBuilders: + def test_chained_comparison_is_rejected_before_querying(self, search_table): + # The silent bug: this used to return ids 0..4 (lower bound dropped). + with pytest.raises(TypeError, match="ambiguous"): + search_table.search().where(lit(2) < col("id") < lit(5)) + + def test_plain_where_expr(self, search_table): + where = (lit(2) < col("id")) & (col("id") < lit(5)) + rows = search_table.search().where(where).limit(100).to_list() + assert _ids(rows) == [3, 4] + + def test_vector_where_expr(self, search_table): + where = (col("id") > lit(7)) & (col("g") == lit(0)) + rows = search_table.search([0.0, 0.0]).where(where).limit(100).to_list() + assert _ids(rows) == [8, 10] + + def test_fts_where_expr(self, search_table): + where = (col("id") > lit(3)) | (col("g") == lit(1)) + rows = ( + search_table.search("keep", query_type="fts") + .where(where) + .limit(100) + .to_list() + ) + # "keep" matches ids 0..8; filter keeps id > 3 or odd ids. + assert _ids(rows) == [1, 3, 4, 5, 6, 7, 8] + + def test_hybrid_where_expr(self, search_table): + # The hybrid builder used to test ``if self._where:``; that must not + # call bool() on an Expr now that it raises. + where = (col("id") > lit(3)) & (col("g") == lit(0)) + rows = ( + search_table.search(query_type="hybrid") + .vector([0.0, 0.0]) + .text("keep") + .where(where) + .limit(100) + .to_list() + ) + # Hybrid search fuses the vector and FTS results, and the filter applies + # to both sides: the vector side alone returns every row passing it. + assert _ids(rows) == [4, 6, 8, 10] + + def test_hybrid_where_sql_string_still_works(self, search_table): + rows = ( + search_table.search(query_type="hybrid") + .vector([0.0, 0.0]) + .text("keep") + .where("id > 3 AND g = 0") + .limit(100) + .to_list() + ) + assert _ids(rows) == [4, 6, 8, 10] + + def test_hybrid_empty_where_is_ignored(self, search_table): + rows = ( + search_table.search(query_type="hybrid") + .vector([0.0, 0.0]) + .text("keep") + .where("") + .limit(100) + .to_list() + ) + assert _ids(rows) == list(range(12)) + + def test_repeated_where_expr_combines(self, search_table): + rows = ( + search_table.search() + .where(col("id") > lit(2)) + .where(col("id") < lit(5)) + .limit(100) + .to_list() + ) + assert _ids(rows) == [3, 4] + + def test_query_model_with_expr_filter(self, search_table): + query = search_table.search().where(col("id") > lit(2)).to_query_object() + assert isinstance(query.filter, Expr) + + @pytest.mark.asyncio + async def test_async_where_expr(self, tmp_path): + db = await lancedb.connect_async(str(tmp_path)) + table = await db.create_table( + "t", pa.table({"id": list(range(12)), "g": [i % 2 for i in range(12)]}) + ) + where = (col("id") > lit(7)) & (col("g") == lit(0)) + rows = await table.query().where(where).to_list() + assert _ids(rows) == [8, 10] + with pytest.raises(TypeError, match="ambiguous"): + table.query().where(lit(2) < col("id") < lit(5)) diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index b08dadf36..64a610b53 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -146,6 +146,27 @@ def test_function_version_identity_is_immutable_and_exact(): FunctionVersion(**{**value, "version": invalid}) +@pytest.mark.parametrize("source_digest", [None, "sha256:source-artifact"]) +def test_function_version_preserves_source_digest(source_digest): + value = job_result("remote_function_job.json") + legacy = FunctionVersion.from_json(json.dumps(value)) + assert legacy.source_digest is None + assert "source_digest" not in json.loads(legacy.to_canonical_json()) + + value["source_digest"] = source_digest + version = FunctionVersion.from_json(json.dumps(value)) + assert version.source_digest == source_digest + assert version.image == legacy.image + encoded = version.to_canonical_json() + if source_digest is None: + assert "source_digest" not in json.loads(encoded) + else: + assert json.loads(encoded)["source_digest"] == source_digest + assert FunctionVersion.from_json(encoded) == version + with pytest.raises((TypeError, ValueError)): + version.source_digest = "sha256:changed" + + def test_function_version_binds_named_columns_as_one_immutable_application(): version = FunctionVersion.from_json( json.dumps(job_result("remote_function_job.json")) @@ -398,8 +419,21 @@ class _FunctionDeclarationInner: def __init__(self): self.calls = [] - async def add_function_columns(self, application_json, output_name): - self.calls.append((json.loads(application_json), output_name)) + async def add_function_columns( + self, + application_json, + output_name, + auto_refresh_enabled, + auto_refresh_interval_seconds, + ): + self.calls.append( + ( + json.loads(application_json), + output_name, + auto_refresh_enabled, + auto_refresh_interval_seconds, + ) + ) return "declared" @@ -420,14 +454,18 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica ) assert result == "declared" assert inner.calls[-1][1] == "features" + assert inner.calls[-1][2:] == (None, None) bare = application._copy(update={"columns": {}}).rename( columns={"normalized_text": "search_text"} ) - result = await table.add_columns(bare) + result = await table.add_columns( + bare, auto_refresh_enabled=False, auto_refresh_interval_seconds=300 + ) assert result == "declared" assert inner.calls[-1][1] is None assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"} + assert inner.calls[-1][2:] == (False, 300) @pytest.mark.asyncio diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 9ee3e388a..562a90eb4 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -15,7 +15,6 @@ import os from pathlib import Path import subprocess import sys -import threading import urllib.parse from typing import Optional @@ -23,6 +22,7 @@ import pyarrow as pa import pytest import lancedb +from lancedb import BlobReader from lancedb.functions import ( PythonRuntimeSpec, SecretBinding, @@ -33,6 +33,7 @@ from lancedb.functions import ( udf, ) from lancedb.secrets import EnvVarSecret +from utils import start_server_thread THRESHOLD = 20 _CACHE = None @@ -88,6 +89,27 @@ def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): } +@pytest.mark.parametrize( + "name", ["examples.image_info", "image-info", "image_info.", "image_info-"] +) +def test_udf_rejects_function_names_with_periods_or_hyphens(name): + with pytest.raises(ValueError, match="invalid Function name"): + + @udf(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 image_info(value: int) -> int: + return value + + assert image_info.registration_request.name == name + assert image_info(1) == 1 + + def test_secret_bound_udf_matches_its_shared_registration_golden(): assert analyze_caption(" hello ") == "hello" bound = analyze_caption.bind_secrets( @@ -273,13 +295,15 @@ class Handler(http.server.BaseHTTPRequestHandler): self.wfile.write(payload) -server = http.server.ThreadingHTTPServer(("localhost", 0), Handler) -threading.Thread(target=server.serve_forever, daemon=True).start() +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: db = lancedb.connect( "db://dev", api_key="API_KEY_SENTINEL", - host_override="http://localhost:%d" % server.server_address[1], + host_override="http://127.0.0.1:%d" % server.server_address[1], client_config={"retry_config": {"retries": 0}}, ) db.create_secret("openai-prod", "SECRET_VALUE_SENTINEL") @@ -470,6 +494,30 @@ def test_udf_conda_environment(): udf(name="channels", conda_channels=["conda-forge"])(lambda value: value) +def test_udf_apt_system_packages(): + @udf(pip=["torchcodec"], apt=["libavutil58", "libavcodec60", "libavutil58"]) + def decode(value: float) -> float: + return value + + request = json.loads(decode.registration_request.to_canonical_json()) + assert request["runtime"]["environment"] == { + "kind": "pip", + "packages": ["torchcodec"], + "system_packages": ["libavcodec60", "libavutil58"], + } + + @udf(conda=["numpy"], apt=["libsndfile1"]) + def conda_decode(value: float) -> float: + return value + + request = json.loads(conda_decode.registration_request.to_canonical_json()) + assert request["runtime"]["environment"]["system_packages"] == ["libsndfile1"] + 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) + + def test_udf_gpu_marker_uses_gpu_runtime(): @udf(pip=["cupy-cuda12x"], gpu=True) def double_on_gpu(value: int) -> int: @@ -966,6 +1014,60 @@ def test_blob_fields_use_the_scalar_function_semantic_type(): assert signature.output.arrow_type == "blob_v2" +def test_blob_input_access_is_inferred_from_annotations(): + @udf + def read_blob(video: BlobReader, timestamp_s: float) -> bytes: + video.seek(int(timestamp_s)) + return video.read(4) + + @udf + def read_bytes(video: bytes) -> int: + return len(video) + + reader = read_blob.registration_request.signature + assert reader.inputs[0].arrow_type == "blob_v2" + assert reader.inputs[0].blob_access == "reader" + assert reader.inputs[1].blob_access is None + assert reader.output.arrow_type == "binary" + eager = read_bytes.registration_request.signature.inputs[0] + assert eager.arrow_type == "binary" + assert eager.blob_access == "bytes" + encoded = json.loads(read_blob.registration_request.to_canonical_json()) + assert encoded["signature"]["inputs"][0]["blob_access"] == "reader" + + +def test_nullable_blob_reader_and_explicit_blob_bytes(): + @udf + def nullable(video: Optional[BlobReader]) -> int: + return 0 if video is None else video.size() + + @udf( + input_schema=pa.schema([lancedb.blob("video", nullable=False)]), + output_schema=pa.field("size", pa.int64(), nullable=False), + ) + def eager(video: bytes) -> int: + return len(video) + + parameter = nullable.registration_request.signature.inputs[0] + assert parameter.nullable is True + assert parameter.blob_access == "reader" + parameter = eager.registration_request.signature.inputs[0] + assert parameter.arrow_type == "blob_v2" + assert parameter.blob_access == "bytes" + + +def test_blob_reader_rejects_an_incompatible_explicit_schema(): + def read(video: BlobReader) -> int: + return video.size() + + with pytest.raises(TypeError, match="requires a Blob V2 field"): + udf( + read, + input_schema=pa.schema([pa.field("video", pa.int64(), nullable=False)]), + output_schema=pa.field("size", pa.int64(), nullable=False), + ) + + def test_whole_named_struct_function_can_include_a_blob_result_field(): @udf( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), @@ -1419,7 +1521,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): def nullable_output(value: int) -> Optional[int]: return value - with pytest.raises(ValueError, match="provided together"): + with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"): @udf(input_schema=pa.schema([pa.field("value", pa.int64())])) def partial_schema(value): @@ -1575,6 +1677,7 @@ def _mock_remote_function_catalog(): ).read_text() )["image"], "signature": body["signature"], + "source_digest": body["artifact"]["digest"], "secret_bindings": body.get("secret_bindings", []), "created_at_millis": 1787270400000, # 2026-08-21T00:00:00Z } @@ -1654,11 +1757,10 @@ def _mock_remote_function_catalog(): response = {"functions": []} self._write_response(200, response) - with http.server.HTTPServer(("localhost", 0), Handler) as server: - thread = threading.Thread(target=server.serve_forever) - thread.start() + with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) try: - yield f"http://localhost:{server.server_address[1]}", state + yield f"http://127.0.0.1:{server.server_address[1]}", state finally: server.shutdown() thread.join() @@ -1674,12 +1776,19 @@ def test_remote_registration_job_and_exact_version_reopen_round_trip(): ) 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() @@ -1786,6 +1895,7 @@ def test_blocking_remote_registration_returns_function_version(): 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", @@ -1805,6 +1915,9 @@ def test_remote_list_functions_paginates_and_returns_typed_versions(): functions = list(db.list_functions()) assert functions == [created] + assert functions[0].source_digest == ( + normalize_score.registration_request.artifact.digest + ) assert state["requests"] == [ ("/v1/namespace/$/function/list", {"include_definition": "true"}), ( @@ -1829,6 +1942,9 @@ async def test_async_remote_list_functions_returns_typed_versions(): 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", @@ -1971,3 +2087,21 @@ def test_a_function_namespace_path_must_be_a_list_of_segments(): list(db.list_functions(namespace_path="analytics")) assert state["requests"] == [] + + +def test_one_explicit_schema_infers_the_other_from_annotations(): + @udf(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)) + def explicit_output(value: Optional[int]): + return float(value or 0) + + for fn in (explicit_input, explicit_output): + signature = fn.registration_request.signature + assert [(p.name, p.arrow_type, p.nullable) for p in signature.inputs] == [ + ("value", "int64", True) + ] + assert explicit_input.registration_request.signature.output.arrow_type == "float64" + assert explicit_output.registration_request.signature.output.arrow_type == "float32" diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index d7fa2e0ec..6714f35d9 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -26,7 +26,9 @@ from lancedb.db import DBConnection from lancedb.index import FTS from lancedb.query import ( BoostQuery, + CombinedFieldsQuery, DocumentGranularity, + FullTextOperator, MatchQuery, MultiMatchQuery, PhraseQuery, @@ -384,13 +386,27 @@ def test_custom_stop_words_list(table): assert [token.text for token in tokens] == ["the", "data"] empty_tokens = ldb.tokenize("the lance data", stem=False, custom_stop_words=[]) assert [token.text for token in empty_tokens] == ["the", "lance", "data"] - with pytest.raises(TypeError, match=r"custom_stop_words.*int"): + with pytest.raises(TypeError, match=r"'int' object is not an instance of 'str'"): ldb.tokenize( "the lance data", custom_stop_words=["lance", 42], ) +def test_list_indices_with_missing_fts_files(table): + # Regression test for https://github.com/lancedb/lancedb/issues/4250 + table.create_fts_index("text") + table.create_scalar_index("id") + + fts = next(i for i in table.list_indices() if i.index_type == "FTS") + shutil.rmtree(Path(table.uri) / "_indices" / fts.index_uuid) + + indices = {i.name: i for i in table.list_indices()} + assert set(indices) == {"text_idx", "id_idx"} + assert indices["text_idx"].index_type == "FTS" + assert indices["text_idx"].columns == ["text"] + + def test_search_fts(table): table.create_fts_index("text") results = table.search("puppy").select(["id", "text"]).limit(5).to_list() @@ -570,6 +586,52 @@ async def test_search_fts_phrase_query_async(async_table): assert len(phrase_results) > 0 +@pytest.mark.asyncio +@pytest.mark.parametrize("columns", [None, ["text"]]) +async def test_phrase_query_to_query_object_async(tmp_path, columns): + db = await ldb.connect_async(tmp_path) + table = await db.create_table( + "phrases", pa.table({"text": ["puppy runs fast", "cat sleeps"]}) + ) + await table.create_index("text", config=FTS(with_position=True)) + + query = table.query().nearest_to_text('"puppy runs"', columns=columns) + phrase = query.to_query_object().full_text_query.query + + expected = ( + PhraseQuery("puppy runs", "text") if columns else PhraseQuery("puppy runs") + ) + assert phrase == expected + results = await table.query().nearest_to_text(phrase).to_list() + assert [row["text"] for row in results] == ["puppy runs fast"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("column", [None, "text"]) +async def test_phrase_query_object_roundtrip_async(tmp_path, column): + db = await ldb.connect_async(tmp_path) + table = await db.create_table( + "phrases", + pa.table({"text": ["puppy runs fast", "puppy often runs", "cat sleeps"]}), + ) + await table.create_index("text", config=FTS(with_position=True)) + phrase = PhraseQuery( + "puppy runs", column, slop=1, document_granularity=DocumentGranularity.ROW + ) + query = table.query().nearest_to_text(phrase) + + assert query.to_query_object().full_text_query.query == phrase + serialized = json.loads(phrase.to_json())["phrase"] + assert serialized["slop"] == 1 + assert serialized["document_granularity"] == "row" + assert serialized.get("column") == column + results = await query.to_list() + assert sorted(row["text"] for row in results) == [ + "puppy often runs", + "puppy runs fast", + ] + + def test_search_fts_specify_column(table): table.create_fts_index("text") table.create_fts_index("text2") @@ -1307,6 +1369,103 @@ def test_match_query_fuzziness_search(tmp_db, options, expected): assert sorted(row["text"] for row in results) == sorted(expected) +@pytest.mark.parametrize( + "operator,combined_ids,multi_match_ids", + [ + # Combined fields treat the columns as one field, so AND also matches + # row 0, where "john" is in the title and "smith" is in the body. + (FullTextOperator.AND, {0, 1}, {1}), + (FullTextOperator.OR, {0, 1, 2}, {0, 1, 2}), + ], +) +def test_combined_fields_query(mem_db, operator, combined_ids, multi_match_ids): + table = mem_db.create_table( + "people", + pa.table( + { + "id": [0, 1, 2], + "title": ["john", "john smith", "john"], + "body": ["smith", "foo", "alice"], + } + ), + ) + table.create_index("title", config=FTS()) + table.create_index("body", config=FTS()) + + def ids(query): + return {row["id"] for row in table.search(query).select(["id"]).to_list()} + + combined = CombinedFieldsQuery("john smith", ["title", "body"], operator=operator) + multi_match = MultiMatchQuery("john smith", ["title", "body"], operator=operator) + assert ids(combined) == combined_ids + assert ids(multi_match) == multi_match_ids + + +def test_combined_fields_query_boosts(mem_db): + table = mem_db.create_table( + "docs", pa.table({"title": ["hello"], "body": ["world"]}) + ) + table.create_index("title", config=FTS()) + table.create_index("body", config=FTS()) + + results = table.search( + CombinedFieldsQuery("hello", ["title", "body"], boosts=[1.5, 1.0]) + ).to_list() + assert len(results) == 1 + + # Each weight must be at least 1, and there must be one per column. + with pytest.raises(ValueError, match="boost"): + table.search( + CombinedFieldsQuery("hello", ["title", "body"], boosts=[0.5, 1.0]) + ).to_list() + with pytest.raises(ValueError, match="boosts"): + table.search( + CombinedFieldsQuery("hello", ["title", "body"], boosts=[1.0]) + ).to_list() + + +@pytest.mark.asyncio +async def test_combined_fields_query_round_trip(mem_db_async): + table = await mem_db_async.create_table( + "docs", pa.table({"title": ["hello"], "body": ["world"]}) + ) + query = CombinedFieldsQuery( + "hello world", + ["title", "body"], + boosts=[2.0, 1.0], + operator=FullTextOperator.AND, + ) + + query_obj = table.query().nearest_to_text(query).to_query_object() + + assert query_obj.full_text_query.query == query + + +@pytest.mark.asyncio +async def test_combined_fields_query_nested_round_trip(mem_db_async): + table = await mem_db_async.create_table( + "docs", pa.table({"title": ["hello"], "body": ["world"]}) + ) + query = BooleanQuery( + [ + ( + Occur.MUST, + CombinedFieldsQuery( + "hello world", + ["title", "body"], + boosts=[2.0, 1.0], + operator=FullTextOperator.AND, + ), + ), + (Occur.MUST_NOT, MatchQuery("draft", "body")), + ] + ) + + query_obj = table.query().nearest_to_text(query).to_query_object() + + assert query_obj.full_text_query.query == query + + def test_fts_query_to_json(): """Test that FTS query to_json() produces valid JSON strings with exact format.""" @@ -1444,6 +1603,17 @@ def test_fts_query_to_json(): ) assert json_str == expected + # Test CombinedFieldsQuery + combined_fields = CombinedFieldsQuery( + "python", ["tags", "title"], boosts=[2.0, 1.0], operator=FullTextOperator.AND + ) + json_str = combined_fields.to_json() + expected = ( + '{"combined_fields":{"query":"python","columns":["tags","title"],' + '"boost":[2.0,1.0],"operator":"And"}}' + ) + assert json_str == expected + # Test complex nested BooleanQuery inner1 = BooleanQuery( [ diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 6e1e1cf43..a61588777 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -11,9 +11,10 @@ import json import subprocess import sys import textwrap +import types import warnings from pathlib import Path -from typing import Annotated, Optional +from typing import Annotated, Optional, get_type_hints import pyarrow as pa import pytest @@ -126,6 +127,136 @@ def test_function_without_initialization_keeps_its_wire_form(): assert request["artifact"]["kind"] == "python_callable" +@pytest.mark.parametrize("annotation", ["Array", "RecordBatch"]) +@pytest.mark.parametrize("kind", ["function", "class"]) +def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_package): + if kind == "class": + source = f""" + import pyarrow as pa + + class identity: + def __call__(self, value: pa.{annotation}) -> pa.{annotation}: + return value + """ + else: + source = f""" + import pyarrow as pa + + def identity(value: pa.{annotation}) -> pa.{annotation}: + return value + """ + module = helper_package("fx_batch_annotations", {"__init__.py": source}) + with pytest.raises(TypeError, match="input_schema and output_schema"): + udf(module.identity) + + +def test_array_batch_annotations_accept_explicit_schemas(): + @udf( + input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + output_schema=pa.int64(), + ) + def identity(value: pa.Array) -> pa.Array: + return value + + signature = identity.registration_request.signature + assert [(p.name, p.arrow_type, p.nullable) for p in signature.inputs] == [ + ("value", "int64", False) + ] + assert signature.output.arrow_type == "int64" + assert signature.output.nullable is False + values = pa.array([1, 2, 3]) + assert identity(values).equals(values) + + +@pytest.mark.parametrize("class_udf", [False, True]) +@pytest.mark.parametrize("postponed", [False, True]) +@pytest.mark.parametrize( + ("annotation", "nullable"), + [ + ("BlobReader", False), + ("Reader", False), + ('"Reader"', False), + ("Reader | None", True), + ("Optional[Reader]", True), + ('Optional["Reader"]', True), + ("MaybeReader", True), + ("lancedb.BlobReader", False), + ("lancedb.BlobReader | None", True), + ], +) +def test_blob_reader_annotations_resolve_in_the_artifact( + helper_package, monkeypatch, class_udf, postponed, annotation, nullable +): + definition = ( + f"class read_blob:\n" + f" def __call__(self, video: {annotation}) -> int:\n" + f" return 0\n" + if class_udf + else f"def read_blob(video: {annotation}) -> int:\n return 0\n" + ) + module = helper_package( + "fx_blob_annotations", + { + "__init__.py": ( + ("from __future__ import annotations\n" if postponed else "") + + "import lancedb\n" + "from typing import Optional\n" + "from lancedb import BlobReader, BlobReader as Reader\n" + "from lancedb.functions import udf\n" + "MaybeReader = Optional[Reader]\n\n" + f"@udf\n{definition}" + ) + }, + ) + request = module.read_blob.registration_request + parameter = request.signature.inputs[0] + assert parameter.arrow_type == "blob_v2" + assert parameter.blob_access == "reader" + assert parameter.nullable is nullable + + # Workers provide lance_blob rather than importing the client SDK's reader. + worker = types.ModuleType("lance_blob") + worker.BlobReader = type("BlobReader", (), {}) + monkeypatch.setitem(sys.modules, "lance_blob", worker) + namespace = {} + exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace) + packaged = namespace["read_blob"] + if class_udf: + packaged = packaged.__call__ + assert get_type_hints(packaged) == { + "video": Optional[worker.BlobReader] if nullable else worker.BlobReader, + "return": int, + } + + +def test_blob_reader_annotation_does_not_shadow_body_globals( + helper_package, monkeypatch +): + module = helper_package( + "fx_blob_annotation_globals", + { + "__init__.py": """ + from lancedb import BlobReader + from lancedb.functions import udf + + _lance_blob_reader = 7 + + @udf + def read_blob(video: BlobReader) -> int: + return _lance_blob_reader + """ + }, + ) + worker = types.ModuleType("lance_blob") + worker.BlobReader = type("BlobReader", (), {}) + monkeypatch.setitem(sys.modules, "lance_blob", worker) + namespace = {} + exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace) + packaged = namespace["read_blob"] + assert get_type_hints(packaged)["video"] is worker.BlobReader + assert packaged(worker.BlobReader()) == 7 + + @pytest.mark.parametrize( ("init", "message"), [ diff --git a/python/python/tests/test_header_provider.py b/python/python/tests/test_header_provider.py index 187b0a50a..9d19e7bef 100644 --- a/python/python/tests/test_header_provider.py +++ b/python/python/tests/test_header_provider.py @@ -114,6 +114,30 @@ class TestOAuthProvider: "x-lancedb-credential-type": "oidc", } + def test_zero_lifetime_token_is_refreshed(self): + """A token that expires immediately must not be cached indefinitely.""" + call_count = 0 + + def fetcher(): + nonlocal call_count + call_count += 1 + return { + "access_token": f"token{call_count}", + "expires_in": 0, + } + + provider = OAuthProvider(fetcher, refresh_buffer_seconds=0) + + assert provider.get_headers() == { + "Authorization": "Bearer token1", + "x-lancedb-credential-type": "oidc", + } + assert provider.get_headers() == { + "Authorization": "Bearer token2", + "x-lancedb-credential-type": "oidc", + } + assert call_count == 2 + def test_missing_access_token(self): """Test error handling when access_token is missing.""" diff --git a/python/python/tests/test_huggingface.py b/python/python/tests/test_huggingface.py index 9b597bbc9..91421b79c 100644 --- a/python/python/tests/test_huggingface.py +++ b/python/python/tests/test_huggingface.py @@ -129,3 +129,106 @@ def test_generator(tmp_path: Path): assert len(tbl) == 2 assert tbl.schema == ds.features.arrow_schema + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("operation", ["create", "add"]) +@pytest.mark.parametrize( + "selection", + ["normal", "contiguous", "selected", "duplicates", "filtered", "shuffled", "empty"], +) +async def test_write_selected_hf_dataset(tmp_path, asynchronous, operation, selection): + source = datasets.Dataset.from_dict({"id": list(range(5)), "text": list("abcde")}) + data = { + "normal": source, + "contiguous": source.select(range(1, 4)), + "selected": source.select([4, 1]), + "duplicates": source.select([2, 2, 0]), + "filtered": source.filter(lambda row: row["id"] % 2 == 1), + "shuffled": source.shuffle(seed=42), + "empty": source.select([]), + }[selection] + expected = data.to_list() + if asynchronous: + db = await lancedb.connect_async(tmp_path) + if operation == "create": + table = await db.create_table("selected", data) + else: + table = await db.create_table("selected", schema=data.features.arrow_schema) + await table.add(data) + actual = await table.to_arrow() + else: + db = lancedb.connect(tmp_path) + if operation == "create": + table = db.create_table("selected", data) + else: + table = db.create_table("selected", schema=data.features.arrow_schema) + table.add(data) + actual = table.to_arrow() + assert actual.to_pylist() == expected + assert actual.schema.equals(data.features.arrow_schema, check_metadata=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("operation", ["create", "add"]) +async def test_write_selected_hf_splits(tmp_path, asynchronous, operation): + source = datasets.Dataset.from_dict({"id": list(range(5)), "text": list("abcde")}) + data = datasets.DatasetDict( + { + "train": source.select([4, 1]), + "test": source.select([3, 0, 2]), + "empty": source.select([]), + } + ) + expected = [ + dict(row, split=split) + for split, dataset in data.items() + for row in dataset.to_list() + ] + schema = source.features.arrow_schema.append(pa.field("split", pa.string())) + if asynchronous: + db = await lancedb.connect_async(tmp_path) + if operation == "create": + table = await db.create_table("splits", data) + else: + table = await db.create_table("splits", schema=schema) + await table.add(data) + actual = await table.to_arrow() + else: + db = lancedb.connect(tmp_path) + if operation == "create": + table = db.create_table("splits", data) + else: + table = db.create_table("splits", schema=schema) + table.add(data) + actual = table.to_arrow() + assert actual.to_pylist() == expected + assert actual.schema.equals(schema, check_metadata=True) + + +@pytest.mark.parametrize("format_type", [None, "numpy", "pandas", "arrow"]) +@pytest.mark.parametrize("empty", [False, True]) +def test_selected_hf_reader_is_rescannable(format_type, empty): + from lancedb.scannable import _register_optional_converters, to_scannable + + source = datasets.Dataset.from_dict( + {"id": list(range(2105)), "text": [str(i) for i in range(2105)]} + ) + indices = [] if empty else list(reversed(range(2105))) + [1, 1] + data = source.select(indices).with_format(format_type, columns=["id"]) + original_format = data.format + expected = source.select(indices).to_list() + _register_optional_converters() + scannable = to_scannable(data) + assert scannable.rescannable + assert scannable.num_rows == len(expected) + for _ in range(2): + batches = list(scannable.reader()) + if not empty: + assert all(batch.num_rows <= 1000 for batch in batches) + actual = pa.Table.from_batches(batches, schema=scannable.schema) + assert actual.to_pylist() == expected + assert actual.schema.equals(data.features.arrow_schema, check_metadata=True) + assert data.format == original_format diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index 8d670a136..c432bac59 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -315,13 +315,53 @@ def test_hybrid_query_offset(sync_table: Table): assert offset_result["_rowid"].to_pylist() == full["_rowid"].to_pylist()[2:] +@pytest.mark.parametrize( + "query_vector", + [ + pytest.param((0.0, 0.4), id="tuple"), + pytest.param(pa.array([0.0, 0.4], type=pa.float32()), id="pa-array"), + pytest.param( + pa.chunked_array([[0.0], [0.4]], type=pa.float32()), id="pa-chunked-array" + ), + ], +) +def test_hybrid_query_accepts_every_vector_container(sync_table: Table, query_vector): + # Vector search and the async hybrid API both accept tuples and pyarrow + # arrays for the query vector (``VEC`` in ``lancedb/common.py``), so the + # sync hybrid builder must accept them too. + expected = ( + sync_table.search(query_type="hybrid") + .vector([0.0, 0.4]) + .text("dog") + .limit(2) + .with_row_id(True) + .to_arrow() + ) + + result = ( + sync_table.search(query_type="hybrid") + .vector(query_vector) + .text("dog") + .limit(2) + .with_row_id(True) + .to_arrow() + ) + + assert result["_rowid"].to_pylist() == expected["_rowid"].to_pylist() + + def test_hybrid_query_default_limit(sync_table: Table): # The vector and FTS legs match disjoint rows, so fusing their results # yields more rows than the default limit. new_rows = [] + # Distinct distances and document lengths avoid ties in either leg, + # so comparing offset windows does not depend on tie ordering. for i in range(20): - new_rows.append({"text": "close_vec", "vector": [0.1, 0.1]}) - new_rows.append({"text": "dog", "vector": [50.0 + i, 50.0 + i]}) + coordinate = 0.11 + i * 0.001 + new_rows.append({"text": "close_vec", "vector": [coordinate, coordinate]}) + new_rows.append( + {"text": "dog " + "padding " * (i + 1), "vector": [50.0 + i, 50.0 + i]} + ) sync_table.add(new_rows) def query(): @@ -536,3 +576,15 @@ def test_normalize_scores(): assert pc.equal(result, expected), ( f"Expected {expected} but got {result} for invert={invert}" ) + + +def test_hybrid_query_rejects_query_with_vector(sync_table: Table): + # Pins the full message: the space between "hybrid search." and "But" is + # load-bearing (see the _validate_query literal concatenation). + with pytest.raises(ValueError) as excinfo: + sync_table.search("dog", query_type="hybrid").vector([0.5, -0.5]).to_arrow() + assert str(excinfo.value) == ( + "You can either provide a string query in search() method " + "or set `vector()` and `text()` explicitly for hybrid search. " + "But not both." + ) diff --git a/python/python/tests/test_import.py b/python/python/tests/test_import.py index 4b87a0ce8..e8373b03b 100644 --- a/python/python/tests/test_import.py +++ b/python/python/tests/test_import.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +import os import re import shutil import subprocess @@ -31,3 +32,36 @@ def test_native_extension_does_not_link_openssl(): "the LanceDB native extension must use rustls instead of linking OpenSSL: " f"{openssl_libraries}" ) + + +def test_top_level_version_comes_from_native_module(): + child_code = """ +import importlib.metadata + +orig_version = importlib.metadata.version + +def fail_version_lookup(_: str) -> str: + if _ in {"lancedb", "lancedb-compat"}: + raise AssertionError("lancedb import should not query distribution metadata") + return orig_version(_) + +importlib.metadata.version = fail_version_lookup + +import lancedb +import lancedb._lancedb as native_module +import lancedb.db + +assert lancedb.__version__ == native_module.__version__ +""" + 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], + check=False, + capture_output=True, + text=True, + env=env, + ) + + assert result.returncode == 0, result.stderr or result.stdout diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index fe6ebe87a..a1ec1e04b 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -364,6 +364,8 @@ async def test_create_vector_index(some_table: AsyncTable): assert indices[0].columns == ["vector"] assert indices[0].name == "vector_idx" + await some_table.prewarm_index(indices[0].name) + stats = await some_table.index_stats("vector_idx") assert stats.index_type == "IVF_PQ" assert stats.distance_type == "l2" @@ -421,13 +423,45 @@ async def test_create_4bit_ivfpq_index(some_table: AsyncTable): @pytest.mark.asyncio -async def test_create_ivfrq_index(some_table: AsyncTable): - await some_table.create_index("vector", config=IvfRq(num_bits=1)) +@pytest.mark.parametrize( + "config, expected_bits", + [ + pytest.param(IvfRq(), 5, id="default"), + pytest.param(IvfRq(num_bits=None), 5, id="none"), + pytest.param(IvfRq(num_bits=1), 1, id="one-bit"), + pytest.param(IvfRq(num_bits=4), 4, id="multi-bit"), + ], +) +async def test_create_ivfrq_index(some_table: AsyncTable, config, expected_bits): + await some_table.create_index("vector", config=config) indices = await some_table.list_indices() assert len(indices) == 1 assert indices[0].index_type == "IvfRq" assert indices[0].columns == ["vector"] assert indices[0].name == "vector_idx" + assert indices[0].index_details["compression"]["num_bits"] == expected_bits + + +@pytest.mark.asyncio +async def test_read_ivfrq_index_created_with_lance(db_async, some_table: AsyncTable): + pytest.importorskip("lance") + dataset = await some_table.to_lance() + dataset.create_index( + "vector", + index_type="IVF_RQ", + metric="cosine", + num_partitions=1, + ) + + # Open a fresh LanceDB handle so the index is discovered from disk. + table = await db_async.open_table("some_table") + indices = await table.list_indices() + assert len(indices) == 1 + assert indices[0].index_type == "IvfRq" + assert indices[0].columns == ["vector"] + + results = await table.query().nearest_to(list(range(DIM))).limit(8).to_arrow() + assert len(results) == 8 @pytest.mark.asyncio diff --git a/python/python/tests/test_listing.py b/python/python/tests/test_listing.py index 4a2745eb8..4cf37b631 100644 --- a/python/python/tests/test_listing.py +++ b/python/python/tests/test_listing.py @@ -5,12 +5,12 @@ import asyncio from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json from pathlib import Path -from threading import Thread from urllib.parse import parse_qs, urlsplit import lancedb from lancedb.remote.errors import HttpError import pytest +from utils import start_server_thread @pytest.fixture @@ -31,8 +31,7 @@ def listing_server(): do_POST = handle_request with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: - thread = Thread(target=server.serve_forever, daemon=True) - thread.start() + thread = start_server_thread(server, daemon=True) try: yield f"http://127.0.0.1:{server.server_port}", requests, responses finally: @@ -66,7 +65,7 @@ def response_page(kind, names, token): ] else: items = names - key = "views" if kind == "materialized_views" else kind + key = kind return {key: items, "page_token": token} @@ -85,7 +84,144 @@ async def advance(items, asynchronous): return await items.__anext__() if asynchronous else next(items) -KINDS = ["secrets", "views", "jobs", "functions", "materialized_views"] +KINDS = ["secrets", "views", "jobs", "functions"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_compatible_name_listing_pages(listing_server, kind, asynchronous): + endpoint, requests, responses = listing_server + responses.extend( + [ + (200, response_page(kind, ["a", "b"], "next")), + (200, response_page(kind, ["c"], None)), + ] + ) + db = await connection(endpoint, asynchronous) + listing = getattr(db, "list_" + kind)( + namespace_path=["team"], page_token="start", limit=2 + ) + field = kind + assert len(requests) == (0 if asynchronous else 1) + if asynchronous: + with pytest.raises(RuntimeError, match="Await or iterate"): + getattr(listing, field) + assert listing.page_token == "start" + assert await listing is listing + assert len(requests) == 1 + page_names = getattr(listing, field) + assert type(page_names) is list + assert page_names == ["a", "b"] + page_names.append("changed") + assert getattr(listing, field) == ["a", "b"] + assert listing.page_token == "next" + assert listing.num_page_results() == 2 + assert await advance(listing, asynchronous) == "a" + assert getattr(listing, field) == ["a", "b"] + assert await advance(listing, asynchronous) == "b" + assert len(requests) == 1 + assert await advance(listing, asynchronous) == "c" + assert getattr(listing, field) == ["c"] + assert listing.page_token is None + assert len(requests) == 2 + assert ([item async for item in listing] if asynchronous else list(listing)) == [] + if asynchronous: + assert await listing is listing + assert len(requests) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +async def test_name_listing_skips_empty_page_only_during_iteration( + listing_server, kind +): + endpoint, requests, responses = listing_server + responses.extend( + [ + (200, response_page(kind, [], "next")), + (200, response_page(kind, ["a"], None)), + ] + ) + db = await connection(endpoint, True) + listing = getattr(db, "list_" + kind)() + await listing + assert getattr(listing, kind) == [] + assert listing.page_token == "next" + assert len(requests) == 1 + assert [name async for name in listing] == ["a"] + assert len(requests) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_name_listing_zero_limit_uses_no_request( + listing_server, kind, asynchronous +): + endpoint, requests, _ = listing_server + db = await connection(endpoint, asynchronous) + listing = getattr(db, "list_" + kind)(limit=0) + if asynchronous: + assert await listing is listing + assert [name async for name in listing] == [] + else: + assert list(listing) == [] + assert getattr(listing, kind) == [] + assert listing.page_token is None + assert requests == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +async def test_name_listing_failure_retains_token(listing_server, kind): + endpoint, requests, responses = listing_server + responses.append((401, {})) + db = await connection(endpoint, True) + listing = getattr(db, "list_" + kind)(page_token="retry") + with pytest.raises(HttpError): + await listing + assert listing.page_token == "retry" + with pytest.raises(HttpError): + await listing + assert [name async for name in listing] == [] + assert len(requests) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +async def test_name_listing_direct_async_iteration(listing_server, kind): + endpoint, requests, responses = listing_server + responses.extend( + [ + (200, response_page(kind, ["a"], "next")), + (200, response_page(kind, ["b"], None)), + ] + ) + db = await connection(endpoint, True) + listing = getattr(db, "list_" + kind)(limit=1) + assert requests == [] + assert [name async for name in listing] == ["a", "b"] + assert getattr(listing, kind) == ["b"] + assert len(requests) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +async def test_name_listing_serializes_concurrent_advances(listing_server, kind): + endpoint, requests, responses = listing_server + responses.append((200, response_page(kind, ["a", "b"], None))) + db = await connection(endpoint, True) + listing = getattr(db, "list_" + kind)() + results = await asyncio.gather( + listing.__anext__(), + listing.__anext__(), + listing.__anext__(), + return_exceptions=True, + ) + assert results[:2] == ["a", "b"] + assert isinstance(results[2], StopAsyncIteration) + assert len(requests) == 1 @pytest.mark.asyncio @@ -99,9 +235,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous) ) db = await connection(endpoint, asynchronous) method = getattr(db, "list_" + kind) - kwargs = ( - {} if kind in ("jobs", "materialized_views") else {"namespace_path": ["team"]} - ) + kwargs = {} if kind == "jobs" else {"namespace_path": ["team"]} items = method(page_token="start/token", page_limit=2, **kwargs) assert requests == [] assert items.page_token() == "start/token" @@ -136,7 +270,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous) assert path.path == "/v1/jobs/list" assert body == {"page_token": token, "limit": 2} else: - namespace = "$" if kind == "materialized_views" else "team" + namespace = "team" resource = kind.removesuffix("s") assert path.path == f"/v1/namespace/{namespace}/{resource}/list" expected = {"page_token": [token], "limit": ["2"]} diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index bd1b2a0bb..891b49164 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -1,15 +1,18 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors + import contextlib import http.server import json -import threading import lancedb import pytest +import pyarrow as pa +from lancedb.db import AsyncConnection from lancedb.materialized_view import MaterializedViewDefinition from lancedb.remote.db import RemoteDBConnection +from utils import start_server_thread STABLE_ROW_IDS = {"new_table_enable_stable_row_ids": "true"} @@ -29,34 +32,7 @@ def make_db(tmp_path): @contextlib.contextmanager -def mock_remote_materialized_views(): - requests = [] - - class Handler(http.server.BaseHTTPRequestHandler): - def log_message(self, *args): - pass - - def do_GET(self): - requests.append(self.path) - encoded = json.dumps({"views": ["daily_sales"]}).encode() - self.send_response(200) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(encoded))) - self.end_headers() - self.wfile.write(encoded) - - with http.server.HTTPServer(("localhost", 0), Handler) as server: - thread = threading.Thread(target=server.serve_forever) - thread.start() - try: - yield f"http://localhost:{server.server_address[1]}", requests - finally: - server.shutdown() - thread.join() - - -@contextlib.contextmanager -def mock_remote_materialized_view_create(): +def mock_remote_materialized_view_refresh(): requests = [] class Handler(http.server.BaseHTTPRequestHandler): @@ -64,50 +40,108 @@ def mock_remote_materialized_view_create(): pass def do_POST(self): - length = int(self.headers.get("Content-Length", 0)) - body = json.loads(self.rfile.read(length) or b"{}") - requests.append((self.path, body)) - job_id = "mv-drop-123" if self.path.endswith("/drop") else "mv-create-123" - encoded = json.dumps({"job_id": job_id}).encode() - self.send_response(202) + requests.append(self.path) + assert self.path == "/v1/table/view/describe/" + response = {"version": 42, "schema": {"fields": []}} + encoded = json.dumps(response).encode() + self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(encoded))) self.end_headers() self.wfile.write(encoded) - with http.server.HTTPServer(("localhost", 0), Handler) as server: - thread = threading.Thread(target=server.serve_forever) - thread.start() + with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) try: - yield f"http://localhost:{server.server_address[1]}", requests + yield f"http://127.0.0.1:{server.server_address[1]}", requests finally: server.shutdown() thread.join() -def test_remote_list_uses_namespace_route(): - with mock_remote_materialized_views() as (host, requests): - db = lancedb.connect( +@pytest.mark.asyncio +@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): + flight = pytest.importorskip("pyarrow.flight") + + class RefreshServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.commands = [] + + def do_get(self, context, ticket): + self.commands.append(ticket.ticket) + if b"DESCRIBE MATERIALIZED VIEW" in ticket.ticket: + return flight.RecordBatchStream( + pa.table( + { + "name": ["view"], + "query": ["SELECT * FROM source"], + } + ) + ) + assert b"REFRESH MATERIALIZED VIEW" in ticket.ticket + # SQL completion carries no refresh statistics. + return flight.RecordBatchStream(pa.table({"status": ["ok"]})) + + with ( + mock_remote_materialized_view_refresh() as (host, requests), + RefreshServer() as server, + ): + options = {"full": True} if full else {} + connect = lancedb.connect if sync else lancedb.connect_async + db = connect( "db://dev", api_key="fake", host_override=host, + sql_host_override=f"grpc://127.0.0.1:{server.port}", client_config={"retry_config": {"retries": 0}}, ) - assert list(db.list_materialized_views()) == ["daily_sales"] - assert requests == ["/v1/namespace/$/materialized_view/list"] + if sync: + view = db.open_materialized_view("view") + result = ( + view.refresh_async(**options).wait() + if background + else view.refresh(**options) + ) + else: + db = await db + view = await db.open_materialized_view("view") + if background: + job = await view.refresh_async(**options) + result = await job.wait() + else: + result = await view.refresh(**options) - -def test_remote_drop_async_returns_server_job(): - with mock_remote_materialized_view_create() as (host, requests): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, + assert result.mode is None + assert result.rows_written is None + assert result.source_version is None + assert result.version == 42 + assert repr(result) == ( + "RefreshMaterializedViewResult(mode=None, rows_written=None, " + "source_version=None, version=42)" ) - job = db.drop_materialized_view_async("adults") - assert job.id == "mv-drop-123" - assert requests == [("/v1/materialized_view/adults/drop", {})] + describes = [ + command + for command in server.commands + if b"DESCRIBE MATERIALIZED VIEW" in command + ] + refreshes = [ + command + for command in server.commands + if b"REFRESH MATERIALIZED VIEW" in command + ] + assert len(describes) == 2 + assert len(refreshes) == 1 + assert all( + b'DESCRIBE MATERIALIZED VIEW "view"' in command for command in describes + ) + (refresh,) = refreshes + assert b'REFRESH MATERIALIZED VIEW "view"' in refresh + assert (b"WITH (full = true)" in refresh) is full + assert not any("count_rows" in path for path in requests) def test_sync_remote_create_uses_public_async_connection(): @@ -129,8 +163,21 @@ def test_sync_remote_create_uses_public_async_connection(): where=None, limit=None, with_no_data=False, + auto_refresh_enabled=None, + auto_refresh_interval_seconds=None, ): - calls.append((name, source, select, where, limit, with_no_data)) + calls.append( + ( + name, + source, + select, + where, + limit, + with_no_data, + auto_refresh_enabled, + auto_refresh_interval_seconds, + ) + ) return StubAsyncMaterializedView() async def drop_materialized_view(self, name, *, namespace_path=None): @@ -148,14 +195,17 @@ def test_sync_remote_create_uses_public_async_connection(): where="age >= 18", limit=10, with_no_data=True, + auto_refresh_enabled=True, + auto_refresh_interval_seconds=0.5, ) assert view.name == "adults" - assert calls == [("adults", "people", ["name"], "age >= 18", 10, True)] + assert calls == [("adults", "people", ["name"], "age >= 18", 10, True, True, 0.5)] db.drop_materialized_view("adults", namespace_path=["analytics"]) assert calls[-1] == ("drop", "adults", ["analytics"]) +@pytest.mark.experimental_functions def test_create_refresh_and_query(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view( @@ -171,17 +221,20 @@ def test_create_refresh_and_query(tmp_path): assert sorted(row["shout"] for row in rows) == ["ADA", "GRACE"] +@pytest.mark.experimental_functions def test_create_and_refresh_jobs(tmp_path): db = make_db(tmp_path) create_job = db.create_materialized_view_async( "adults", "people", where="age >= 18", with_no_data=True ) assert create_job.id is None + assert create_job.job_type is None assert create_job.wait() is None view = db.open_materialized_view("adults") refresh_job = view.refresh_async() assert refresh_job.id is None + assert refresh_job.job_type is None result = refresh_job.wait() assert result.mode == "rebuild" assert result.rows_written == 2 @@ -193,6 +246,7 @@ def test_create_and_refresh_jobs(tmp_path): assert "adults" not in list(db.list_materialized_views()) +@pytest.mark.experimental_functions def test_definition_round_trips(tmp_path): db = make_db(tmp_path) db.create_materialized_view("adults", "people", where="age >= 18") @@ -203,20 +257,39 @@ def test_definition_round_trips(tmp_path): ) -def test_full_refresh_after_append(tmp_path): +@pytest.mark.experimental_functions +@pytest.mark.parametrize("full", [False, True]) +def test_full_refresh_after_append(tmp_path, full): db = make_db(tmp_path) view = db.create_materialized_view("copy", "people", with_no_data=True) view.refresh() db.open_table("people").add([{"name": "alan", "age": 41}]) - result = view.refresh() + result = view.refresh(full=full) assert result.mode == "rebuild" assert result.rows_written == 4 + assert result.source_version == db.open_table("people").version assert view.table.count_rows() == 4 assert view.refresh().mode == "rebuild" +@pytest.mark.experimental_functions +def test_full_refresh_can_pin_local_source_version(tmp_path): + db = make_db(tmp_path) + source = db.open_table("people") + version = source.version + view = db.create_materialized_view("copy", "people", with_no_data=True) + source.add([{"name": "alan", "age": 41}]) + + result = view.refresh(full=True, source_version=version) + assert result.mode == "rebuild" + assert result.rows_written == 3 + assert result.source_version == version + assert view.table.count_rows() == 3 + + +@pytest.mark.experimental_functions def test_full_refresh_after_update(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("copy", "people", with_no_data=True) @@ -230,6 +303,7 @@ def test_full_refresh_after_update(tmp_path): assert sorted(row["age"] for row in rows) == [8, 36, 85] +@pytest.mark.experimental_functions def test_legacy_storage_source_update_rebuilds(tmp_path): db = lancedb.connect( tmp_path, @@ -246,6 +320,7 @@ def test_legacy_storage_source_update_rebuilds(tmp_path): assert sorted(row["age"] for row in rows) == [8, 36] +@pytest.mark.experimental_functions def test_direct_writes_to_a_view_are_refused(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("copy", "people") @@ -271,6 +346,7 @@ def test_direct_writes_to_a_view_are_refused(tmp_path): assert view.refresh().rows_written == 4 +@pytest.mark.experimental_functions def test_list_and_not_a_view(tmp_path): db = make_db(tmp_path) db.create_materialized_view("adults", "people", where="age >= 18") @@ -285,6 +361,7 @@ def test_list_and_not_a_view(tmp_path): assert list(db.list_materialized_views()) == [] +@pytest.mark.experimental_functions def test_invalid_expression_fails_at_create(tmp_path): db = make_db(tmp_path) with pytest.raises(Exception, match="missing"): @@ -292,6 +369,7 @@ def test_invalid_expression_fails_at_create(tmp_path): assert "bad" not in db.list_tables().tables +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_create_refresh_and_open(tmp_path): db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) @@ -313,6 +391,7 @@ async def test_async_create_refresh_and_open(tmp_path): assert [item async for item in db.list_materialized_views()] == ["shouts"] +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_create_and_refresh_jobs(tmp_path): db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) @@ -322,11 +401,13 @@ async def test_async_create_and_refresh_jobs(tmp_path): "adults", "people", with_no_data=True ) assert create_job.id is None + assert create_job.job_type is None assert await create_job.wait() is None view = await db.open_materialized_view("adults") refresh_job = await view.refresh_async() assert refresh_job.id is None + assert refresh_job.job_type is None result = await refresh_job.wait() assert result.mode == "rebuild" assert result.rows_written == 1 @@ -337,6 +418,7 @@ async def test_async_create_and_refresh_jobs(tmp_path): assert "adults" not in [item async for item in db.list_materialized_views()] +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_refresh_rebuilds(tmp_path): db = await lancedb.connect_async(tmp_path) @@ -351,6 +433,7 @@ async def test_async_refresh_rebuilds(tmp_path): assert result.rows_written == 2 +@pytest.mark.experimental_functions def test_source_does_not_require_stable_row_ids(tmp_path): db = lancedb.connect(tmp_path) db.create_table("plain", [{"x": 1}]) @@ -358,6 +441,7 @@ def test_source_does_not_require_stable_row_ids(tmp_path): assert view.table.count_rows() == 1 +@pytest.mark.experimental_functions def test_bare_select_names_are_quoted(tmp_path): db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS) db.create_table("odd_names", [{"order item": "widget", "select": 2}]) @@ -375,6 +459,7 @@ def test_bare_select_names_are_quoted(tmp_path): assert rows[0]["select"] == 2 +@pytest.mark.experimental_functions def test_scalar_select_is_one_column(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("just_name", "people", select="name") @@ -384,6 +469,7 @@ def test_scalar_select_is_one_column(tmp_path): assert sorted(row["name"] for row in rows) == ["ada", "grace", "kid"] +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_scalar_select_is_one_column(tmp_path): db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) @@ -394,6 +480,7 @@ async def test_async_scalar_select_is_one_column(tmp_path): assert set(rows[0]) == {"name"} +@pytest.mark.experimental_functions def test_limit_above_i64_max_is_refused(tmp_path): db = make_db(tmp_path) with pytest.raises(ValueError, match="exceeds the maximum"): @@ -413,6 +500,7 @@ def _namespace_db(tmp_path): ) +@pytest.mark.experimental_functions def test_namespace_connection_materialized_views(tmp_path): db = _namespace_db(tmp_path) db.create_table( @@ -443,6 +531,7 @@ def test_namespace_connection_materialized_views(tmp_path): assert list(db.list_materialized_views()) == [] +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_namespace_connection_materialized_views(tmp_path): db = lancedb.connect_namespace_async( @@ -489,8 +578,6 @@ async def test_async_namespace_connection_materialized_views(tmp_path): def test_stored_queries_and_legacy_layouts_are_read(): - import json - import pyarrow as pa from lancedb.materialized_view import _definition_from_schema @@ -536,6 +623,7 @@ def test_stored_queries_and_legacy_layouts_are_read(): read(newer) +@pytest.mark.experimental_functions def test_local_materialized_view_listing_pages_and_resume(tmp_path): db = make_db(tmp_path) db.create_materialized_view("a_view", "people", with_no_data=True) @@ -550,3 +638,124 @@ def test_local_materialized_view_listing_pages_and_resume(tmp_path): assert sorted([first, *resumed]) == ["a_view", "z_view"] assert resumed.page_token() is None assert list(resumed) == [] + + +class QueryBackedCreateJob: + id = "0198f1b2-c3d4-7e5f-8123-456789abcdef" + + job_type = "query" + + async def wait(self): + return None + + async def status(self): + return "finished" + + +class CapturingCreateConnection: + def __init__(self): + self.calls = [] + + async def create_materialized_view_async(self, name, source, **options): + self.calls.append((name, source, options)) + return QueryBackedCreateJob() + + +@pytest.mark.parametrize( + "options", + [ + {}, + {"auto_refresh_enabled": True}, + {"auto_refresh_enabled": False, "auto_refresh_interval_seconds": 0.5}, + ], +) +def test_remote_create_forwards_refresh_options_without_interval_default(options): + native = CapturingCreateConnection() + db = RemoteDBConnection.__new__(RemoteDBConnection) + db._conn = AsyncConnection(native) + job = db.create_materialized_view_async("adults", "people", **options) + assert job.id == QueryBackedCreateJob.id + assert job.job_type == "query" + assert not hasattr(job, "query_id") + assert job.wait() is None + assert job.status() == "finished" + assert native.calls == [ + ( + "adults", + "people", + { + "projections": None, + "filter": None, + "limit": None, + "with_no_data": False, + "auto_refresh_enabled": options.get("auto_refresh_enabled"), + "auto_refresh_interval_seconds": options.get( + "auto_refresh_interval_seconds" + ), + }, + ) + ] + + +@pytest.mark.asyncio +async def test_async_remote_create_keeps_interval_unspecified(): + native = CapturingCreateConnection() + db = AsyncConnection(native) + job = await db.create_materialized_view_async( + "adults", "people", auto_refresh_enabled=True + ) + assert job.id == QueryBackedCreateJob.id + assert job.job_type == "query" + assert not hasattr(job, "query_id") + assert await job.wait() is None + assert await job.status() == "finished" + assert native.calls[0][2]["auto_refresh_enabled"] is True + assert native.calls[0][2]["auto_refresh_interval_seconds"] is None + + +@pytest.mark.experimental_functions +@pytest.mark.parametrize( + "options", + [ + {"auto_refresh_enabled": True}, + {"auto_refresh_interval_seconds": 300}, + ], +) +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"): + db.create_materialized_view("adults", "people", **options) + assert "adults" not in db.table_names() + + +@pytest.mark.parametrize("seconds", [0, -1, float("nan"), float("inf")]) +def test_remote_create_rejects_invalid_interval_without_request(seconds): + db = lancedb.connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1") + with pytest.raises(ValueError, match="positive, finite"): + db.create_materialized_view_async( + "mv", "source", auto_refresh_interval_seconds=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"): + db.create_materialized_view("mv", "source", auto_refresh_enabled=True) + + +@pytest.mark.experimental_functions +@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"): + await db.create_materialized_view("mv", "source", auto_refresh_enabled=True) + + +@pytest.mark.experimental_functions +def test_embedded_explicitly_disabled_refresh_is_supported(tmp_path): + db = make_db(tmp_path) + view = db.create_materialized_view("mv", "people", auto_refresh_enabled=False) + assert view.table.count_rows() == 3 diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 520a6992d..663172e77 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -6,15 +6,17 @@ import tempfile import shutil import importlib +import warnings import http.server import json -import threading from urllib.parse import parse_qs, unquote, urlparse import pytest 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.query import Query from lancedb.table import AsyncTable, LanceTable @@ -25,6 +27,125 @@ PUSHDOWN_DATA = pa.table( ) +class TestNamespaceCreateTableOptions: + @pytest.mark.parametrize("version", ["legacy", "stable"]) + @pytest.mark.parametrize("empty", [False, True]) + def test_deprecated_storage_version(self, tmp_path, version, empty): + db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "namespace")}) + data = None if empty else [{"id": 1}] + schema = pa.schema([("id", pa.int64())]) + other_version = "stable" if version == "legacy" else "legacy" + options = {"new_table_data_storage_version": other_version} + control = lancedb.connect(tmp_path / "control").create_table( + "test", + data=data, + schema=schema, + storage_options={"new_table_data_storage_version": version}, + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + table = db.create_table( + "test", + data=data, + schema=schema, + storage_options=options, + data_storage_version=version, + ) + + assert ( + table.to_lance().data_storage_version + == control.to_lance().data_storage_version + ) + assert table.to_arrow().to_pylist() == ([] if empty else data) + assert options == {"new_table_data_storage_version": other_version} + assert any("data_storage_version" in str(w.message) for w in caught) + + @pytest.mark.asyncio + @pytest.mark.parametrize("version", ["legacy", "stable"]) + @pytest.mark.parametrize("empty", [False, True]) + async def test_deprecated_storage_version_async(self, tmp_path, version, empty): + root = str(tmp_path / "namespace") + db = lancedb.connect_namespace_async("dir", {"root": root}) + data = None if empty else [{"id": 1}] + schema = pa.schema([("id", pa.int64())]) + other_version = "stable" if version == "legacy" else "legacy" + options = {"new_table_data_storage_version": other_version} + control = lancedb.connect(tmp_path / "control").create_table( + "test", + data=data, + schema=schema, + storage_options={"new_table_data_storage_version": version}, + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + table = await db.create_table( + "test", + data=data, + schema=schema, + storage_options=options, + data_storage_version=version, + ) + + reopened = lancedb.connect_namespace("dir", {"root": root}).open_table("test") + assert ( + reopened.to_lance().data_storage_version + == control.to_lance().data_storage_version + ) + assert (await table.to_arrow()).to_pylist() == ([] if empty else data) + assert options == {"new_table_data_storage_version": other_version} + assert any("data_storage_version" in str(w.message) for w in caught) + + @pytest.mark.parametrize("enabled", [False, True]) + @pytest.mark.parametrize("empty", [False, True]) + def test_deprecated_manifest_paths(self, tmp_path, enabled, empty): + db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) + data = None if empty else [{"id": 1}] + options = {"new_table_enable_v2_manifest_paths": str(not enabled).lower()} + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + table = db.create_table( + "test", + data=data, + schema=pa.schema([("id", pa.int64())]), + storage_options=options, + enable_v2_manifest_paths=enabled, + ) + + assert table.uses_v2_manifest_paths() == enabled + assert table.to_arrow().to_pylist() == ([] if empty else data) + assert db.open_table("test").uses_v2_manifest_paths() == enabled + assert options == { + "new_table_enable_v2_manifest_paths": str(not enabled).lower() + } + assert any("enable_v2_manifest_paths" in str(w.message) for w in caught) + + @pytest.mark.asyncio + @pytest.mark.parametrize("enabled", [False, True]) + @pytest.mark.parametrize("empty", [False, True]) + async def test_deprecated_manifest_paths_async(self, tmp_path, enabled, empty): + db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}) + data = None if empty else [{"id": 1}] + options = {"new_table_enable_v2_manifest_paths": str(not enabled).lower()} + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + table = await db.create_table( + "test", + data=data, + schema=pa.schema([("id", pa.int64())]), + storage_options=options, + enable_v2_manifest_paths=enabled, + ) + + assert await table.uses_v2_manifest_paths() == enabled + assert (await table.to_arrow()).to_pylist() == ([] if empty else data) + reopened = await db.open_table("test") + assert await reopened.uses_v2_manifest_paths() == enabled + assert options == { + "new_table_enable_v2_manifest_paths": str(not enabled).lower() + } + assert any("enable_v2_manifest_paths" in str(w.message) for w in caught) + + def _ipc_file(table: pa.Table = PUSHDOWN_DATA) -> bytes: sink = pa.BufferOutputStream() with pa.ipc.new_file(sink, table.schema) as writer: @@ -146,8 +267,7 @@ def paginated_rest_namespace(): pass with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server: - thread = threading.Thread(target=server.serve_forever) - thread.start() + thread = start_server_thread(server) try: yield {"uri": f"http://127.0.0.1:{server.server_port}"}, requests finally: @@ -239,7 +359,17 @@ class TestNamespaceConnection: def test_list_materialized_views(self): db = lancedb.connect_namespace("dir", {"root": self.temp_dir}) db.create_table("source", [{"id": 1}]) - db.create_materialized_view("view", "source", with_no_data=True) + # Model a stored view from an enabled build: listing must also work + # when local creation is disabled in the current build. + schema = pa.schema( + [("id", pa.int64())], + metadata={ + DEFINITION_META_KEY: json.dumps( + {"format": DEFINITION_FORMAT, "query": "SELECT id FROM source"} + ).encode() + }, + ) + db.create_table("view", schema=schema) names = db.list_materialized_views(page_limit=1) assert isinstance(names, Listing) @@ -752,7 +882,16 @@ class TestAsyncNamespaceConnection: async def test_list_materialized_views(self): db = lancedb.connect_namespace_async("dir", {"root": self.temp_dir}) await db.create_table("source", [{"id": 1}]) - await db.create_materialized_view("view", "source", with_no_data=True) + # Model a stored view independently of the local creation feature. + schema = pa.schema( + [("id", pa.int64())], + metadata={ + DEFINITION_META_KEY: json.dumps( + {"format": DEFINITION_FORMAT, "query": "SELECT id FROM source"} + ).encode() + }, + ) + await db.create_table("view", schema=schema) names = db.list_materialized_views(page_limit=1) assert isinstance(names, AsyncListing) @@ -1065,7 +1204,7 @@ class TestPushdownOperations: Rust so reads carry the x-lancedb-min-timestamp read-freshness header.""" db = lancedb.connect_namespace( "rest", - {"uri": "http://localhost:12345"}, + {"uri": "http://127.0.0.1:12345"}, namespace_client_pushdown_operations=["QueryTable"], ) assert db._route_pushdown_to_rust is True @@ -1082,7 +1221,7 @@ class TestPushdownOperations: for the async path omitting the freshness header).""" db = lancedb.connect_namespace_async( "rest", - {"uri": "http://localhost:12345"}, + {"uri": "http://127.0.0.1:12345"}, namespace_client_pushdown_operations=["QueryTable"], ) assert db._route_pushdown_to_rust is True diff --git a/python/python/tests/test_nvidia_embeddings.py b/python/python/tests/test_nvidia_embeddings.py new file mode 100644 index 000000000..3ae07c330 --- /dev/null +++ b/python/python/tests/test_nvidia_embeddings.py @@ -0,0 +1,522 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +import os +from typing import Optional + +import lancedb +import numpy as np +import pyarrow as pa +import pytest + +from lancedb.embeddings import ( + EmbeddingFunctionConfig, + NvidiaEmbeddings, + UntrustedEmbeddingConfigError, + get_registry, +) +from lancedb.embeddings.nvidia import MODEL_DIMENSIONS, NVIDIA_BASE_URL +from lancedb.pydantic import LanceModel, Vector + + +@pytest.fixture +def nvidia_api(monkeypatch): + """Exercise the real OpenAI client against a deterministic NVIDIA endpoint.""" + httpx = pytest.importorskip("httpx") + openai = pytest.importorskip("openai") + requests, responses, clients = [], [], [] + original_client = openai.OpenAI + monkeypatch.setenv("NVIDIA_API_KEY", "test-nvidia-key") + registry = get_registry() + monkeypatch.setattr(registry, "_variables", {}) + monkeypatch.setattr(registry, "_allowed_endpoints", set()) + + def respond(request): + requests.append(request) + if responses: + return responses.pop(0) + body = json.loads(request.content) + data = [] + for index, text in enumerate(body["input"]): + vector = [0.0] * body["dimensions"] + vector[0 if text == "alpha" else 1] = 1.0 + data.append({"index": index, "embedding": vector, "object": "embedding"}) + return httpx.Response( + 200, + json={ + "object": "list", + "model": body["model"], + # The API's index, not response order, determines the input row. + "data": data[::-1], + "usage": {"prompt_tokens": len(data), "total_tokens": len(data)}, + }, + ) + + def client(**kwargs): + assert kwargs["max_retries"] == 0 + instance = original_client( + **kwargs, + http_client=httpx.Client( + transport=httpx.MockTransport(respond), trust_env=False + ), + ) + clients.append(instance) + return instance + + monkeypatch.setattr(openai, "OpenAI", client) + yield requests, responses + for client in clients: + client.close() + + +@pytest.mark.parametrize( + "name,dimensions", [(name, dims[0]) for name, dims in MODEL_DIMENSIONS.items()] +) +def test_hosted_models(nvidia_api, name, dimensions): + requests, _ = nvidia_api + func = get_registry().get("nvidia").create(name=name) + assert isinstance(func, NvidiaEmbeddings) + assert func.ndims() == dimensions + assert len(func.compute_source_embeddings(["alpha"])[0]) == dimensions + assert len(func.compute_query_embeddings("alpha")[0]) == dimensions + for request, input_type in zip(requests, ["passage", "query"]): + assert str(request.url) == f"{NVIDIA_BASE_URL}/embeddings" + assert request.headers["authorization"] == "Bearer test-nvidia-key" + assert json.loads(request.content) == { + "model": name, + "input": ["alpha"], + "dimensions": dimensions, + "encoding_format": "float", + "input_type": input_type, + "modality": "text", + "truncate": "END", + } + + +@pytest.mark.parametrize( + "texts", + [ + ["alpha", "beta", "gamma"], + np.array(["alpha", "beta", "gamma"]), + pa.array(["alpha", "beta", "gamma"]), + pa.chunked_array([["alpha"], ["beta", "gamma"]]), + ], +) +def test_batching_and_response_order(nvidia_api, texts): + requests, _ = nvidia_api + func = NvidiaEmbeddings.create(dim=128, batch_size=2, truncate="NONE") + result = func.compute_source_embeddings(texts) + assert [vector[:2] for vector in result] == [[1, 0], [0, 1], [0, 1]] + assert [json.loads(request.content)["input"] for request in requests] == [ + ["alpha", "beta"], + ["gamma"], + ] + assert all(json.loads(r.content)["truncate"] == "NONE" for r in requests) + assert func.compute_source_embeddings([]) == [] + assert len(requests) == 2 + + +@pytest.mark.parametrize( + "texts", + [ + ["alpha", None, "", "beta"], + pa.array(["alpha", None, "", "beta"]), + ], +) +def test_null_and_empty_inputs(nvidia_api, texts): + requests, _ = nvidia_api + func = NvidiaEmbeddings.create(dim=128) + result = func.compute_source_embeddings(texts) + assert [vector and vector[:2] for vector in result] == [[1, 0], None, None, [0, 1]] + assert [json.loads(r.content)["input"] for r in requests] == [["alpha", "beta"]] + assert func.compute_source_embeddings([None, ""]) == [None, None] + assert len(requests) == 1 + + +def test_table_with_null_text(nvidia_api, tmp_path): + func = NvidiaEmbeddings.create(dim=128) + + class Document(LanceModel): + text: Optional[str] = func.SourceField() + vector: Optional[Vector(func.ndims())] = func.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table("docs", schema=Document) + table.add([{"text": "alpha"}, {"text": None}], on_bad_vectors="null") + rows = table.to_arrow().to_pylist() + assert rows[0]["vector"][:2] == [1, 0] + assert rows[1]["vector"] is None + + +@pytest.mark.parametrize("texts", [[b"image"], [["nested"]], [123]]) +def test_rejects_non_text(nvidia_api, monkeypatch, texts): + requests, _ = nvidia_api + monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", pytest.fail) + func = NvidiaEmbeddings.create() + with pytest.raises(ValueError, match="text strings only"): + func.compute_source_embeddings(texts) + with pytest.raises(ValueError, match="text strings only"): + func.compute_source_embeddings_with_retry(texts) + assert requests == [] + + +@pytest.mark.parametrize( + "options", + [ + {"batch_size": 0}, + {"dim": 0}, + {"dim": 127}, + {"dim": 2049}, + {"name": "nvidia/nemotron-3.5-embed-8b", "dim": 4097}, + {"name": "nvidia/Nemotron-3.5-Embed-8B-BF16"}, + {"truncate": "START"}, + ], +) +def test_invalid_configuration(options): + with pytest.raises(ValueError): + NvidiaEmbeddings.create(**options) + + +@pytest.mark.parametrize( + "data,error", + [ + ([], "number of embeddings"), + (None, "number of embeddings"), + ([{"index": 1, "embedding": [0.0] * 128}], "indices"), + ([{"embedding": [0.0] * 128}], "indices"), + ([{"index": 0, "embedding": [0.0]}], "finite numeric"), + ([{"index": 0, "embedding": "base64"}], "finite numeric"), + ([{"index": 0, "embedding": ["bad"] * 128}], "finite numeric"), + ([{"index": 0}], "finite numeric"), + ], +) +def test_invalid_response(nvidia_api, data, error): + import httpx + + _, responses = nvidia_api + responses.append(httpx.Response(200, json={"data": data})) + with pytest.raises(ValueError, match=error): + NvidiaEmbeddings.create(dim=128).compute_source_embeddings(["alpha"]) + + +def test_invalid_response_is_not_retried(nvidia_api, monkeypatch): + import httpx + + requests, responses = nvidia_api + monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", pytest.fail) + responses.append(httpx.Response(200, json={"data": []})) + func = NvidiaEmbeddings.create(dim=128) + with pytest.raises(ValueError, match="number of embeddings"): + func.compute_source_embeddings_with_retry(["alpha"]) + assert len(requests) == 1 + + +def test_missing_response_data(nvidia_api): + import httpx + + _, responses = nvidia_api + responses.append(httpx.Response(200, json={})) + with pytest.raises(ValueError, match="number of embeddings"): + NvidiaEmbeddings.create().compute_query_embeddings("alpha") + + +@pytest.mark.parametrize("bad_value", ["NaN", "Infinity", "-Infinity"]) +def test_nonfinite_response(nvidia_api, bad_value): + import httpx + + _, responses = nvidia_api + # Raw JSON is needed because httpx refuses to encode non-finite numbers. + vector = ",".join([bad_value] + ["0"] * 127) + responses.append( + httpx.Response(200, text='{"data":[{"index":0,"embedding":[' + vector + "]}]}") + ) + with pytest.raises(ValueError, match="finite numeric"): + NvidiaEmbeddings.create(dim=128).compute_source_embeddings(["alpha"]) + + +def test_duplicate_indices(nvidia_api): + import httpx + + _, responses = nvidia_api + responses.append( + httpx.Response(200, json={"data": [{"index": 0, "embedding": [0.0] * 128}] * 2}) + ) + with pytest.raises(ValueError, match="indices"): + NvidiaEmbeddings.create(dim=128).compute_source_embeddings(["alpha", "beta"]) + + +@pytest.mark.parametrize( + "status,expected_calls", [(429, 2), (503, 2), (401, 1), (400, 1)] +) +def test_retry_policy(nvidia_api, monkeypatch, status, expected_calls): + import httpx + import openai + + requests, responses = nvidia_api + monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", lambda _: None) + responses.append(httpx.Response(status, json={"error": {"message": "test error"}})) + func = NvidiaEmbeddings.create(dim=128, max_retries=1) + if expected_calls == 2: + assert len(func.compute_query_embeddings_with_retry("alpha")[0]) == 128 + else: + with pytest.raises(openai.APIStatusError) as error: + func.compute_query_embeddings_with_retry("alpha") + assert error.value.status_code == status + assert len(requests) == expected_calls + + +def test_retry_resends_only_failed_batch(nvidia_api, monkeypatch): + import httpx + + requests, responses = nvidia_api + monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", lambda _: None) + vector = [1.0] + [0.0] * 127 + responses.append( + httpx.Response(200, json={"data": [{"index": 0, "embedding": vector}]}) + ) + responses.append(httpx.Response(429, json={"error": {"message": "slow down"}})) + func = NvidiaEmbeddings.create(dim=128, batch_size=1, max_retries=1) + result = func.compute_source_embeddings_with_retry(["alpha", "beta"]) + assert [v[:2] for v in result] == [[1, 0], [0, 1]] + assert [json.loads(r.content)["input"] for r in requests] == [ + ["alpha"], + ["beta"], + ["beta"], + ] + + +def test_credentials_and_metadata(nvidia_api, monkeypatch): + requests, _ = nvidia_api + registry = get_registry() + registry.set_var("nvidia-key", "secret-from-registry") + options = { + "name": "nvidia/Nemotron-3.5-Embed-8B-BF16", + "base_url": "http://localhost:8000/v1", + "dim": 2048, + "api_key": "$var:nvidia-key", + "batch_size": 2, + "truncate": "NONE", + } + func = NvidiaEmbeddings.create(**options) + config = EmbeddingFunctionConfig( + source_column="text", vector_column="vector", function=func + ) + schema = pa.schema([], metadata=registry.get_table_metadata([config])) + # Round-trip the configuration through Arrow, as table schemas do. + restored_schema = pa.ipc.read_schema(pa.BufferReader(schema.serialize())) + metadata = restored_schema.metadata + assert b"secret-from-registry" not in metadata[b"embedding_functions"] + restored = registry.parse_functions(metadata)["vector"].function + assert restored.safe_model_dump() == options + restored.compute_source_embeddings(["alpha"]) + restored.compute_query_embeddings("alpha") + assert str(requests[0].url) == "http://localhost:8000/v1/embeddings" + assert requests[0].headers["authorization"] == "Bearer secret-from-registry" + assert json.loads(requests[0].content)["model"] == options["name"] + assert [json.loads(r.content)["input_type"] for r in requests] == [ + "passage", + "query", + ] + + monkeypatch.setattr(registry, "_allowed_endpoints", set()) + blocked = registry.parse_functions(metadata)["vector"].function + with pytest.raises(UntrustedEmbeddingConfigError): + blocked.compute_query_embeddings("alpha") + registry.allow_endpoint(options["base_url"]) + assert isinstance( + registry.parse_functions(metadata)["vector"].function, NvidiaEmbeddings + ) + with pytest.raises(ValueError, match="Sensitive key"): + NvidiaEmbeddings.create(api_key="hardcoded-secret") + + +def test_missing_key_and_unauthenticated_nim(nvidia_api, monkeypatch): + from lancedb.embeddings.utils import MissingApiKeyError + + requests, _ = nvidia_api + # The hosted key in NVIDIA_API_KEY is not sent to custom endpoints. + func = NvidiaEmbeddings.create( + name="nvidia/Nemotron-3.5-Embed-1B-BF16", + base_url="http://localhost:8000/v1", + dim=128, + ) + func.compute_query_embeddings("alpha") + assert requests[0].headers["authorization"] == "Bearer not-required" + monkeypatch.delenv("NVIDIA_API_KEY") + with pytest.raises(MissingApiKeyError, match="NVIDIA_API_KEY"): + NvidiaEmbeddings.create().compute_query_embeddings_with_retry("alpha") + assert len(requests) == 1 + + +@pytest.mark.parametrize("name", MODEL_DIMENSIONS) +def test_local_table_document_query_and_reopen(nvidia_api, tmp_path, name): + requests, _ = nvidia_api + func = NvidiaEmbeddings.create(name=name, dim=128) + + class Document(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table("docs", schema=Document, data=[{"text": "alpha"}]) + table.add([{"text": "beta"}]) + reopened = lancedb.connect(tmp_path).open_table("docs") + assert reopened.schema.metadata == table.schema.metadata + assert isinstance(reopened.embedding_functions["vector"].function, NvidiaEmbeddings) + assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha" + assert [json.loads(request.content)["input_type"] for request in requests] == [ + "passage", + "passage", + "query", + ] + + +@pytest.mark.parametrize("name", MODEL_DIMENSIONS) +def test_remote_table_document_query_and_reopen(nvidia_api, name): + from test_remote_db import mock_lancedb_connection, read_json_body, send_json + + requests, _ = nvidia_api + func = NvidiaEmbeddings.create(name=name, dim=128) + config = EmbeddingFunctionConfig( + source_column="text", vector_column="vector", function=func + ) + writes, queries = [], [] + + def handler(request): + if "/create/" in request.path or "/insert/" in request.path: + if request.headers.get("Transfer-Encoding") == "chunked": + body = bytearray() + while True: + size = int(request.rfile.readline(), 16) + if size == 0: + request.rfile.readline() + break + body.extend(request.rfile.read(size)) + request.rfile.read(2) + else: + body = request.rfile.read(int(request.headers["Content-Length"])) + writes.append(pa.ipc.open_stream(body).read_all()) + send_json(request, {}) + elif "/describe/" in request.path: + send_json( + request, + { + "version": 1, + "schema": { + "fields": [ + { + "name": "text", + "type": {"type": "string"}, + "nullable": True, + }, + { + "name": "vector", + "nullable": True, + "type": { + "type": "fixed_size_list", + "length": 128, + "fields": [ + { + "name": "item", + "type": {"type": "float"}, + "nullable": True, + } + ], + }, + }, + ], + "metadata": { + k.decode(): v.decode() + for k, v in writes[0].schema.metadata.items() + }, + }, + }, + ) + elif "/query/" in request.path: + queries.append(read_json_body(request)) + result = pa.table({"text": ["alpha"], "_distance": [0.0]}) + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.file") + request.end_headers() + with pa.ipc.new_file(request.wfile, result.schema) as writer: + writer.write_table(result) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + table = db.create_table( + "docs", data=[{"text": "alpha"}], embedding_functions=[config] + ) + table.add([{"text": "beta"}]) + reopened = db.open_table("docs") + assert reopened.schema.metadata == writes[0].schema.metadata + assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha" + assert len(writes) == 2 + assert writes[0]["vector"].to_pylist()[0] == [1.0] + [0.0] * 127 + assert writes[1]["vector"].to_pylist()[0] == [0.0, 1.0] + [0.0] * 126 + assert queries[0]["vector"] == [1.0] + [0.0] * 127 + assert [json.loads(r.content)["input_type"] for r in requests] == [ + "passage", + "passage", + "query", + ] + + +@pytest.mark.asyncio +async def test_async_local_table(nvidia_api, tmp_path): + requests, _ = nvidia_api + func = NvidiaEmbeddings.create(dim=128) + + class Document(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + with await lancedb.connect_async(tmp_path) as db: + table = await db.create_table("docs", schema=Document) + await table.add([{"text": "alpha"}, {"text": "beta"}]) + reopened = await db.open_table("docs") + results = await (await reopened.search("alpha")).limit(1).to_list() + assert results[0]["text"] == "alpha" + assert [json.loads(r.content)["input_type"] for r in requests] == [ + "passage", + "query", + ] + + +@pytest.mark.slow +@pytest.mark.skipif( + not os.environ.get("NVIDIA_API_KEY"), reason="NVIDIA_API_KEY not set" +) +@pytest.mark.parametrize("name", MODEL_DIMENSIONS) +def test_nvidia_live(name, tmp_path): + """Five small requests per model, with retries disabled for free-tier tests.""" + pytest.importorskip("openai") + func = NvidiaEmbeddings.create(name=name, max_retries=0) + passages = ["Paris is the capital of France.", "Bananas are yellow fruit."] + question = "What is the capital of France?" + + class Document(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table( + "docs", schema=Document, data=[{"text": text} for text in passages] + ) + table.add([{"text": "Saturn is a planet with rings."}]) + reopened = lancedb.connect(tmp_path).open_table("docs") + assert reopened.schema.metadata == table.schema.metadata + assert reopened.schema.field("vector").type.list_size == func.ndims() + result = reopened.search(question).limit(1).to_list()[0] + assert result["text"] == passages[0] + assert len(result["vector"]) == func.ndims() + assert np.isfinite(result["vector"]).all() + + reduced = NvidiaEmbeddings.create(name=name, dim=128, max_retries=0) + vectors = reduced.compute_source_embeddings_with_retry(passages) + query = reduced.compute_query_embeddings_with_retry(question)[0] + assert np.shape(vectors) == (2, 128) + assert np.shape(query) == (128,) + assert np.dot(query, vectors[0]) > np.dot(query, vectors[1]) diff --git a/python/python/tests/test_ollama_embeddings.py b/python/python/tests/test_ollama_embeddings.py new file mode 100644 index 000000000..de36dc24b --- /dev/null +++ b/python/python/tests/test_ollama_embeddings.py @@ -0,0 +1,126 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json + +import numpy as np +import pyarrow as pa +import pytest +from pydantic import ValidationError + +from lancedb.embeddings import get_registry + + +@pytest.fixture +def ollama_embeddings(): + httpx = pytest.importorskip("httpx") + pytest.importorskip("ollama") + requests = [] + + def respond(request): + body = json.loads(request.content) + requests.append(body) + if body["model"] == "missing-model": + return httpx.Response(404, json={"error": "model not found"}) + return httpx.Response( + 200, + json={ + "embeddings": [ + [float(index), float(len(text))] + for index, text in enumerate(body["input"]) + ] + }, + ) + + function = ( + get_registry() + .get("ollama") + .create( + name="nomic-embed-text", + options={"num_ctx": 4096}, + keep_alive="10m", + ollama_client_kwargs={ + "transport": httpx.MockTransport(respond), + "trust_env": False, + }, + ) + ) + yield function, requests + function._ollama_client._client.close() + + +@pytest.mark.parametrize( + "texts", + [ + pytest.param(["hello", "世界"], id="list"), + pytest.param(np.array(["hello", "世界"]), id="numpy-unicode"), + pytest.param(np.array(["hello", "世界"], dtype=object), id="numpy-object"), + pytest.param( + np.array([b"hello", "世界".encode("utf-8")]), id="numpy-utf8-bytes" + ), + pytest.param([b"hello", "世界".encode("utf-8")], id="list-utf8-bytes"), + pytest.param(np.array(["hello", "unused", "世界"])[::2], id="numpy-slice"), + pytest.param(pa.array(["hello", "世界"]), id="arrow"), + pytest.param(pa.chunked_array([["hello"], ["世界"]]), id="chunked-arrow"), + ], +) +def test_ollama_source_embeddings_inputs(ollama_embeddings, texts): + function, requests = ollama_embeddings + + assert function.compute_source_embeddings(texts) == [[0.0, 5.0], [1.0, 2.0]] + assert requests == [ + { + "model": "nomic-embed-text", + "input": ["hello", "世界"], + "options": {"num_ctx": 4096}, + "keep_alive": "10m", + } + ] + + +@pytest.mark.parametrize( + "texts", + [ + pytest.param(np.array([["hello"], ["world"]]), id="numpy-two-dimensional"), + pytest.param([["hello"], ["world"]], id="list-two-dimensional"), + pytest.param(np.array([b"\xff"]), id="numpy-invalid-utf8"), + pytest.param([b"\xff"], id="list-invalid-utf8"), + ], +) +def test_ollama_source_embeddings_rejects_invalid_input_locally( + ollama_embeddings, texts +): + function, requests = ollama_embeddings + + with pytest.raises(ValidationError, match="valid string"): + function.compute_source_embeddings(texts) + + assert requests == [] + + +def test_ollama_generate_embeddings_empty_array(ollama_embeddings): + function, requests = ollama_embeddings + + assert function.generate_embeddings(np.array([], dtype=str)) == [] + assert len(requests) == 1 + assert requests[0]["input"] == [] + + +def test_ollama_query_embeddings(ollama_embeddings): + function, requests = ollama_embeddings + + assert function.compute_query_embeddings("hello") == [[0.0, 5.0]] + assert len(requests) == 1 + assert requests[0]["input"] == ["hello"] + + +def test_ollama_source_embeddings_preserves_api_error(ollama_embeddings): + ollama = pytest.importorskip("ollama") + function, requests = ollama_embeddings + function.name = "missing-model" + + with pytest.raises(ollama.ResponseError, match="model not found") as error: + function.compute_source_embeddings(np.array(["hello"])) + + assert error.value.status_code == 404 + assert len(requests) == 1 diff --git a/python/python/tests/test_openai_reranker.py b/python/python/tests/test_openai_reranker.py new file mode 100644 index 000000000..43475103f --- /dev/null +++ b/python/python/tests/test_openai_reranker.py @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from types import SimpleNamespace + +import pyarrow as pa +import pytest + +from lancedb.rerankers import OpenaiReranker + + +def reranker_replying(documents): + """Return an OpenaiReranker whose chat client replies with these documents.""" + reply = json.dumps({"documents": documents}) + + def create(**kwargs): + message = SimpleNamespace(content=reply) + return SimpleNamespace(choices=[SimpleNamespace(message=message)]) + + reranker = OpenaiReranker(api_key="test-key") + reranker.__dict__["_client"] = SimpleNamespace( + chat=SimpleNamespace(completions=SimpleNamespace(create=create)) + ) + return reranker + + +def vector_results(): + return pa.table( + { + "id": [1, 2, 3], + "text": ["dogs bark", "cats purr", "birds sing"], + "_distance": [0.1, 0.2, 0.3], + } + ) + + +def test_scores_stay_with_their_rows_when_the_model_reorders(): + reranker = reranker_replying( + [ + {"content": "cats purr", "relevance_score": 0.9}, + {"content": "birds sing", "relevance_score": 0.5}, + {"content": "dogs bark", "relevance_score": 0.1}, + ] + ) + + result = reranker.rerank_vector("which animal purrs?", vector_results()) + + assert result.select(["id", "text"]).to_pylist() == [ + {"id": 2, "text": "cats purr"}, + {"id": 3, "text": "birds sing"}, + {"id": 1, "text": "dogs bark"}, + ] + assert result["_relevance_score"].to_pylist() == pytest.approx([0.9, 0.5, 0.1]) + + +def test_a_row_the_model_leaves_out_raises(): + reranker = reranker_replying( + [ + {"content": "cats purr", "relevance_score": 0.9}, + {"content": "dogs bark", "relevance_score": 0.1}, + ] + ) + + with pytest.raises(ValueError, match="1 of 3"): + reranker.rerank_vector("which animal purrs?", vector_results()) diff --git a/python/python/tests/test_openai_reranker_credentials.py b/python/python/tests/test_openai_reranker_credentials.py new file mode 100644 index 000000000..aa11239b2 --- /dev/null +++ b/python/python/tests/test_openai_reranker_credentials.py @@ -0,0 +1,38 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +from lancedb.rerankers import OpenaiReranker + + +@pytest.mark.parametrize( + "explicit_key, environment_key, expected_key", + [ + ("explicit-test-key", "environment-test-key", "explicit-test-key"), + ("explicit-test-key", None, "explicit-test-key"), + (None, "environment-test-key", "environment-test-key"), + ], +) +def test_openai_reranker_api_key_precedence( + monkeypatch, explicit_key, environment_key, expected_key +): + pytest.importorskip("openai") + if environment_key is None: + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + else: + monkeypatch.setenv("OPENAI_API_KEY", environment_key) + + reranker = OpenaiReranker(api_key=explicit_key) + client = reranker._client + try: + assert client.api_key == expected_key + finally: + client.close() + + +def test_openai_reranker_requires_api_key(monkeypatch): + pytest.importorskip("openai") + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with pytest.raises(ValueError, match="OPENAI_API_KEY not set"): + OpenaiReranker()._client diff --git a/python/python/tests/test_package_metadata.py b/python/python/tests/test_package_metadata.py index 27def814f..58f4e7267 100644 --- a/python/python/tests/test_package_metadata.py +++ b/python/python/tests/test_package_metadata.py @@ -32,8 +32,10 @@ def test_pyo3_abi_matches_minimum_supported_python(): expected_abi = f"abi3-py{major}{minor}" configured_abis = re.findall(r'"(abi3-py\d+)"', cargo_manifest) - assert configured_abis == [expected_abi, expected_abi], ( - "the pyo3 runtime and build ABI features must both match requires-python" + # PyO3 0.29 configures the ABI through the runtime dependency; its + # build-config crate no longer exposes ABI features. + assert configured_abis == [expected_abi], ( + "the pyo3 runtime ABI feature must match requires-python" ) diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 5e8bb1d76..bc5c1649c 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -161,6 +161,76 @@ def test_split_random_with_seed(mem_db): assert data1["split_id"] == data2["split_id"] +def test_bootstrap_sample_fixed(mem_db): + """Output row count is num_samples, not the input row count, and splits divide + it evenly.""" + tbl = mem_db.create_table("test_table", pa.table({"x": range(20)})) + permutation_tbl = ( + permutation_builder(tbl).bootstrap_sample(1000, fixed=4, seed=42).execute() + ) + + assert permutation_tbl.count_rows() == 1000 + + data = permutation_tbl.search(None).to_arrow().to_pydict() + split_ids = data["split_id"] + assert set(split_ids) == {0, 1, 2, 3} + for split_id in range(4): + assert split_ids.count(split_id) == 250 + + # Every sampled row_id must still be one of the 20 real rows. + assert set(data["row_id"]).issubset(set(range(20))) + + +def test_bootstrap_sample_draws_with_replacement(mem_db): + """Sampling more rows than exist must produce repeats.""" + tbl = mem_db.create_table("test_table", pa.table({"x": range(5)})) + permutation_tbl = ( + permutation_builder(tbl).bootstrap_sample(500, fixed=1, seed=1).execute() + ) + + data = permutation_tbl.search(None).to_arrow().to_pydict() + assert len(data["row_id"]) == 500 + # Only 5 distinct rows exist, so with 500 draws every one of them must repeat. + for row_id in range(5): + assert data["row_id"].count(row_id) > 1 + + +def test_bootstrap_sample_with_seed_is_reproducible(mem_db): + tbl = mem_db.create_table("test_table", pa.table({"x": range(50)})) + + perm1 = permutation_builder(tbl).bootstrap_sample(200, fixed=2, seed=42).execute() + perm2 = permutation_builder(tbl).bootstrap_sample(200, fixed=2, seed=42).execute() + + data1 = perm1.search(None).to_arrow().to_pydict() + data2 = perm2.search(None).to_arrow().to_pydict() + assert data1["row_id"] == data2["row_id"] + assert data1["split_id"] == data2["split_id"] + + +def test_bootstrap_sample_respects_filter(mem_db): + tbl = mem_db.create_table("test_table", pa.table({"x": range(20)})) + permutation_tbl = ( + permutation_builder(tbl) + .filter("x >= 15") + .bootstrap_sample(100, fixed=1, seed=7) + .execute() + ) + + data = permutation_tbl.search(None).to_arrow().to_pydict() + assert len(data["row_id"]) == 100 + assert set(data["row_id"]).issubset(set(range(15, 20))) + + +def test_bootstrap_sample_requires_exactly_one_size_arg(mem_db): + tbl = mem_db.create_table("test_table", pa.table({"x": range(10)})) + with pytest.raises(ValueError): + permutation_builder(tbl).bootstrap_sample(10).execute() + with pytest.raises(ValueError): + permutation_builder(tbl).bootstrap_sample( + 10, ratios=[0.5, 0.5], fixed=2 + ).execute() + + def test_split_hash(mem_db): """Test hash-based splitting.""" tbl = mem_db.create_table( @@ -741,6 +811,13 @@ def test_rename_column(some_permutation: Permutation): some_permutation.rename_column("non_existent", "new_value") +def test_rename_column_keeps_position(some_permutation: Permutation): + renamed = some_permutation.rename_column("id", "new_id") + assert renamed.schema == pa.schema([("new_id", pa.int64()), ("value", pa.int64())]) + batch = renamed.with_format("arrow").__getitems__([0]) + assert batch.schema.names == ["new_id", "value"] + + def test_rename_columns(some_permutation: Permutation): assert some_permutation.rename_columns({"value": "new_value"}).schema == pa.schema( [("id", pa.int64()), ("new_value", pa.int64())] @@ -1327,3 +1404,10 @@ def test_permutation_over_remote_table(): ] assert_server_safe_row_id_requests(server) + + +def test_from_tables_split_without_permutation_table(mem_db): + tbl = mem_db.create_table("test_table", pa.table({"id": range(10)})) + + with pytest.raises(ValueError, match="permutation on split `train` because no"): + Permutation.from_tables(tbl, split="train") diff --git a/python/python/tests/test_pyarrow.py b/python/python/tests/test_pyarrow.py index 7d99d19c6..272eee2ea 100644 --- a/python/python/tests/test_pyarrow.py +++ b/python/python/tests/test_pyarrow.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import pyarrow as pa +import pyarrow.compute as pc import lancedb from lancedb.integrations.pyarrow import PyarrowDatasetAdapter @@ -48,3 +49,19 @@ def test_dataset_adapter(tmp_path): assert adapter.head(10).num_rows == 0 assert adapter.scanner().projected_schema == pa.schema({"x": pa.int64()}) + + +def test_dataset_adapter_expression_filter(tmp_path): + data = pa.table({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) + conn = lancedb.connect(tmp_path) + tbl = conn.create_table("test", data) + + adapter = PyarrowDatasetAdapter(tbl) + filt = pc.field("x") > 2 + + assert adapter.count_rows(filt) == 2 + assert adapter.to_table(filter=filt) == data.slice(2, 2) + assert adapter.head(1, filter=filt) == data.slice(2, 1) + # The filter can reference a column that is not projected + assert adapter.to_table(columns=["y"], filter=filt) == pa.table({"y": [7, 8]}) + assert adapter.scanner(filter=filt).count_rows() == 2 diff --git a/python/python/tests/test_pydantic.py b/python/python/tests/test_pydantic.py index 81674d735..09af2f081 100644 --- a/python/python/tests/test_pydantic.py +++ b/python/python/tests/test_pydantic.py @@ -200,6 +200,27 @@ def test_bare_generic_raises_type_error(): pydantic_to_schema(TestModel) +def test_tuple_with_mixed_element_types_raises_type_error(): + # An Arrow list has one element type, so Tuple[int, str] has no Arrow + # equivalent. It used to map to list and fail later, on write. + class TestModel(pydantic.BaseModel): + pair: Tuple[int, str] + + with pytest.raises(TypeError, match="same type"): + pydantic_to_schema(TestModel) + + +def test_homogeneous_tuples_map_to_lists(): + class TestModel(pydantic.BaseModel): + pair: Tuple[int, int] + many: Tuple[float, ...] + + schema = pydantic_to_schema(TestModel) + + assert schema.field("pair").type == pa.list_(pa.int64()) + assert schema.field("many").type == pa.list_(pa.float64()) + + def test_nested_struct_list_optional(): class SplitInfo(pydantic.BaseModel): start_frame: int @@ -415,6 +436,67 @@ def test_nullable_vector(): assert schema == pa.schema([pa.field("vec", pa.list_(pa.float32(), 16), True)]) +@pytest.mark.parametrize("vector_type", [Vector, MultiVector]) +@pytest.mark.parametrize( + "value_type, values", + [ + (pa.int64(), [-(2**53 + 1), 2**53 + 3]), + (pa.uint64(), [2**53 + 1, 2**64 - 1]), + (pa.int8(), [-128, 127]), + (pa.uint8(), [0, 255]), + (pa.float32(), [1.25, 2.5]), + (pa.float64(), [1.25, 2.5]), + ], +) +def test_typed_vector_round_trip(tmp_path, vector_type, value_type, values): + import lancedb + + annotation = vector_type(2, value_type=value_type) + expected = [values, values] if vector_type is MultiVector else values + + class Row(LanceModel): + id: int + payload: annotation + + row = Row(id=1, payload=expected) + table = lancedb.connect(tmp_path).create_table("typed_vectors", [row], schema=Row) + table.add([Row(id=2, payload=expected)]) + assert table.schema == Row.to_arrow_schema() + assert table.search().to_arrow().to_pylist() == [ + {"id": 1, "payload": expected}, + {"id": 2, "payload": expected}, + ] + assert json.loads(row.model_dump_json())["payload"] == expected + + +@pytest.mark.parametrize("vector_type", [Vector, MultiVector]) +@pytest.mark.parametrize("nullable", [False, True]) +def test_integer_vector_validation(vector_type, nullable): + annotation = vector_type(2, value_type=pa.int64(), nullable=nullable) + + class Row(LanceModel): + payload: annotation + + def shape(values): + return [values] if vector_type is MultiVector else values + + assert Row.to_arrow_schema().field("payload").nullable is nullable + assert Row(payload=shape([1.0, -2.0])).model_dump()["payload"] == shape([1, -2]) + with pytest.raises(pydantic.ValidationError, match="valid integer"): + Row(payload=shape([1.5, 2])) + with pytest.raises(pydantic.ValidationError): + Row(payload=shape([1])) + with pytest.raises(pydantic.ValidationError): + Row(payload=shape([1, 2, 3])) + with pytest.raises(pydantic.ValidationError): + Row(payload=None) + + class OptionalRow(LanceModel): + payload: Optional[annotation] = None + + assert OptionalRow(payload=None).payload is None + + def test_bare_vector_raises_clear_error(): namespace = { "__name__": "test_model_without_pyarrow", @@ -733,3 +815,52 @@ def test_enum_types(): assert schema.field("priority").type == pa.int64() assert schema.field("opt_status").type == pa.dictionary(pa.int32(), pa.utf8()) assert schema.field("opt_status").nullable + + +def test_plain_enum_values_are_written(mem_db): + """Members of an Enum without a str/int mixin are written as their values.""" + + class Color(Enum): + RED = "red" + BLUE = "blue" + + class Priority(Enum): + LOW = 1 + HIGH = 2 + + class Tag(LanceModel): + color: Color + + class TestModel(LanceModel): + color: Color + priority: Priority + opt_color: Optional[Color] = None + colors: List[Color] + tag: Tag + vector: Vector(2) + + rows = [ + TestModel( + color=Color.RED, + priority=Priority.HIGH, + opt_color=Color.BLUE, + colors=[Color.BLUE, Color.RED], + tag=Tag(color=Color.BLUE), + vector=[1.0, 2.0], + ), + TestModel( + color=Color.BLUE, + priority=Priority.LOW, + colors=[], + tag=Tag(color=Color.RED), + vector=[3.0, 4.0], + ), + ] + tbl = mem_db.create_table("test", schema=TestModel) + tbl.add(rows) + + assert tbl.to_arrow().select(["color", "priority", "opt_color"]).to_pylist() == [ + {"color": "red", "priority": 2, "opt_color": "blue"}, + {"color": "blue", "priority": 1, "opt_color": None}, + ] + assert tbl.search().to_pydantic(TestModel) == rows diff --git a/python/python/tests/test_pydantic_excluded_fields.py b/python/python/tests/test_pydantic_excluded_fields.py new file mode 100644 index 000000000..5f1fd1adb --- /dev/null +++ b/python/python/tests/test_pydantic_excluded_fields.py @@ -0,0 +1,128 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import lancedb +import pytest +from pydantic import BaseModel, Field +from lancedb.pydantic import LanceModel + + +class Details(BaseModel): + label: str + transient: str = Field(default="nested default", exclude=True) + + +class Row(LanceModel): + id: int + details: Details + transient: str = Field(default="local default", exclude=True) + generated: list[str] = Field(default_factory=lambda: ["local"], exclude=True) + retained: str = Field(default="persisted", exclude=False) + + +def rows(): + return [ + Row( + id=i, + details=Details(label=str(i), transient="private"), + transient="private", + generated=["private"], + ) + for i in (1, 2) + ] + + +def assert_schema(schema): + assert schema.names == ["id", "details", "retained"] + assert [field.name for field in schema.field("details").type] == ["label"] + assert Row.field_names() == ["id", "details", "transient", "generated", "retained"] + + +def assert_restored(restored): + assert sorted(row.id for row in restored) == [1, 2] + for row in restored: + assert row.transient == "local default" + assert row.generated == ["local"] + assert row.details.transient == "nested default" + assert row.details.label == str(row.id) + assert row.retained == "persisted" + + +@pytest.mark.parametrize("explicit_schema", [False, True]) +def test_excluded_fields_round_trip(tmp_path, explicit_schema): + data = rows() + kwargs = {"schema": Row} if explicit_schema else {} + db = lancedb.connect(tmp_path) + table = db.create_table("rows", data=data[:1], **kwargs) + table.add(data[1:]) + assert_schema(table.schema) + reopened = lancedb.connect(tmp_path).open_table("rows") + assert_restored(reopened.search().to_pydantic(Row)) + assert data[0].transient == "private" + assert data[0].generated == ["private"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("explicit_schema", [False, True]) +async def test_excluded_fields_round_trip_async(tmp_path, explicit_schema): + data = rows() + kwargs = {"schema": Row} if explicit_schema else {} + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("rows", data=data[:1], **kwargs) + await table.add(data[1:]) + assert_schema(await table.schema()) + reopened_db = await lancedb.connect_async(tmp_path) + reopened = await reopened_db.open_table("rows") + assert_restored(await reopened.query().to_pydantic(Row)) + assert data[0].details.transient == "private" + + +@pytest.mark.parametrize("excluded", ["transient", "source", "vector"]) +def test_excluded_fields_keep_embedding_metadata_consistent( + tmp_path, monkeypatch, excluded +): + from lancedb.embeddings.base import TextEmbeddingFunction + from lancedb.embeddings.registry import get_registry + from lancedb.pydantic import Vector + + calls = [] + + class LocalEmbedding(TextEmbeddingFunction): + def ndims(self): + return 2 + + def generate_embeddings(self, texts): + calls.extend(texts) + return [[1.0, 0.0] for _ in texts] + + registry = get_registry() + monkeypatch.setattr(registry, "_functions", registry._functions.copy()) + registry.register("test-excluded-fields")(LocalEmbedding) + function = LocalEmbedding.create(max_retries=0) + + class EmbeddedRow(LanceModel): + text: str = function.SourceField(default="alpha", exclude=excluded == "source") + vector: Vector(2) = function.VectorField( + default_factory=lambda: [1.0, 0.0], exclude=excluded == "vector" + ) + transient: str = Field(default="local", exclude=True) + + configs = EmbeddedRow.parse_embedding_functions() + assert len(configs) == (1 if excluded == "transient" else 0) + db = lancedb.connect(tmp_path) + data = [{"text": "alpha"}] if excluded == "transient" else [EmbeddedRow()] + table = db.create_table("embeddings", schema=EmbeddedRow, data=data) + assert "transient" not in table.schema.names + assert ("text" in table.schema.names) == (excluded != "source") + assert ("vector" in table.schema.names) == (excluded != "vector") + reopened = lancedb.connect(tmp_path).open_table("embeddings") + assert len(reopened.embedding_functions) == len(configs) + restored = reopened.search().to_pydantic(EmbeddedRow) + assert restored[0].text == "alpha" + assert restored[0].vector == [1.0, 0.0] + assert restored[0].transient == "local" + if excluded == "transient": + assert calls == ["alpha"] + assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha" + else: + assert calls == [] diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index c8d0ad159..b898a8888 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -675,10 +675,10 @@ def test_blob_v2_vector_projection_and_plain_scan_options(tmp_db, monkeypatch): query = table.search().where("id = 1") - def fail_to_arrow(*args, **kwargs): - raise AssertionError("the native scanner should handle bytes with flatten") + def fail_to_lance(*args, **kwargs): + raise AssertionError("blob v2 bytes should not open a pylance dataset") - monkeypatch.setattr(query, "to_arrow", fail_to_arrow) + monkeypatch.setattr(table, "to_lance", fail_to_lance) assert query.to_pandas(blob_mode="bytes", flatten=True)["blob"].tolist() == [b"one"] flattened_lazy = table.search().where("id = 1").to_pandas(flatten=True) @@ -833,6 +833,28 @@ def test_with_row_id(table: lancedb.table.Table): assert rs["_rowid"].to_pylist() == [0, 1] +def test_filter_preserves_deeply_nested_struct_fields(tmp_db): + # Regression test for https://github.com/lancedb/lancedb/issues/2217. + data = [ + { + "item": "test", + "sub_obj": { + "second_sub_obj": [ + { + "third_sub_obj": {"int_val": 1}, + "str_val": "test", + } + ] + }, + } + ] + table = tmp_db.create_table("deeply_nested_struct", data=data) + + result = table.search().where("item = 'test'").limit(1).to_arrow() + + assert result.to_pylist() == data + + def test_blob_v2_query_omits_auto_row_id(tmp_db): table = _create_blob_v2_query_table(tmp_db, "test_blob_v2_omits_auto_rowid") @@ -1955,6 +1977,56 @@ def test_query_serialization_sync(table: lancedb.table.Table): check_set_props(q, full_text_query=FullTextSearchQuery(columns=[], query="foo")) +@pytest.mark.asyncio +@pytest.mark.parametrize("query_type", ["plain", "fts", "vector"]) +@pytest.mark.parametrize("fast_search", [False, True]) +@pytest.mark.parametrize("postfilter", [False, True]) +async def test_query_serialization_async_search_options( + table_async: AsyncTable, query_type, fast_search, postfilter +): + query = table_async.query().where("id = 1") + if query_type == "fts": + query = query.nearest_to_text(MatchQuery("dog", "text")) + elif query_type == "vector": + query = query.nearest_to([1.0, 2.0]) + if fast_search: + query = query.fast_search() + if postfilter: + query = query.postfilter() + + serialized = query.to_query_object() + assert serialized.fast_search is (True if fast_search else None) + default_postfilter = False if query_type == "vector" else None + assert serialized.postfilter is (True if postfilter else default_postfilter) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fast_search", [False, True]) +async def test_query_serialization_async_fast_search_execution( + table_async, fast_search +): + await table_async.create_index("text", config=FTS()) + await table_async.add( + [ + { + "id": 3, + "vector": [5.0, 6.0], + "str_field": "c", + "float_field": 3.0, + "text": "unindexed dog", + } + ] + ) + query = table_async.query().nearest_to_text(MatchQuery("unindexed", "text")) + if fast_search: + query = query.fast_search() + + expected_ids = [] if fast_search else [3] + assert [row["id"] for row in await query.to_list()] == expected_ids + restored = table_async._sync_query_to_async(query.to_query_object()) + assert [row["id"] for row in await restored.to_list()] == expected_ids + + @pytest.mark.asyncio async def test_query_serialization_async(table_async: AsyncTable): # Simple queries @@ -2302,6 +2374,33 @@ def test_take_queries(tmp_path): ] +def test_take_queries_with_row_id(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("test", pa.table({"idx": range(100)})) + + by_row_id = table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow() + assert "_rowid" in by_row_id.column_names + by_offset = table.take_offsets([5, 2, 17], with_row_id=True).to_arrow() + assert "_rowid" in by_offset.column_names + + # The column is opt-in and must stay out of the default projection. + assert "_rowid" not in table.take_row_ids([5, 2, 17]).to_arrow().column_names + + +@pytest.mark.asyncio +async def test_take_queries_with_row_id_async(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", pa.table({"idx": range(100)})) + + 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 + by_offset = await table.take_offsets([5, 2, 17], with_row_id=True).to_arrow() + assert "_rowid" in by_offset.column_names + + default = await table.take_row_ids([5, 2, 17]).to_arrow() + assert "_rowid" not in default.column_names + + def test_take_queries_to_batches(tmp_path): # Regression test for the sync take-query path: `to_batches` previously # raised ``AttributeError: 'AsyncTakeQuery' object has no attribute diff --git a/python/python/tests/test_read_consistency_interval.py b/python/python/tests/test_read_consistency_interval.py new file mode 100644 index 000000000..bc69775ea --- /dev/null +++ b/python/python/tests/test_read_consistency_interval.py @@ -0,0 +1,83 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import timedelta + +import lancedb +import pytest +from lance_namespace import connect as connect_namespace_client +from lancedb import _lancedb +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): + interval = timedelta(seconds=seconds) + with pytest.raises(ValueError, match="read_consistency_interval"): + if kind == "sync": + lancedb.connect(tmp_path, read_consistency_interval=interval) + elif kind == "client": + client = connect_namespace_client("dir", {"root": str(tmp_path)}) + LanceNamespaceDBConnection(client, read_consistency_interval=interval) + else: + connect = ( + lancedb.connect_namespace + if kind == "namespace" + else lancedb.connect_namespace_async + ) + connect("dir", {"root": str(tmp_path)}, read_consistency_interval=interval) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("seconds", [-1.0, -0.000001]) +async def test_negative_async_read_consistency_interval(tmp_path, seconds): + with pytest.raises(ValueError, match="read_consistency_interval"): + await lancedb.connect_async( + tmp_path, read_consistency_interval=timedelta(seconds=seconds) + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("seconds", [float("nan"), float("inf"), -float("inf"), 1e30]) +@pytest.mark.parametrize("kind", ["connect", "namespace", "client"]) +async def test_binding_rejects_invalid_read_consistency_interval( + tmp_path, seconds, kind +): + with pytest.raises(ValueError, match="read_consistency_interval"): + if kind == "connect": + await _lancedb.connect(str(tmp_path), read_consistency_interval=seconds) + elif kind == "namespace": + _lancedb.connect_namespace( + "dir", {"root": str(tmp_path)}, read_consistency_interval=seconds + ) + else: + client = connect_namespace_client("dir", {"root": str(tmp_path)}) + _lancedb.connect_namespace_client(client, read_consistency_interval=seconds) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "interval", [None, timedelta(0), timedelta(microseconds=1), timedelta(seconds=5)] +) +async def test_valid_read_consistency_intervals(tmp_path, interval): + db = lancedb.connect(tmp_path / "sync", read_consistency_interval=interval) + assert db.read_consistency_interval == interval + db.close() + + db = await lancedb.connect_async( + tmp_path / "async", read_consistency_interval=interval + ) + assert await db.get_read_consistency_interval() == interval + db.close() + + db = lancedb.connect_namespace( + "dir", {"root": str(tmp_path / "namespace")}, read_consistency_interval=interval + ) + assert db.read_consistency_interval == interval + db.close() + + client = connect_namespace_client("dir", {"root": str(tmp_path / "client")}) + db = LanceNamespaceDBConnection(client, read_consistency_interval=interval) + assert db.read_consistency_interval == interval + db.close() diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 80bd10289..415f8be3c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5,11 +5,14 @@ import contextlib from datetime import timedelta import http.server import io +import inspect import json import multiprocessing as mp import pickle import re +import subprocess import sys +import textwrap import threading import time from unittest.mock import MagicMock, patch @@ -31,6 +34,7 @@ from lancedb.remote import ClientConfig from lancedb.remote.errors import HttpError, RetryError import pytest import pyarrow as pa +from utils import start_server_thread def make_mock_http_handler(handler): @@ -51,46 +55,17 @@ def test_connect_rejects_invalid_cloud_dns_hostname(db_name): @contextlib.contextmanager -def mock_lancedb_connection(handler): +def mock_lancedb_connection(handler, **client_config): with http.server.HTTPServer( - ("localhost", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", - client_config={ - "retry_config": {"retries": 2}, - "timeout_config": { - "connect_timeout": 1, - }, - }, - ) - - try: - yield db - finally: - server.shutdown() - handle.join() - - -@contextlib.asynccontextmanager -async def mock_lancedb_connection_async(handler, **client_config): - with http.server.HTTPServer( - ("localhost", 0), make_mock_http_handler(handler) - ) as server: - port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() - - db = await lancedb.connect_async( - "db://dev", - api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 2}, "timeout_config": { @@ -107,6 +82,129 @@ async def mock_lancedb_connection_async(handler, **client_config): handle.join() +@contextlib.asynccontextmanager +async def mock_lancedb_connection_async(handler, **client_config): + with http.server.HTTPServer( + ("127.0.0.1", 0), make_mock_http_handler(handler) + ) as server: + port = server.server_address[1] + handle = start_server_thread(server) + + db = await lancedb.connect_async( + "db://dev", + api_key="fake", + host_override=f"http://127.0.0.1:{port}", + client_config={ + "retry_config": {"retries": 2}, + "timeout_config": { + "connect_timeout": 1, + }, + **client_config, + }, + ) + + try: + yield db + finally: + server.shutdown() + handle.join() + + +@pytest.fixture +def existence_handler(method, identifier, status): + def handler(request): + resource = "namespace" if method == "namespace_exists" else "table" + resource_id = "$".join(identifier) or "$" + suffix = "/" if resource == "table" else "" + assert request.command == "POST" + assert request.path == f"/v1/{resource}/{resource_id}/describe{suffix}" + assert request.headers["x-api-key"] == "fake" + assert request.headers["X-Exists-Test"] == "present" + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b"{}" if status == 200 else b"lookup failed") + + return handler + + +@pytest.mark.parametrize( + "method,identifier", + [ + ("namespace_exists", []), + ("namespace_exists", ["ns"]), + ("namespace_exists", ["parent", "ns"]), + ("table_exists", ["table"]), + ("table_exists", ["parent", "ns", "table"]), + ], +) +@pytest.mark.parametrize("status", [200, 404, 403, 507]) +def test_remote_exists(method, identifier, status, existence_handler): + from lancedb.remote.header import StaticHeaderProvider + + provider = StaticHeaderProvider({"X-Exists-Test": "present"}) + with mock_lancedb_connection(existence_handler, header_provider=provider) as db: + if status in (200, 404): + assert getattr(db, method)(identifier) is (status == 200) + else: + with pytest.raises(HttpError) as exc_info: + getattr(db, method)(identifier) + assert exc_info.value.status_code == status + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "method,identifier", + [ + ("namespace_exists", []), + ("namespace_exists", ["parent", "ns"]), + ("table_exists", ["table"]), + ("table_exists", ["parent", "ns", "table"]), + ], +) +@pytest.mark.parametrize("status", [200, 404, 403, 507]) +async def test_async_remote_exists(method, identifier, status, existence_handler): + from lancedb.remote.header import StaticHeaderProvider + + provider = StaticHeaderProvider({"X-Exists-Test": "present"}) + async with mock_lancedb_connection_async( + existence_handler, header_provider=provider + ) as db: + if status in (200, 404): + assert await getattr(db, method)(identifier) is (status == 200) + else: + with pytest.raises(HttpError) as exc_info: + await getattr(db, method)(identifier) + assert exc_info.value.status_code == status + + +@pytest.mark.parametrize("table_id", [[], ["invalid/name"]]) +def test_remote_table_exists_rejects_invalid_identifier(table_id): + requests = [] + with mock_lancedb_connection(lambda request: requests.append(request.path)) as db: + with pytest.raises(ValueError): + db.table_exists(table_id) + assert requests == [] + + +def test_remote_table_exists_rechecks_cached_table(): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200 if len(requests) == 1 else 404) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b"{}") + + with mock_lancedb_connection(handler) as db: + table_id = ["ns", "table"] + assert db.table_exists(table_id) is True + assert db.table_exists(table_id) is False + assert table_id == ["ns", "table"] + assert requests == ["/v1/table/ns$table/describe/"] * 2 + + def paginated_table_listing_handler(request): url = urlparse(request.path) assert url.path in { @@ -561,16 +659,15 @@ def test_remote_table_open_does_not_require_picklable_client_config(): request.end_headers() with http.server.HTTPServer( - ("localhost", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) try: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -765,6 +862,15 @@ def test_create_table_embedding_functions(with_schema): ] +def test_create_table_positional_parameters_match_base_contract(): + from lancedb.db import DBConnection + from lancedb.remote.db import RemoteDBConnection + + expected = list(inspect.signature(DBConnection.create_table).parameters)[:9] + actual = list(inspect.signature(RemoteDBConnection.create_table).parameters)[:9] + assert actual == expected + + def test_create_table_exist_ok(): def handler(request): if request.path == "/v1/table/test/create/?mode=exist_ok": @@ -801,6 +907,43 @@ def test_create_table_exist_ok_with_mode_overwrite(): assert table is not None +@pytest.mark.asyncio +@pytest.mark.parametrize( + "timeout_config", + [{"read_timeout": 0.5}, {"timeout": 0.5, "read_timeout": 5}], +) +async def test_create_table_timeout_is_actionable(timeout_config): + release_response = threading.Event() + received = {} + + def handler(request): + received["path"] = request.path + received["request_id"] = request.headers["x-request-id"] + release_response.wait(timeout=5) + request.close_connection = True + + async with mock_lancedb_connection_async( + handler, timeout_config=timeout_config + ) as db: + batch = pa.record_batch({"id": [1, 2]}) + reader = pa.RecordBatchReader.from_batches(batch.schema, [batch]) + try: + with pytest.raises(HttpError) as exc_info: + await db.create_table("test", reader) + finally: + release_response.set() + + error = exc_info.value + assert "timed out" in str(error) + assert "client_config.timeout_config.read_timeout" in str(error) + assert "client_config.timeout_config.timeout" in str(error) + assert "LANCE_CLIENT_READ_TIMEOUT" in str(error) + assert received["path"] == "/v1/table/test/create/?mode=create" + assert error.request_id == received["request_id"] + assert error.status_code is None + assert isinstance(error.__cause__, HttpError) + + @pytest.mark.asyncio async def test_http_error(): request_id_holder = {"request_id": None} @@ -857,10 +1000,116 @@ def test_table_unimplemented_functions(): with mock_lancedb_connection(handler) as db: table = db.create_table("test", [{"id": 1}]) - with pytest.raises(NotImplementedError): - table.to_arrow() - with pytest.raises(NotImplementedError): - table.to_pandas() + for method in ["to_arrow", "to_pandas", "to_polars"]: + with pytest.raises(NotImplementedError) as exc_info: + getattr(table, method)() + message = str(exc_info.value) + assert method in message + assert "not" in message and "supported" in message + assert "LanceDB Distributed" in message + assert "cloud" not in message.lower() + assert f"search().{method}()" in message + + +@pytest.mark.parametrize("method", ["to_arrow", "to_pandas"]) +@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes", "invalid"]) +def test_remote_conversion_blob_mode_errors(method, blob_mode): + with blob_remote_table() as table: + if blob_mode == "invalid": + with pytest.raises(ValueError, match="blob_mode must be one of"): + getattr(table, method)(blob_mode=blob_mode) + else: + with pytest.raises(NotImplementedError) as error: + getattr(table, method)(blob_mode=blob_mode) + assert f"search().{method}()" in str(error.value) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("version", [None, 1]) +@pytest.mark.parametrize("expose_location", [False, True]) +async def test_remote_to_lance_rejection( + tmp_path, version, expose_location, monkeypatch +): + import lance + + location = tmp_path / "test.lance" + lance.write_dataset(pa.table({"id": [1]}), location) + lance.write_dataset(pa.table({"id": [2]}), location, mode="append") + requests = [] + + def fail_dataset(*args, **kwargs): + raise AssertionError("remote storage must not be opened") + + monkeypatch.setattr(lance, "dataset", fail_dataset) + + def handler(request): + requests.append(request.path) + assert request.path == "/v1/table/test/describe/" + content_len = int(request.headers.get("Content-Length", 0)) + body = json.loads(request.rfile.read(content_len)) if content_len else {} + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + response = { + "version": body.get("version") or 2, + "schema": {"fields": []}, + } + if expose_location: + response["location"] = str(location) + request.wfile.write(json.dumps(response).encode()) + + options = {"default_scan_options": {"with_row_id": True}} + with mock_lancedb_connection(handler) as db: + table = db.open_table("test", version=version) + opened_requests = list(requests) + with pytest.raises(NotImplementedError) as sync_error: + table.to_lance(**options) + assert requests == opened_requests + + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test", version=version) + opened_requests = list(requests) + with pytest.raises(NotImplementedError) as async_error: + await table.to_lance(**options) + assert requests == opened_requests + + assert "to_lance() is not supported in LanceDB Distributed" 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", + [ + ("drop_all_tables", {}), + ("drop_all_tables", {"namespace_path": []}), + ("drop_all_tables", {"namespace_path": ["team"]}), + ("drop_database", {}), + ], +) +async def test_remote_drop_all_tables_not_supported(method, kwargs): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(500) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + with pytest.raises(NotImplementedError) as sync_error: + 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) + + 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 == [] def test_table_to_pandas_not_supported(): @@ -1039,8 +1288,9 @@ def test_table_create_indices(): # Test create_fts_index with custom name (legacy method) with pytest.warns(DeprecationWarning, match="create_fts_index"): table.create_fts_index( - "text", + field_names="text", wait_timeout=timedelta(seconds=2), + tokenizer_name="en_stem", block_size=256, custom_stop_words=["cloud"], name="custom_fts_idx", @@ -1049,6 +1299,8 @@ def test_table_create_indices(): # Test create_index with custom name (legacy form: vector_column_name kwarg) with pytest.warns(DeprecationWarning, match="create_index"): table.create_index( + "cosine", + 2, vector_column_name="vector", wait_timeout=timedelta(seconds=10), name="custom_vector_idx", @@ -1061,7 +1313,8 @@ def test_table_create_indices(): scalar_req = received_requests[0] assert "name" in scalar_req assert scalar_req["name"] == "custom_scalar_idx" - assert scalar_req["replace"] is False + # The wire protocol omits replace=True (the server default). + assert "replace" not in scalar_req # Check FTS index request has custom name fts_req = received_requests[1] @@ -1070,18 +1323,39 @@ def test_table_create_indices(): assert fts_req["replace"] is False assert fts_req["block_size"] == 256 assert fts_req["custom_stop_words"] == ["cloud"] + assert fts_req["language"] == "English" + assert fts_req["stem"] is True # Check vector index request has custom name vector_req = received_requests[2] assert "name" in vector_req assert vector_req["name"] == "custom_vector_idx" assert "replace" not in vector_req + assert vector_req["metric_type"] == "cosine" + assert vector_req["num_partitions"] == 2 + + with pytest.warns(DeprecationWarning, match="create_index"): + table.create_index( + index_type="IVF_HNSW_SQ", + num_partitions=1, + m=10, + ef_construction=50, + max_iterations=12, + sample_rate=64, + ) + tuned_req = received_requests[-1] + assert tuned_req["index_type"] == "IVF_HNSW_SQ" + assert tuned_req["num_partitions"] == 1 + assert tuned_req["m"] == 10 + assert tuned_req["ef_construction"] == 50 + assert tuned_req["max_iterations"] == 12 + assert tuned_req["sample_rate"] == 64 table.wait_for_index(["custom_scalar_idx"], timedelta(seconds=2)) table.wait_for_index( ["custom_fts_idx", "custom_vector_idx"], timedelta(seconds=2) ) - table.drop_index("custom_vector_idx") + table.drop_index(name="custom_vector_idx") table.drop_index("custom_scalar_idx") table.drop_index("custom_fts_idx") @@ -1477,7 +1751,10 @@ def test_remote_json_fts_config(server_version): assert request["block_size"] == 256 -def test_remote_create_index_new_api(caplog): +@pytest.mark.parametrize( + "rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}] +) +def test_remote_create_index_new_api(caplog, rq_kwargs): received_requests = [] def handler(request): @@ -1550,7 +1827,7 @@ def test_remote_create_index_new_api(caplog): table.create_index("category", config=BTree()) table.create_index("text", config=FTS(block_size=256)) # IvfRq via new API - table.create_index("vector", config=IvfRq(distance_type="l2")) + table.create_index("vector", config=IvfRq(distance_type="l2", **rq_kwargs)) table.create_index( "vector", config=IvfPq(distance_type="l2"), replace=False ) @@ -1575,11 +1852,16 @@ def test_remote_create_index_new_api(caplog): "vector", ] assert received_requests[2]["block_size"] == 256 + if rq_kwargs.get("num_bits") is None: + assert "num_bits" not in received_requests[3] + else: + assert received_requests[3]["num_bits"] == rq_kwargs["num_bits"] assert received_requests[4]["replace"] is False assert received_requests[5]["replace"] is False assert "replace is not supported" not in caplog.text assert caplog.messages == [ - "GPU accelerator is not supported for remote tables and will be ignored." + "GPU accelerator is not supported in LanceDB Distributed " + "and will be ignored." ] @@ -1637,7 +1919,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 += "for remote tables." + expected += "in LanceDB Distributed." if operation == "IVF_HNSW_PQ": expected += " Please use IVF_HNSW_SQ instead." assert str(error.value) == expected @@ -1655,7 +1937,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 += "for remote tables." + expected += "in LanceDB Distributed." if operation == "IVF_HNSW_PQ": expected += " Please use IVF_HNSW_SQ instead." assert str(error.value) == expected @@ -1667,7 +1949,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 for remote tables. " + match="IVF_HNSW_PQ is not supported in LanceDB Distributed. " "Please use IVF_HNSW_SQ instead.", ): table.create_index( @@ -1675,21 +1957,25 @@ def test_remote_unsupported_legacy_hnsw_pq(): ) -def test_remote_python_only_messages(caplog): +def test_remote_python_only_messages(): with mock_lancedb_connection(remote_unsupported_handler) as db: - with caplog.at_level("INFO"): - table = db.open_table("test", storage_options={}, index_cache_size=1) - assert "storage_options is ignored for remote tables" in caplog.text - assert "index_cache_size is ignored for remote tables" in caplog.text - for method in ["to_arrow", "to_pandas"]: + for options in [{"storage_options": {}}, {"index_cache_size": 1}]: + with pytest.raises(NotImplementedError, match=next(iter(options))): + db.open_table("test", **options) + table = db.open_table("test") + for method in ["to_arrow", "to_pandas", "to_polars"]: with pytest.raises(NotImplementedError) as error: getattr(table, method)() - assert str(error.value) == f"{method}() is not supported for remote tables." + assert str(error.value) == ( + f"{method}() is not supported in LanceDB Distributed. " + f"Use table.search().{method}() instead." + ) for method in ["compact_files", "cleanup_old_versions"]: with pytest.warns(UserWarning) as warning: getattr(table, method)() assert ( - str(warning[0].message) == f"{method}() is a no-op for remote tables." + str(warning[0].message) + == f"{method}() is a no-op in LanceDB Distributed." ) @@ -1793,6 +2079,79 @@ def test_table_wait_for_index_timeout(): table.wait_for_index(["id_idx"], timedelta(seconds=1)) +def _jieba_fts_handler(request): + """Serve a table with a ``jieba/default`` FTS index and no other state.""" + if request.path == "/v1/table/test/describe/": + body = { + "version": 1, + "schema": { + "fields": [ + {"name": "text", "type": {"type": "string"}, "nullable": True} + ] + }, + } + elif request.path == "/v1/table/test/index/list/": + index_details = { + "base_tokenizer": "jieba/default", + "language": "English", + "with_position": False, + "max_token_length": 40, + "lower_case": True, + "stem": False, + "remove_stop_words": False, + "ascii_folding": False, + } + body = { + "indexes": [ + { + "index_name": "text_idx", + "columns": ["text"], + "index_type": "FTS", + "index_details": json.dumps(index_details), + } + ] + } + else: + request.send_response(404) + request.end_headers() + return + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(body).encode()) + + +_MODEL_FILES_ERROR = ( + r"(?s)Invalid directory path.*" + r"full text search index 'text_idx'.*" + r"tokenize\(\) runs on the client.*'jieba/default'.*" + r"LANCE_LANGUAGE_MODEL_HOME.*match the files the server uses" +) + + +def test_remote_tokenize_model_backed_without_model_files(tmp_path, monkeypatch): + monkeypatch.setenv("LANCE_LANGUAGE_MODEL_HOME", str(tmp_path)) + with mock_lancedb_connection(_jieba_fts_handler) as db: + table = db.open_table("test") + with pytest.raises(ValueError, match=_MODEL_FILES_ERROR): + table.tokenize("我们是中国人", index_name="text_idx") + with pytest.raises(ValueError, match=_MODEL_FILES_ERROR): + table.tokenize("我们是中国人", column="text") + + +@pytest.mark.asyncio +async def test_remote_tokenize_model_backed_without_model_files_async( + tmp_path, monkeypatch +): + monkeypatch.setenv("LANCE_LANGUAGE_MODEL_HOME", str(tmp_path)) + async with mock_lancedb_connection_async(_jieba_fts_handler) as db: + table = await db.open_table("test") + with pytest.raises(ValueError, match=_MODEL_FILES_ERROR): + await table.tokenize("我们是中国人", index_name="text_idx") + with pytest.raises(ValueError, match=_MODEL_FILES_ERROR): + await table.tokenize("我们是中国人", column="text") + + def test_stats(): stats = { "total_bytes": 38, @@ -2152,6 +2511,23 @@ def test_head(): assert data == pa.table({"id": [1, 2, 3]}) +def test_remote_take_row_ids_with_row_id(): + bodies = [] + + def handler(body): + bodies.append(body) + return pa.table({"id": [1, 2], "_rowid": pa.array([0, 1], pa.uint64())}) + + with query_test_table(handler) as table: + result = table.take_row_ids([0, 1], with_row_id=True).to_arrow() + assert "_rowid" in result.column_names + 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] + + def test_query_sync_minimal(): def handler(body): assert body == { @@ -2871,17 +3247,16 @@ def test_header_provider_with_sync_connection(): # Create connection with custom client config with http.server.HTTPServer( - ("localhost", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) try: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 2}, "timeout_config": {"connect_timeout": 1}, @@ -3085,7 +3460,7 @@ def _remote_fork_child(port: int, queue) -> None: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -3119,17 +3494,16 @@ def test_remote_connection_after_fork(): request.end_headers() request.wfile.write(b'{"tables": []}') - server = http.server.HTTPServer(("localhost", 0), make_mock_http_handler(handler)) + server = http.server.HTTPServer(("127.0.0.1", 0), make_mock_http_handler(handler)) port = server.server_address[1] - server_thread = threading.Thread(target=server.serve_forever) - server_thread.start() + server_thread = start_server_thread(server) try: # Hit the server in the parent first so the runtime + LOOP are warm # before fork; a fresh child must still succeed. parent_db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -3185,15 +3559,14 @@ def test_inherited_remote_table_reopens_after_fork(): request.send_response(404) request.end_headers() - server = http.server.HTTPServer(("localhost", 0), make_mock_http_handler(handler)) + server = http.server.HTTPServer(("127.0.0.1", 0), make_mock_http_handler(handler)) port = server.server_address[1] - server_thread = threading.Thread(target=server.serve_forever) - server_thread.start() + server_thread = start_server_thread(server) try: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -3254,6 +3627,128 @@ BLOB_DESCRIBE_RESPONSE = { } +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("with_pylance", [False, True]) +@pytest.mark.parametrize("nested", [False, True]) +def test_remote_schema_restores_blob_extensions(use_async, with_pylance, nested): + description = json.loads(json.dumps(BLOB_DESCRIBE_RESPONSE)) + without_ranges = description["schema"]["fields"].pop() + without_ranges["name"] = "without_ranges" + image = json.loads(json.dumps(without_ranges)) + image["name"] = "image" + image["nullable"] = False + image["metadata"]["lance-encoding:blob-inline-size-threshold"] = "8192" + image["type"]["fields"].extend( + {"name": name, "type": {"type": "uint64"}, "nullable": True} + for name in ("position", "size") + ) + plain = { + "name": "plain", + "type": image["type"], + "nullable": True, + "metadata": {"app-key": "app-value"}, + } + fields = [image, without_ranges, plain] + if nested: + fields = [ + { + "name": "nested", + "type": {"type": "struct", "fields": fields}, + "nullable": False, + }, + { + "name": "images", + "type": {"type": "list", "fields": [image]}, + "nullable": True, + }, + ] + description["schema"]["fields"].extend(fields) + description["schema"]["metadata"] = {"schema-key": "schema-value"} + + def handler(request): + assert request.path == "/v1/table/test/describe/" + send_json(request, description) + + # A fresh interpreter must read the schema before blob() or a pylance import + # registers the extension type and hides the original failure. + script = textwrap.dedent( + """\ + import asyncio + import importlib.abc + import sys + import pyarrow as pa + + if sys.argv[3] == "False": + class NoLance(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == "lance" or fullname.startswith("lance."): + raise ModuleNotFoundError(fullname, name="lance") + sys.meta_path.insert(0, NoLance()) + import lancedb + + assert "lance.blob" not in sys.modules + options = dict(api_key="fake", host_override=sys.argv[1]) + + async def read_schema(): + db = await lancedb.connect_async("db://dev", **options) + table = await db.open_table("test") + return await table.schema() + + if sys.argv[2] == "True": + schema = asyncio.run(read_schema()) + else: + db = lancedb.connect("db://dev", **options) + schema = db.open_table("test").schema + + assert schema.metadata == {b"schema-key": b"schema-value"} + assert schema.field("id") == pa.field("id", pa.int64(), nullable=False) + if sys.argv[4] == "True": + assert not schema.field("nested").nullable + fields = schema.field("nested").type + assert schema.field("images").type.value_field.equals( + fields.field("image"), check_metadata=True + ) + else: + fields = schema + + image = fields.field("image") + assert isinstance(image.type, pa.ExtensionType), image + assert image.type == lancedb.blob("x").type + assert type(image.type) is lancedb.BlobType + assert not image.nullable + assert image.metadata == { + b"lance-encoding:blob-inline-size-threshold": b"8192" + } + plain = fields.field("plain") + assert plain.type == image.type.storage_type + assert plain.metadata == {b"app-key": b"app-value"} + without_ranges = fields.field("without_ranges") + assert isinstance(without_ranges.type, pa.ExtensionType), without_ranges + assert type(without_ranges.type) is lancedb.BlobType + assert without_ranges.type.storage_type == pa.struct([ + pa.field("data", pa.large_binary()), pa.field("uri", pa.string()) + ]) + assert without_ranges.nullable + """ + ) + with mock_lancedb_connection(handler) as db: + result = subprocess.run( + [ + sys.executable, + "-c", + script, + db.host_override, + str(use_async), + str(with_pylance), + str(nested), + ], + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stderr + + @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) @pytest.mark.parametrize("mode", ["merge", "overwrite"]) @@ -3400,14 +3895,17 @@ def blob_descriptor_take_table(): @contextlib.contextmanager -def blob_remote_table(*, server_version=Version("0.5.0")): +def blob_remote_table(*, server_version=Version("0.5.0"), location=None): def handler(request): if request.path == "/v1/table/test/describe/": request.send_response(200) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", str(server_version)) request.end_headers() - request.wfile.write(json.dumps(BLOB_DESCRIBE_RESPONSE).encode()) + response = dict(BLOB_DESCRIBE_RESPONSE) + if location is not None: + response["location"] = str(location) + request.wfile.write(json.dumps(response).encode()) elif request.path.startswith("/v1/table/test/blob/image/"): path = request.path.partition("?")[0] row_id = int(path.split("/")[-2]) @@ -3442,7 +3940,6 @@ def blob_remote_table(*, server_version=Version("0.5.0")): if columns == ["id"]: response_table = blob_query_response_table().select(["id"]) else: - assert body["with_row_id"] is True if columns == ["image"]: # Blob handles are sized from a descriptor take. assert body["filter"].startswith("_rowid IN") @@ -3455,6 +3952,8 @@ def blob_remote_table(*, server_version=Version("0.5.0")): ) else: response_table = blob_query_response_table() + if not body.get("with_row_id", False): + response_table = response_table.drop(["_rowid"]) request.send_response(200) request.send_header("Content-Type", "application/vnd.apache.arrow.file") request.send_header("x-lancedb-version", "1") @@ -3489,6 +3988,32 @@ def test_remote_blob_columns_and_fetch(): assert blobs.to_pylist() == [b"alpha", None, b"gamma"] +@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes", "lazy"]) +def test_sync_remote_blob_pandas_avoids_storage_access( + tmp_path, monkeypatch, blob_mode +): + import lance + + location = tmp_path / "remote.lance" + lance.write_dataset(pa.table({"id": [7], "image": [b"server-owned"]}), location) + + def fail_dataset(*args, **kwargs): + raise AssertionError("remote storage must not be opened") + + monkeypatch.setattr(lance, "dataset", fail_dataset) + with blob_remote_table(location=location) as table: + monkeypatch.setattr(table, "to_lance", fail_dataset) + query = table.search().select(["id", "image"]) + if blob_mode == "descriptions": + df = query.to_pandas(blob_mode=blob_mode) + assert df["id"].tolist() == [1, 2, 3] + assert "_rowid" not in df.columns + assert df["image"][0]["size"] == 5 + else: + with pytest.raises(NotImplementedError, match="stable table snapshot"): + query.to_pandas(blob_mode=blob_mode) + + @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) async def test_remote_fetch_blob_ranges(use_async): @@ -3534,7 +4059,7 @@ 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="remote tables"): + with pytest.raises(NotImplementedError, match="LanceDB Distributed"): await table.to_lance() diff --git a/python/python/tests/test_remote_options.py b/python/python/tests/test_remote_options.py new file mode 100644 index 000000000..0dbc21029 --- /dev/null +++ b/python/python/tests/test_remote_options.py @@ -0,0 +1,156 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import inspect +from urllib.parse import parse_qs, urlparse + +import lancedb +import pyarrow as pa +import pytest + +from test_remote_db import mock_lancedb_connection, mock_lancedb_connection_async + + +@pytest.mark.parametrize("uri", ["memory://", "db://dev"]) +def test_unknown_connect_options(uri): + with pytest.raises(ValueError, match="Unknown keyword arguments.*bogus"): + lancedb.connect(uri, api_key="fake", bogus=1) + + +@pytest.mark.parametrize("option", ["session", "manifest_enabled"]) +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.asyncio +async def test_remote_connect_rejects_local_options(option, asynchronous): + value = lancedb.Session() if option == "session" else True + with pytest.raises(NotImplementedError, match=option): + if asynchronous: + await lancedb.connect_async("db://dev", api_key="fake", **{option: value}) + else: + lancedb.connect("db://dev", api_key="fake", **{option: value}) + + +def test_remote_create_signature(): + from lancedb.db import DBConnection + from lancedb.remote.db import RemoteDBConnection + + expected = inspect.signature(DBConnection.create_table).parameters + actual = inspect.signature(RemoteDBConnection.create_table).parameters + assert list(actual) == list(expected) + for name in expected: + assert actual[name].kind == expected[name].kind + if name == "mode": + # Remote connections retain their existing server-default mode. + assert actual[name].default is None + else: + assert actual[name].default == expected[name].default + + +def test_remote_create_positional_mode(): + modes = [] + + def handler(request): + assert urlparse(request.path).path == "/v1/table/ct_pos/create/" + modes.append(parse_qs(urlparse(request.path).query)["mode"]) + request.send_response(200) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + data = [{"value": 1}] + db.create_table("ct_pos", data, None, "overwrite") + db.create_table("ct_pos", data, None, "overwrite") + db.create_table("ct_pos", data, None, "create", True) + with pytest.raises(ValueError, match="Invalid mode"): + db.create_table("ct_pos", data, None, "drop") + assert modes == [["overwrite"], ["overwrite"], ["exist_ok"]] + + +CREATE_OPTIONS = [ + {"new_table_data_storage_version": "2.0"}, + {"new_table_enable_v2_manifest_paths": "false"}, + {"bogus_option_xyz": "1"}, +] + + +@pytest.mark.parametrize("storage_options", CREATE_OPTIONS) +@pytest.mark.parametrize("empty", [False, True]) +@pytest.mark.asyncio +async def test_remote_create_rejects_write_options(storage_options, empty): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200) + request.end_headers() + + kwargs = {"schema": pa.schema([("value", pa.int64())])} + if not empty: + kwargs["data"] = [{"value": 1}] + async with mock_lancedb_connection_async(handler) as db: + with pytest.raises( + NotImplementedError, match="write_options.*LanceDB Distributed" + ): + await db.create_table("t", storage_options=storage_options, **kwargs) + assert requests == [] + + +@pytest.mark.parametrize( + "options", + [ + {"data_storage_version": "2.0"}, + {"enable_v2_manifest_paths": False}, + {"storage_options": {"x": "1"}}, + ], +) +def test_sync_remote_create_rejects_write_options(options): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + with pytest.raises(NotImplementedError, match="LanceDB Distributed"): + db.create_table("t", [{"value": 1}], **options) + assert requests == [] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "options", [{"index_cache_size": 10}, {"storage_options": {"x": "y"}}] +) +@pytest.mark.asyncio +async def test_remote_open_rejects_local_options(options, asynchronous): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200) + request.end_headers() + request.wfile.write(b'{"version": 1, "schema": {"fields": []}}') + + if asynchronous: + async with mock_lancedb_connection_async(handler) as db: + with pytest.raises(NotImplementedError, match="LanceDB Distributed"): + await db.open_table("t", **options) + else: + with mock_lancedb_connection(handler) as db: + with pytest.raises(NotImplementedError, match="LanceDB Distributed"): + db.open_table("t", **options) + assert requests == [] + + +@pytest.mark.asyncio +async def test_remote_open_rejects_location(): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200) + request.end_headers() + 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"): + await db.open_table("t", location="/tmp/zzz") + assert requests == [] diff --git a/python/python/tests/test_reranker_credentials.py b/python/python/tests/test_reranker_credentials.py new file mode 100644 index 000000000..c8f63a9ef --- /dev/null +++ b/python/python/tests/test_reranker_credentials.py @@ -0,0 +1,74 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import sys +import types + +import pytest + +from lancedb.rerankers import CohereReranker, VoyageAIReranker + +RERANKERS = [ + pytest.param("cohere", "COHERE_API_KEY", CohereReranker, {}, id="cohere"), + pytest.param( + "voyageai", + "VOYAGE_API_KEY", + VoyageAIReranker, + {"model_name": "rerank-2.5"}, + id="voyageai", + ), +] + + +def fake_sdk(monkeypatch, module_name): + """Replace the SDK module with one whose Client records the API key.""" + keys = [] + + def client(api_key=None): + keys.append(api_key) + return object() + + module = types.ModuleType(module_name) + module.Client = client + monkeypatch.setitem(sys.modules, module_name, module) + return keys + + +@pytest.mark.parametrize("module_name, env_var, reranker_cls, kwargs", RERANKERS) +@pytest.mark.parametrize( + "explicit_key, environment_key, expected_key", + [ + ("explicit-test-key", "environment-test-key", "explicit-test-key"), + ("explicit-test-key", None, "explicit-test-key"), + (None, "environment-test-key", "environment-test-key"), + ], +) +def test_reranker_api_key_precedence( + monkeypatch, + module_name, + env_var, + reranker_cls, + kwargs, + explicit_key, + environment_key, + expected_key, +): + keys = fake_sdk(monkeypatch, module_name) + if environment_key is None: + monkeypatch.delenv(env_var, raising=False) + else: + monkeypatch.setenv(env_var, environment_key) + + reranker_cls(api_key=explicit_key, **kwargs)._client + assert keys == [expected_key] + + +@pytest.mark.parametrize("module_name, env_var, reranker_cls, kwargs", RERANKERS) +def test_reranker_requires_api_key( + monkeypatch, module_name, env_var, reranker_cls, kwargs +): + keys = fake_sdk(monkeypatch, module_name) + monkeypatch.delenv(env_var, raising=False) + with pytest.raises(ValueError, match=f"{env_var} not set"): + reranker_cls(**kwargs)._client + assert keys == [] diff --git a/python/python/tests/test_rerankers.py b/python/python/tests/test_rerankers.py index 850b477a0..78b64613e 100644 --- a/python/python/tests/test_rerankers.py +++ b/python/python/tests/test_rerankers.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import os +from unittest.mock import MagicMock import random import lancedb @@ -427,6 +428,38 @@ def test_rrf_multivector_ranks_each_result_list(): assert result["_rowid"].to_pylist() == [2, 1, 3] +@pytest.mark.parametrize("reranker_cls", [RRFReranker, MRRReranker]) +def test_rank_fusion_return_score_all_keeps_both_scores(reranker_cls): + # A row found by both searches must keep its vector `_distance` and its FTS + # `_score` when the reranker is asked to return all scores. + vector_results = pa.table( + { + "_rowid": pa.array([1, 2], type=pa.uint64()), + "text": ["a", "b"], + "_distance": pa.array([0.1, 0.2], type=pa.float32()), + } + ) + fts_results = pa.table( + { + "_rowid": pa.array([2, 3], type=pa.uint64()), + "text": ["b", "c"], + "_score": pa.array([5.0, 4.0], type=pa.float32()), + } + ) + + result = reranker_cls(return_score="all").rerank_hybrid( + "query", vector_results, fts_results + ) + rows = {row["_rowid"]: row for row in result.to_pylist()} + + assert rows[1]["_distance"] == pytest.approx(0.1) + assert rows[1]["_score"] is None + assert rows[2]["_distance"] == pytest.approx(0.2) + assert rows[2]["_score"] == pytest.approx(5.0) + assert rows[3]["_distance"] is None + assert rows[3]["_score"] == pytest.approx(4.0) + + def test_rrf_reranker_distance(): data = pa.table( { @@ -547,6 +580,24 @@ def test_openai_reranker(tmp_path): _run_test_reranker(reranker, table, "single player experience", None, schema) +def test_openai_reranker_does_not_send_temperature(): + reranker = OpenaiReranker(api_key="test-key") + create = MagicMock() + create.return_value.choices = [ + MagicMock( + message=MagicMock( + content='{"documents": [{"content": "a", "relevance_score": 0.5}]}' + ) + ) + ] + reranker.__dict__["_client"] = MagicMock() + reranker.__dict__["_client"].chat.completions.create = create + + reranker._rerank(pa.table({"text": ["a"]}), "query") + + assert "temperature" not in create.call_args.kwargs + + @pytest.mark.skipif( os.environ.get("JINA_API_KEY") is None, reason="JINA_API_KEY not set" ) @@ -785,6 +836,154 @@ def test_empty_hybrid_result_reranker(): assert "_rowid" in result.column_names +@pytest.mark.parametrize("norm", ["score", "rank"]) +def test_hybrid_return_all_restores_original_scores(norm): + from lancedb.query import LanceHybridQueryBuilder + + vector_results = pa.table( + { + "text": ["a", "b", "c"], + "_rowid": pa.array([0, 1, 2], type=pa.uint64()), + "_distance": pa.array([0.5, 2.5, 10.0], type=pa.float32()), + } + ) + fts_results = pa.table( + { + "text": ["b", "a"], + "_rowid": pa.array([1, 0], type=pa.uint64()), + "_score": pa.array([3.25, 1.75], type=pa.float32()), + } + ) + + result = LanceHybridQueryBuilder._combine_hybrid_results( + fts_results=fts_results, + vector_results=vector_results, + norm=norm, + fts_query="query", + reranker=RRFReranker(return_score="all"), + limit=10, + with_row_ids=True, + ) + + # The raw distances and scores are returned, not the normalized values + # or ranks used for reranking. + rows = {row["_rowid"]: row for row in result.to_pylist()} + assert rows[0]["_distance"] == 0.5 + assert rows[1]["_distance"] == 2.5 + assert rows[2]["_distance"] == 10.0 + assert rows[0]["_score"] == 1.75 + assert rows[1]["_score"] == 3.25 + assert rows[2]["_score"] is None + + +@pytest.mark.parametrize("return_score", ["relevance", "all"]) +@pytest.mark.parametrize("first_row_id", [1, 2**63]) +@pytest.mark.parametrize("score_type", [pa.float32(), pa.float64()]) +def test_model_reranker_preserves_arrow_schema( + mocker, return_score, first_row_id, score_type +): + common_schema = pa.schema( + [ + pa.field("_rowid", pa.uint64()), + pa.field("text", pa.string()), + pa.field("vector", pa.list_(pa.float32(), 2)), + ], + metadata={b"source": b"reranker-test"}, + ) + vector_results = pa.Table.from_pylist( + [ + { + "_rowid": first_row_id, + "text": "vector", + "vector": [1, 0], + "_distance": 0.1, + }, + { + "_rowid": first_row_id + 1, + "text": "both", + "vector": [0, 1], + "_distance": 0.2, + }, + ], + schema=common_schema.append(pa.field("_distance", score_type)), + ) + fts_results = pa.Table.from_pylist( + [ + { + "_rowid": first_row_id + 1, + "text": "both", + "vector": [0, 1], + "_score": 0.9, + }, + { + "_rowid": first_row_id + 2, + "text": "fts", + "vector": [1, 1], + "_score": 0.8, + }, + ], + schema=common_schema.append(pa.field("_score", score_type)), + ) + reranker = CohereReranker(return_score=return_score) + reranker._client = mocker.Mock() + reranker._client.rerank.return_value.results = [ + mocker.Mock(index=index, relevance_score=score) + for index, score in [(2, 0.9), (1, 0.8), (0, 0.7)] + ] + + result = reranker.rerank_hybrid("query", vector_results, fts_results) + + assert result.select(common_schema.names).schema.equals( + common_schema, check_metadata=True + ) + assert result["_rowid"].to_pylist() == [ + first_row_id + 2, + first_row_id + 1, + first_row_id, + ] + assert result["text"].to_pylist() == ["fts", "both", "vector"] + if return_score == "all": + assert ( + result["_distance"] + .combine_chunks() + .equals(pa.array([None, 0.2, 0.1], type=score_type)) + ) + assert ( + result["_score"] + .combine_chunks() + .equals(pa.array([0.8, 0.9, None], type=score_type)) + ) + + +@pytest.mark.parametrize("return_score", ["relevance", "all"]) +def test_model_reranker_empty_results_preserve_schema(mocker, return_score): + common_schema = pa.schema( + [ + ("_rowid", pa.uint64()), + ("text", pa.string()), + ("vector", pa.list_(pa.float32(), 2)), + ], + metadata={b"source": b"reranker-test"}, + ) + vector_results = pa.Table.from_pylist( + [], schema=common_schema.append(pa.field("_distance", pa.float32())) + ) + fts_results = pa.Table.from_pylist( + [], schema=common_schema.append(pa.field("_score", pa.float32())) + ) + reranker = CohereReranker(return_score=return_score) + reranker._client = mocker.Mock() + + result = reranker.rerank_hybrid("query", vector_results, fts_results) + + assert len(result) == 0 + assert result.select(common_schema.names).schema.equals( + common_schema, check_metadata=True + ) + assert result.schema.field("_relevance_score").type == pa.float32() + reranker._client.rerank.assert_not_called() + + def test_cross_encoder_reranker_return_all(tmp_path): pytest.importorskip("sentence_transformers") reranker = CrossEncoderReranker(return_score="all") diff --git a/python/python/tests/test_session.py b/python/python/tests/test_session.py index 8923477c7..d0bc54210 100644 --- a/python/python/tests/test_session.py +++ b/python/python/tests/test_session.py @@ -36,3 +36,13 @@ def test_session_cache_configuration(tmp_path): assert final_cache_size > initial_cache_size # Cache should have grown assert final_cache_items >= initial_cache_items # Items should not decrease assert initial_cache_size < index_cache_size + metadata_cache_size + + +def test_connection_session_returns_supplied_session(tmp_path): + """Sync connections must expose the session they were opened with.""" + db = lancedb.connect(tmp_path) + assert db.session is None + + session = lancedb.Session() + db = lancedb.connect(tmp_path, session=session) + assert db.session is session diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py index e6f5fd3c7..539b88647 100644 --- a/python/python/tests/test_sql.py +++ b/python/python/tests/test_sql.py @@ -137,9 +137,23 @@ async def test_async_namespace_connection_rejects_sql(tmp_path): await connection.describe_query(NIL_QUERY_ID) -def test_describe_query_requires_uuid(): - with pytest.raises(TypeError, match="UUID"): - remote_connection().describe_query(str(NIL_QUERY_ID)) +@pytest.mark.asyncio +@pytest.mark.parametrize("identity", [NIL_QUERY_ID, str(NIL_QUERY_ID)]) +async def test_describe_query_accepts_uuid_and_job_id_string(identity): + calls = [] + + class NativeConnection: + async def describe_query(self, query_id): + calls.append(query_id) + + connection = AsyncConnection(NativeConnection()) + await connection.describe_query(identity) + assert calls == [NIL_QUERY_ID] + + +def test_describe_query_rejects_registry_job_id(): + with pytest.raises(ValueError, match="UUID"): + remote_connection().describe_query("registry-job-id") @pytest.mark.parametrize( diff --git a/python/python/tests/test_sync_api_parity.py b/python/python/tests/test_sync_api_parity.py new file mode 100644 index 000000000..a12efd0c9 --- /dev/null +++ b/python/python/tests/test_sync_api_parity.py @@ -0,0 +1,170 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import timedelta +import json +from urllib.parse import parse_qs, urlparse + +import lancedb +from lancedb.table import Table +import pytest + +from test_remote_db import mock_lancedb_connection + + +@pytest.fixture +def legacy_table(): + """Implement the pre-existing abstract API without the two new members.""" + + def unsupported(self, *args, **kwargs): + raise NotImplementedError + + def update_field_metadata(self, updates): + self.metadata_updates.append(updates) + return object() # The deprecated wrapper must not expose this result. + + # Supply concrete implementations through normal ABC class creation. Leave + # namespace and replace_field_metadata inherited, as an old subclass would. + implementations = { + name: unsupported + for name in Table.__abstractmethods__ + if name not in {"namespace", "replace_field_metadata"} + } + implementations.update( + name=property(lambda self: "legacy"), + update_field_metadata=update_field_metadata, + ) + legacy_class = type("LegacyTable", (Table,), implementations) + table = legacy_class() + table.metadata_updates = [] + return table + + +def test_legacy_table_namespace_and_id(legacy_table): + assert legacy_table.namespace == [] + assert legacy_table.id == "legacy" + namespace = legacy_table.namespace + namespace.append("changed") + assert legacy_table.namespace == [] + assert legacy_table.id == "legacy" + + +def test_legacy_table_replace_field_metadata(legacy_table): + with pytest.warns(DeprecationWarning, match="update_field_metadata"): + result = legacy_table.replace_field_metadata("nested.field", {"a": "b"}) + assert result is None + assert legacy_table.metadata_updates == [ + {"path": "nested.field", "metadata": {"a": "b"}, "replace": True} + ] + + +def respond(request, body): + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(body).encode()) + + +def test_remote_uri(): + with mock_lancedb_connection(lambda request: respond(request, {})) as db: + assert db.uri == "db://dev" + + +@pytest.mark.parametrize("attribute", ["session", "read_consistency_interval"]) +def test_remote_unsupported_properties(attribute): + with mock_lancedb_connection(lambda request: respond(request, {})) as db: + with pytest.raises(NotImplementedError, match=attribute): + getattr(db, attribute) + + +@pytest.mark.parametrize("tables", [[], ["first", "last"]]) +def test_remote_len_and_contains_follow_pages(tables): + requests = [] + + def handler(request): + requests.append(request.path) + query = parse_qs(urlparse(request.path).query) + if tables and "page_token" not in query: + respond(request, {"tables": [tables[0]], "page_token": "opaque-next"}) + else: + if tables: + assert query["page_token"] == ["opaque-next"] + respond(request, {"tables": tables[1:]}) + + with mock_lancedb_connection(handler) as db: + assert len(db) == len(tables) + assert ("last" in db) == bool(tables) + assert "missing" not in db + requests.clear() + assert ("first" in db) == bool(tables) + assert len(requests) == 1 + + +@pytest.mark.parametrize("namespace", [[], ["parent", "child"]]) +def test_remote_table_identifiers(namespace): + def handler(request): + respond(request, {"version": 1, "schema": {"fields": []}}) + + with mock_lancedb_connection(handler) as db: + table = db.open_table("rfm", namespace_path=namespace) + assert table.namespace == namespace + assert table.id == "$".join(namespace + ["rfm"]) + + +def test_remote_replace_field_metadata(): + updates = [] + + def handler(request): + if request.path.endswith("/describe/"): + respond(request, {"version": 1, "schema": {"fields": []}}) + else: + assert request.path == "/v1/table/rfm/update_field_metadata/" + body = request.rfile.read(int(request.headers["Content-Length"])) + updates.append(json.loads(body)) + respond(request, {"version": 2}) + + with mock_lancedb_connection(handler) as db: + table = db.open_table("rfm") + with pytest.warns(DeprecationWarning, match="update_field_metadata"): + assert table.replace_field_metadata("id", {"a": "b"}) is None + assert updates == [ + {"updates": [{"path": "id", "metadata": {"a": "b"}, "replace": True}]} + ] + + +@pytest.mark.parametrize("custom_session", [False, True]) +def test_local_properties_and_metadata(tmp_path, custom_session): + supplied = lancedb.Session() if custom_session else None + db = lancedb.connect( + tmp_path, session=supplied, read_consistency_interval=timedelta(seconds=5) + ) + session = db.session + assert session is supplied + before = session.size_bytes if session is not None else 0 + table = db.create_table("rfm", [{"id": i} for i in range(3)]) + assert table.to_arrow().num_rows == 3 + if supplied is not None: + assert supplied.size_bytes > before + assert db.read_consistency_interval == timedelta(seconds=5) + assert table.namespace == [] + assert table.id == "rfm" + with pytest.warns(DeprecationWarning): + table.replace_field_metadata("id", {"old": "value"}) + with pytest.warns(DeprecationWarning): + table.replace_field_metadata("id", {"a": "b"}) + assert table.schema.field("id").metadata == {b"a": b"b"} + + +def test_namespace_connection_properties_remain_writable(tmp_path): + session = lancedb.Session() + interval = timedelta(seconds=5) + with lancedb.connect_namespace( + "dir", + {"root": str(tmp_path)}, + session=session, + read_consistency_interval=interval, + ) as db: + assert db.session is session + assert db.read_consistency_interval == interval + db.read_consistency_interval = timedelta(0) + assert db.read_consistency_interval == timedelta(0) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 7ec2003b7..f4efb1787 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -14,8 +14,8 @@ from concurrent.futures import ThreadPoolExecutor from datetime import date, datetime, timedelta from decimal import Decimal, localcontext from time import sleep -from typing import List -from unittest.mock import patch +from typing import Any, List +from unittest.mock import MagicMock, patch import lancedb from lancedb import table as table_module @@ -59,6 +59,124 @@ def _blob_v2_table(db: DBConnection, name: str): return table +@pytest.mark.parametrize( + "threshold", + [ + "inline_size_threshold", + "dedicated_size_threshold", + "pack_file_size_threshold", + ], +) +@pytest.mark.parametrize( + "value,error", + [ + (-1, ValueError), + (True, TypeError), + (False, TypeError), + (1.5, TypeError), + ("8192", TypeError), + (ctypes.c_size_t(-1).value + 1, OverflowError), + ], +) +def test_blob_thresholds_reject_invalid_values(threshold, value, error): + # Also runs in CI with pylance actually uninstalled. + with pytest.raises(error, match=f"{threshold} must"): + lancedb.blob("blob", **{threshold: value}) + + +@pytest.mark.parametrize( + "threshold", ["dedicated_size_threshold", "pack_file_size_threshold"] +) +def test_blob_thresholds_reject_zero_for_positive_thresholds(threshold): + with pytest.raises(ValueError, match=f"{threshold} must be positive"): + lancedb.blob("blob", **{threshold: 0}) + + +def test_blob_thresholds_accept_integer_boundaries(): + maximum = ctypes.c_size_t(-1).value + field = lancedb.blob( + "blob", + nullable=False, + inline_size_threshold=0, + dedicated_size_threshold=maximum, + pack_file_size_threshold=maximum, + ) + assert not field.nullable + assert field.metadata == { + b"lance-encoding:blob-inline-size-threshold": b"0", + b"lance-encoding:blob-dedicated-size-threshold": str(maximum).encode(), + b"lance-encoding:blob-pack-file-size-threshold": str(maximum).encode(), + } + + +def test_blob_thresholds_control_writes_after_reopen(tmp_path): + # Keep this in test_table.py: CI runs it without pylance or pandas installed. + field = lancedb.blob( + "blob", + inline_size_threshold=4, + dedicated_size_threshold=12, + pack_file_size_threshold=8, + ) + metadata = { + b"lance-encoding:blob-inline-size-threshold": b"4", + b"lance-encoding:blob-dedicated-size-threshold": b"12", + b"lance-encoding:blob-pack-file-size-threshold": b"8", + } + assert field.metadata == metadata + schema = pa.schema([pa.field("id", pa.int64()), field]) + db = lancedb.connect(tmp_path) + table = db.create_table("blobs", schema=schema) + # Every payload fits in the default inline tier; custom thresholds must + # instead send the larger values to packed and dedicated storage. + rows = [ + {"id": 0, "blob": b"a" * 2}, + {"id": 1, "blob": b"b" * 8}, + {"id": 2, "blob": b"c" * 16}, + {"id": 3, "blob": b"d" * 8}, + ] + + def check_writes(table, expected): + assert table.schema.field("blob").metadata.items() >= metadata.items() + hits = table.search().with_row_id(True).limit(10).to_arrow() + actual = {row["id"]: row for row in hits.to_pylist()} + assert actual.keys() == {row["id"] for row in expected} + for row in expected: + size = len(row["blob"]) + descriptor = actual[row["id"]]["blob"] + assert descriptor["size"] == size + assert descriptor["kind"] == (2 if size > 12 else 1 if size > 4 else 0) + row_ids = [actual[row["id"]]["_rowid"] for row in expected] + assert table.fetch_blobs("blob", row_ids).to_pylist() == [ + row["blob"] for row in expected + ] + # Two packed values reach the configured sidecar limit independently. + packed = [ + actual[row["id"]]["blob"] for row in expected if len(row["blob"]) == 8 + ] + assert len({desc["blob_id"] for desc in packed}) == len(packed) + + table.add(rows) + check_writes(table, rows) + table = lancedb.connect(tmp_path).open_table("blobs") + check_writes(table, rows) + updates = [ + {"id": 0, "blob": b"e" * 16}, + {"id": 1, "blob": b"f" * 2}, + {"id": 2, "blob": b"g" * 8}, + {"id": 3, "blob": b"h" * 8}, + {"id": 4, "blob": b"i" * 16}, + ] + result = ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(updates) + ) + assert result.num_updated_rows == 4 + assert result.num_inserted_rows == 1 + check_writes(lancedb.connect(tmp_path).open_table("blobs"), updates) + + async def _blob_v2_table_async(db: AsyncConnection, name: str): schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("blob")]) table = await db.create_table(name, schema=schema) @@ -280,6 +398,30 @@ def test_create_table_infers_large_int_vectors(mem_db: DBConnection): assert vector_column.to_pylist() == [[0.0, 300.0]] +def test_create_table_all_null_vector_column(mem_db: DBConnection): + # A vector column can legitimately arrive with every value null, e.g. when + # the embeddings have not been computed yet. The dimension is unknowable in + # that case, so schema inference must not crash and should leave the column + # as a variable-length list rather than a fixed-size one. + data = pa.table( + { + "id": pa.array([1, 2]), + "vector": pa.array([None, None], type=pa.list_(pa.float32())), + } + ) + + table = mem_db.create_table("all_null_vector", data=data) + + vector_field = table.schema.field("vector") + assert pa.types.is_list(vector_field.type) + assert vector_field.type.value_type == pa.float32() + + result = table.to_arrow() + assert result.num_rows == 2 + assert result.column("vector").to_pylist() == [None, None] + assert table.count_rows() == 2 + + @pytest.mark.asyncio async def test_create_table_async_infers_large_int_vectors( mem_db_async: AsyncConnection, @@ -518,6 +660,30 @@ def test_add(mem_db: DBConnection): _add(table, schema) +def test_add_from_iterator_that_queries_table(mem_db: DBConnection): + source = mem_db.create_table("source", data=pa.table({"id": range(16)})) + target = mem_db.create_table("target", schema=source.schema) + + def batches(): + for _ in range(5): + yield source.search().limit(10).to_arrow() + + target.add(batches()) + + assert target.count_rows() == 50 + + +def test_create_table_from_iterator_that_queries_table(mem_db: DBConnection): + source = mem_db.create_table("source", data=pa.table({"id": range(16)})) + + def batches(): + yield source.search().limit(10).to_arrow() + + target = mem_db.create_table("target", data=batches()) + + assert target.count_rows() == 10 + + def test_add_releases_arrow_buffers_without_gc(mem_db: DBConnection): """Regression test for https://github.com/lancedb/lancedb/issues/2512.""" schema = pa.schema([pa.field("x", pa.int64())]) @@ -1251,6 +1417,7 @@ def test_branches_preserve_namespace(tmp_path): "lance" ) # namespace_path routes through lance's DirectoryNamespace db = lancedb.connect(tmp_path) + db.create_namespace(["ns1"]) table = db.create_table("t", [{"id": 1}], namespace_path=["ns1"]) assert table.namespace == ["ns1"] @@ -1585,6 +1752,47 @@ def test_create_index_async_returns_done_job(mem_db: DBConnection): job.cancel() +@pytest.mark.parametrize( + "rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}] +) +@patch("lancedb.table.LanceTable.to_lance") +def test_create_ivfrq_index_accelerator(mock_to_lance, mem_db: DBConnection, rq_kwargs): + from lancedb.index import IvfRq + + table = mem_db.create_table("test", [{"vector": [1.0] * 8}]) + torch = MagicMock() + torch.cuda.is_available.return_value = True + with patch.dict(sys.modules, {"torch": torch}): + table.create_index("vector", config=IvfRq(accelerator="cuda", **rq_kwargs)) + + kwargs = mock_to_lance.return_value.create_index.call_args.kwargs + assert kwargs["index_type"] == "IVF_RQ" + assert kwargs["accelerator"] == "cuda" + if rq_kwargs.get("num_bits") is None: + assert "num_bits" not in kwargs + else: + assert kwargs["num_bits"] == rq_kwargs["num_bits"] + + +@pytest.mark.parametrize("method", ["create_index", "create_index_async"]) +@pytest.mark.parametrize("wait_timeout", ["invalid", 1, []]) +def test_create_index_invalid_wait_timeout(mem_db: DBConnection, method, wait_timeout): + table = mem_db.create_table("invalid_timeout", [{"id": 1}]) + with pytest.raises(TypeError): + getattr(table, method)("id", config=BTree(), wait_timeout=wait_timeout) + assert table.list_indices() == [] + + +@pytest.mark.parametrize("method", ["create_index", "create_index_async"]) +@pytest.mark.parametrize("wait_timeout", [None, timedelta(seconds=1)]) +def test_create_index_valid_wait_timeout(mem_db: DBConnection, method, wait_timeout): + table = mem_db.create_table("valid_timeout", [{"id": 1}]) + result = getattr(table, method)("id", config=BTree(), wait_timeout=wait_timeout) + if result is not None: + result.wait() + assert len(table.list_indices()) == 1 + + @patch("lancedb.table.AsyncTable.create_index") def test_create_index_method(mock_create_index, mem_db: DBConnection): table = mem_db.create_table( @@ -1725,6 +1933,51 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): ) +@pytest.mark.parametrize("api", ["legacy", "unified"]) +@pytest.mark.parametrize("cuda_failure", ["unavailable", "init_error"]) +def test_create_index_cuda_failure_suggests_cpu( + api, cuda_failure, mem_db: DBConnection +): + table = mem_db.create_table( + f"test_cuda_unavailable_{api}", + data=[{"vector": [3.1, 4.1]}, {"vector": [5.9, 26.5]}], + ) + torch = MagicMock() + torch.cuda.is_available.return_value = cuda_failure == "init_error" + if cuda_failure == "init_error": + torch.cuda.init.side_effect = RuntimeError("CUDA driver initialization failed") + + with ( + patch.dict(sys.modules, {"torch": torch}), + patch.object(table, "to_lance") as to_lance, + ): + if api == "legacy": + with ( + pytest.warns(DeprecationWarning, match="create_index"), + pytest.raises(RuntimeError, match="accelerator=None.*CPU"), + ): + table.create_index( + metric="dot", + num_partitions=1, + num_sub_vectors=1, + vector_column_name="vector", + accelerator="cuda", + ) + else: + with pytest.raises(RuntimeError, match="accelerator=None.*CPU"): + table.create_index( + "vector", + config=IvfPq( + distance_type="dot", + num_partitions=1, + num_sub_vectors=1, + accelerator="cuda", + ), + ) + + to_lance.return_value.create_index.assert_not_called() + + @patch("lancedb.table.AsyncTable.create_index") def test_create_index_name_and_train_parameters( mock_create_index, mem_db: DBConnection @@ -1940,6 +2193,71 @@ def test_add_with_nans(mem_db: DBConnection): assert np.allclose(filled_vectors[22.0], np.array([5.0, 0.0])) +@pytest.mark.parametrize("operation", ["create", "append", "overwrite"]) +@pytest.mark.parametrize("input_type", ["pandas", "rows", "arrow"]) +@pytest.mark.parametrize("on_bad_vectors", [None, "error", "drop", "fill", "null"]) +def test_write_vectors_with_null_elements( + mem_db: DBConnection, operation, input_type, on_bad_vectors +): + schema = pa.schema({"vector": pa.list_(pa.float32(), 2), "id": pa.int64()}) + vectors = [[3.0, 4.0], [np.nan, 1.0], [np.nan, np.nan]] + if input_type == "pandas": + pd = pytest.importorskip("pandas") + + data = pd.DataFrame( + { + "vector": [np.array(v, dtype=np.float32) for v in vectors], + "id": [0, 1, 2], + } + ) + else: + # Pandas turns the NaNs above into null child elements. Explicit nulls + # in other input formats must follow the same bad-vector policy. + data = [ + {"vector": [3.0, 4.0], "id": 0}, + {"vector": [None, 1.0], "id": 1}, + {"vector": [None, None], "id": 2}, + ] + if input_type == "arrow": + data = pa.Table.from_pylist(data, schema=schema) + + options = {} if on_bad_vectors is None else {"on_bad_vectors": on_bad_vectors} + if on_bad_vectors == "fill": + options["fill_value"] = 42.0 + + table = None + if operation != "create": + table = mem_db.create_table("test", schema=schema) + + def write(): + if operation == "create": + return mem_db.create_table("test", data=data, schema=schema, **options) + table.add(data, mode=operation, **options) + return table + + if on_bad_vectors in (None, "error"): + # Create/overwrite can wrap errors from lazy Arrow readers in RuntimeError. + expected_error = ( + ValueError if operation == "append" else (ValueError, RuntimeError) + ) + with pytest.raises(expected_error, match="NaN|null"): + write() + if table is not None: + assert table.count_rows() == 0 + return + + table = write() + if on_bad_vectors == "drop": + expected = [{"vector": [3.0, 4.0], "id": 0}] + else: + expected = [ + {"vector": [3.0, 4.0], "id": 0}, + {"vector": [42.0, 1.0] if on_bad_vectors == "fill" else None, "id": 1}, + {"vector": [42.0, 42.0] if on_bad_vectors == "fill" else None, "id": 2}, + ] + assert table.to_arrow().to_pylist() == expected + + def test_add_with_empty_fixed_size_list_drops_bad_rows(mem_db: DBConnection): class Schema(LanceModel): text: str @@ -2612,6 +2930,57 @@ def test_update_with_arrow_scalar(mem_db: DBConnection): assert table.to_arrow()["vector"].to_pylist() == [[1.0, 2.0, 3.0, 4.0]] +@pytest.mark.asyncio +@pytest.mark.parametrize("async_api", [False, True]) +@pytest.mark.parametrize("entries", [[("o'brien", 4), ("nil", None)], [], None]) +async def test_update_map_arrow_scalar(tmp_path, async_api, entries): + map_type = pa.map_(pa.string(), pa.int64()) + data = pa.table( + { + "id": [1, 2], + "attrs": pa.array([[("original", 1)], entries], type=map_type), + } + ) + if async_api: + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("maps", data) + source = await table.query().where("id = 2").to_arrow() + result = await table.update({"attrs": source["attrs"][0]}, where="id = 1") + actual = await table.query().to_arrow() + else: + db = lancedb.connect(tmp_path) + table = db.create_table("maps", data) + source = table.search().where("id = 2").to_arrow() + result = table.update(values={"attrs": source["attrs"][0]}, where="id = 1") + actual = table.to_arrow() + assert result.rows_updated == 1 + assert actual.schema.field("attrs").type == map_type + assert actual.sort_by("id")["attrs"].to_pylist() == [entries, entries] + + +@pytest.mark.parametrize( + "map_type, entries", + [ + (pa.map_(pa.int64(), pa.string()), []), + ( + pa.map_(pa.string(), pa.map_(pa.string(), pa.int64())), + [("outer", [("inner", 3)]), ("null", None)], + ), + ], +) +def test_update_typed_map_arrow_scalar(mem_db: DBConnection, map_type, entries): + table = mem_db.create_table( + "maps", + pa.table({"id": [1, 2], "attrs": pa.array([None, entries], type=map_type)}), + ) + scalar = table.search().where("id = 2").to_arrow()["attrs"][0] + result = table.update(values={"attrs": scalar}, where="id = 1") + actual = table.to_arrow().sort_by("id")["attrs"] + assert result.rows_updated == 1 + assert actual.type == map_type + assert actual.to_pylist() == [entries, entries] + + @pytest.mark.parametrize("use_arrow_scalar", [False, True]) @pytest.mark.parametrize( "decimal_type, value", @@ -3597,26 +3966,42 @@ def test_create_f16_table_from_arrow_data(mem_db: DBConnection): assert "s-2" in expected["text"].to_pylist() -def test_create_f16_table(mem_db: DBConnection): +@pytest.mark.parametrize("accelerator", [None, "cuda"]) +def test_create_f16_table(tmp_path, accelerator): + if accelerator == "cuda": + torch = pytest.importorskip("torch") + if not torch.cuda.is_available(): + pytest.skip("CUDA not available") + class MyTable(LanceModel): text: str vector: Vector(32, value_type=pa.float16()) rng = np.random.default_rng(42) + vectors = rng.standard_normal((512, 32)).astype(np.float16) df = pa.table( { "text": [f"s-{i}" for i in range(512)], - "vector": [rng.standard_normal(32).astype(np.float16) for _ in range(512)], + "vector": list(vectors), } ) - table = mem_db.create_table( + db = lancedb.connect(tmp_path) + table = db.create_table( "f16_tbl", schema=MyTable, ) table.add(df) - table.create_index(num_partitions=2, num_sub_vectors=2) + table.create_index( + "vector", + config=IvfPq( + num_partitions=2, + num_sub_vectors=2, + accelerator=accelerator, + ), + ) - query = df["vector"][2].as_py() + # Match the issue's float64 query against an explicitly typed float16 column. + query = vectors[2].astype(np.float64) expected = table.search(query).limit(2).to_arrow() assert "s-2" in expected["text"].to_pylist() @@ -3673,6 +4058,42 @@ def test_multiple_vector_columns(mem_db: DBConnection): assert result1["text"][0] != result2["text"][0] +@pytest.mark.parametrize( + "query", + [ + (0.0, 0.0), + pa.array([0.0, 0.0]), + pa.chunked_array([[0.0], [0.0]]), + ], +) +@pytest.mark.parametrize("query_type", ["auto", "vector"]) +def test_sync_search_accepts_supported_vector_containers( + mem_db: DBConnection, query, query_type +): + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("small", pa.list_(pa.float32(), 2)), + pa.field("large", pa.list_(pa.float32(), 3)), + ] + ) + table = mem_db.create_table( + "supported_vector_containers", + data=pa.table( + { + "id": [1, 2], + "small": [[0.0, 0.0], [1.0, 1.0]], + "large": [[1.0, 1.0, 1.0], [0.0, 0.0, 0.0]], + }, + schema=schema, + ), + ) + + result = table.search(query, query_type=query_type).limit(1).to_arrow() + + assert result["id"].to_pylist() == [1] + + def test_create_scalar_index(mem_db: DBConnection): vec_array = pa.array( [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]], pa.list_(pa.float32(), 2) @@ -4378,6 +4799,58 @@ async def test_alter_columns_rejects_invalid_async( assert await table.schema() == initial_schema +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("list_type", [pa.list_, pa.large_list]) +@pytest.mark.parametrize( + "value_type, values, inferred_type", + [ + (pa.float64(), [1.25, 2.5], pa.float32()), + (pa.int32(), [0, 255], pa.uint8()), + (pa.int32(), [-1, 256], pa.float32()), + ], +) +async def test_inferred_vector_field_metadata( + tmp_db: DBConnection, + tmp_db_async: AsyncConnection, + asynchronous, + list_type, + value_type, + values, + inferred_type, +): + metadata = { + "lancedb:description": "Embedding values", + "lancedb:tag:model": "test-model", + } + schema = pa.schema( + [ + pa.field( + "vector", list_type(value_type), nullable=False, metadata=metadata + ), + pa.field("text", pa.string(), metadata={"description": "Source text"}), + ], + metadata={"description": "Source dataset"}, + ) + rows = [{"vector": values, "text": "first"}, {"vector": values, "text": "second"}] + data = pa.Table.from_pylist(rows, schema=schema) + if asynchronous: + await tmp_db_async.create_table("vector_metadata", data=data) + table = await tmp_db_async.open_table("vector_metadata") + actual_schema = await table.schema() + actual_data = await table.to_arrow() + else: + tmp_db.create_table("vector_metadata", data=data) + table = tmp_db.open_table("vector_metadata") + actual_schema = table.schema + actual_data = table.to_arrow() + expected_schema = schema.set( + 0, schema.field("vector").with_type(pa.list_(inferred_type, 2)) + ) + assert actual_schema.equals(expected_schema, check_metadata=True) + assert actual_data.to_pylist() == rows + + def test_update_field_metadata(mem_db: DBConnection): data = pa.table({"id": [0, 1], "category": ["a", "b"]}) table = mem_db.create_table("my_table", data=data) @@ -4542,6 +5015,134 @@ async def test_optimize(mem_db_async: AsyncConnection): assert await table.query().to_arrow() == pa.table({"x": [[1], [2]]}) +@pytest.mark.asyncio +async def test_optimize_compaction_options(mem_db_async: AsyncConnection): + table = await mem_db_async.create_table("test", data=[{"x": 1}]) + await table.add([{"x": 2}]) + + stats = await table.optimize( + compaction_options={ + "target_rows_per_fragment": 1, + "batch_size": 1, + "num_threads": 1, + } + ) + assert stats.compaction.fragments_removed == 0 + assert stats.compaction.fragments_added == 0 + + stats = await table.optimize(compaction_options={"target_rows_per_fragment": 3}) + assert stats.compaction.fragments_removed == 2 + assert stats.compaction.fragments_added == 1 + + with pytest.raises(ValueError, match="Invalid compaction option: unknown"): + await table.optimize(compaction_options={"unknown": 1}) + + +def test_optimize_compaction_options_sync(mem_db: DBConnection): + table = mem_db.create_table("test", data=[{"x": 1}]) + with pytest.raises(ValueError, match="target_rows_per_fragment must be between"): + table.optimize(compaction_options={"target_rows_per_fragment": 0}) + + +@pytest.mark.parametrize("option", ["max_source_rows", "max_source_bytes"]) +@pytest.mark.asyncio +async def test_optimize_compaction_source_limits( + mem_db_async: AsyncConnection, option: str +): + table = await mem_db_async.create_table("test", data=[{"x": 1}]) + await table.add([{"x": 2}]) + + stats = await table.optimize( + compaction_options={ + "target_rows_per_fragment": 3, + option: 1, + } + ) + assert stats.compaction.fragments_removed == 0 + assert stats.compaction.fragments_added == 0 + + +@pytest.mark.asyncio +async def test_optimize_compaction_data_storage_version( + mem_db_async: AsyncConnection, +): + table = await mem_db_async.create_table("test", data=[{"x": 1}]) + await table.add([{"x": 2}]) + + stats = await table.optimize( + compaction_options={ + "target_rows_per_fragment": 3, + "data_storage_version": "2.2", + } + ) + assert stats.compaction.fragments_removed == 2 + assert stats.compaction.fragments_added == 1 + + table = await mem_db_async.create_table("cross_family", data=[{"x": 1}]) + await table.add([{"x": 2}]) + with pytest.raises(ValueError, match="V1 and V2 storage versions cannot be mixed"): + await table.optimize( + compaction_options={ + "target_rows_per_fragment": 3, + "data_storage_version": "legacy", + } + ) + + +@pytest.mark.asyncio +async def test_optimize_compaction_excluded_fragments(mem_db_async: AsyncConnection): + table = await mem_db_async.create_table("test", data=[{"x": 1}]) + await table.add([{"x": 2}]) + + stats = await table.optimize( + compaction_options={ + "target_rows_per_fragment": 3, + "excluded_fragment_ids": [0], + } + ) + assert stats.compaction.fragments_removed == 0 + assert stats.compaction.fragments_added == 0 + + stats = await table.optimize(compaction_options={"target_rows_per_fragment": 3}) + assert stats.compaction.fragments_removed == 2 + assert stats.compaction.fragments_added == 1 + + +@pytest.mark.parametrize( + ("option", "value", "message"), + [ + ("target_rows_per_fragment", 0, "must be between 1 and 4294967295"), + ("max_rows_per_group", 0, "must be between 1 and 4294967295"), + ("batch_size", 0, "must be between 1 and 4294967295"), + ("num_threads", 0, "must be greater than 0"), + ("target_rows_per_fragment", 2**32, "must be between 1 and 4294967295"), + ("max_rows_per_group", 2**32, "must be between 1 and 4294967295"), + ("batch_size", 2**32, "must be between 1 and 4294967295"), + ("io_buffer_size", 2**63, "must be at most 9223372036854775807"), + ("max_source_rows", 0, "must be greater than 0"), + ("max_source_bytes", 0, "must be greater than 0"), + ("data_storage_version", "invalid", "Unknown Lance storage version: invalid"), + ( + "excluded_fragment_ids", + [-1], + "must contain values between 0 and 4294967295", + ), + ( + "excluded_fragment_ids", + [2**32], + "must contain values between 0 and 4294967295", + ), + ], +) +@pytest.mark.asyncio +async def test_optimize_compaction_options_validation( + mem_db_async: AsyncConnection, option: str, value: Any, message: str +): + table = await mem_db_async.create_table("test", data=[{"x": 1}]) + with pytest.raises(ValueError, match=message): + await table.optimize(compaction_options={option: value}) + + @pytest.mark.asyncio async def test_optimize_delete_unverified(tmp_db_async: AsyncConnection, tmp_path): table = await tmp_db_async.create_table( @@ -4592,6 +5193,57 @@ def test_optimize_warns_on_zero_cleanup_sync(mem_db: DBConnection): assert all("concurrent" in str(w.message) for w in seen) +def test_optimize_retains_tagged_versions(tmp_db: DBConnection): + # A tagged version older than the cleanup cutoff must be retained, not make + # optimize() fail part-way (after compaction, before the index step). + table = tmp_db.create_table( + "test", data=pa.table({"id": list(range(100)), "text": ["a"] * 100}) + ) + table.create_index("id", config=BTree()) + table.tags.create("release-1", table.version) + tagged_version = table.version + for i in range(3): + table.add(pa.table({"id": [1000 + i], "text": ["new"]})) + assert table.stats()["fragment_stats"]["num_fragments"] == 4 + assert table.index_stats("id_idx").num_unindexed_rows == 3 + sleep(1.1) + + table.optimize(cleanup_older_than=timedelta(seconds=1)) + + # The index step ran after the prune step + assert table.index_stats("id_idx").num_unindexed_rows == 0 + # It stays optimizable + table.optimize(cleanup_older_than=timedelta(seconds=1)) + assert table.stats()["fragment_stats"]["num_fragments"] == 1 + + # Untagged old versions were pruned, the tagged one was retained + versions = [v["version"] for v in table.list_versions()] + assert tagged_version in versions + for added in range(tagged_version + 1, tagged_version + 4): + assert added not in versions + assert len(table) == 103 + + table.checkout("release-1") + assert len(table) == 100 + assert table.to_arrow().num_rows == 100 + + +@pytest.mark.asyncio +async def test_optimize_retains_tagged_versions_async(tmp_db_async: AsyncConnection): + table = await tmp_db_async.create_table("test", data=[{"x": [1]}]) + await table.tags.create("keep", await table.version()) + await table.add(data=[{"x": [2]}]) + await table.add(data=[{"x": [3]}]) + sleep(1.1) + + stats = await table.optimize(cleanup_older_than=timedelta(seconds=1)) + assert stats.prune.old_versions_removed >= 1 + + await table.checkout("keep") + assert await table.count_rows() == 1 + assert await table.query().to_arrow() == pa.table({"x": [[1]]}) + + def test_replace_field_metadata(tmp_path): db = lancedb.connect(tmp_path) table = db.create_table("my_table", data=[{"x": 0}]) @@ -4647,6 +5299,81 @@ def test_stats(mem_db: DBConnection): assert stats_with_index["fragment_stats"]["num_fragments"] == 1 +@pytest.mark.parametrize("iterable_type", [iter, tuple]) +@pytest.mark.parametrize("empty", [False, True]) +@pytest.mark.parametrize("with_schema", [False, True]) +def test_create_table_recordbatch_iterable( + mem_db: DBConnection, iterable_type, empty, with_schema +): + schema = pa.schema([pa.field("id", pa.int64())]) + batches = [] if empty else [pa.RecordBatch.from_pydict({"id": [1]}, schema)] + data = iterable_type(batches) + if empty and not with_schema: + with pytest.raises(ValueError, match="empty iterable without a schema"): + mem_db.create_table("test", data=data) + return + + table = mem_db.create_table( + "test", data=data, schema=schema if with_schema else None + ) + assert table.schema == schema + assert table.to_arrow().to_pylist() == ([] if empty else [{"id": 1}]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("iterable_type", [iter, tuple]) +@pytest.mark.parametrize("empty", [False, True]) +@pytest.mark.parametrize("with_schema", [False, True]) +async def test_create_table_recordbatch_iterable_async( + mem_db_async: AsyncConnection, iterable_type, empty, with_schema +): + schema = pa.schema([pa.field("id", pa.int64())]) + batches = [] if empty else [pa.RecordBatch.from_pydict({"id": [1]}, schema)] + data = iterable_type(batches) + if empty and not with_schema: + with pytest.raises(ValueError, match="empty iterable without a schema"): + await mem_db_async.create_table("test", data=data) + return + + table = await mem_db_async.create_table( + "test", data=data, schema=schema if with_schema else None + ) + assert await table.schema() == schema + assert (await table.to_arrow()).to_pylist() == ([] if empty else [{"id": 1}]) + + +@pytest.mark.parametrize("iterable_type", [iter, tuple]) +@pytest.mark.parametrize("on_bad_vectors", ["error", "drop", "fill", "null"]) +def test_add_empty_recordbatch_iterable( + mem_db: DBConnection, iterable_type, on_bad_vectors +): + table = mem_db.create_table("test", [{"id": 1}]) + if on_bad_vectors == "error": + # The default scannable path still requires an input schema. This + # fix does not change its validation policy for schema-less input. + with pytest.raises(ValueError, match="empty iterator"): + table.add(iterable_type([]), on_bad_vectors=on_bad_vectors) + else: + # Sanitization has the existing table schema available. + table.add(iterable_type([]), on_bad_vectors=on_bad_vectors) + assert table.to_arrow().to_pylist() == [{"id": 1}] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("iterable_type", [iter, tuple]) +@pytest.mark.parametrize("on_bad_vectors", ["error", "drop", "fill", "null"]) +async def test_add_empty_recordbatch_iterable_async( + mem_db_async: AsyncConnection, iterable_type, on_bad_vectors +): + table = await mem_db_async.create_table("test", [{"id": 1}]) + if on_bad_vectors == "error": + with pytest.raises(ValueError, match="empty iterator"): + await table.add(iterable_type([]), on_bad_vectors=on_bad_vectors) + else: + await table.add(iterable_type([]), on_bad_vectors=on_bad_vectors) + assert (await table.to_arrow()).to_pylist() == [{"id": 1}] + + def test_create_table_empty_list_with_schema(mem_db: DBConnection): """Test creating table with empty list data and schema @@ -4763,6 +5490,7 @@ async def test_async_search_runs_embedding_on_dedicated_executor( ) +@pytest.mark.experimental_functions def test_computed_column_declare_and_refresh(tmp_path): db = lancedb.connect(tmp_path) table = db.create_table("computed", [{"x": 1}, {"x": 2}]) @@ -4786,6 +5514,7 @@ def test_computed_column_rejects_transforms_and_computed_together(tmp_path): table.add_columns({"a": "x + 1"}, computed={"b": "x * 2"}) +@pytest.mark.experimental_functions def test_computed_column_blob_projection_inherits_semantics(tmp_path): schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) db = lancedb.connect(tmp_path) @@ -4809,6 +5538,7 @@ def test_computed_column_blob_projection_inherits_semantics(tmp_path): assert copied.to_pylist() == [b"hello", b"", None] +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_computed_column_async(tmp_path): db = await lancedb.connect_async(tmp_path) @@ -4823,10 +5553,13 @@ async def test_computed_column_async(tmp_path): 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="LanceDB Cloud and Enterprise"): + with pytest.raises( + NotImplementedError, match="recorded only in LanceDB Distributed" + ): table.function_errors() +@pytest.mark.experimental_functions def test_refresh_column_async_returns_job(tmp_path): db = lancedb.connect(tmp_path) table = db.create_table("computed_job", [{"x": 1}, {"x": 2}]) @@ -4855,6 +5588,7 @@ def test_refresh_column_async_returns_job(tmp_path): table.refresh_column_async("x") +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_refresh_column_async_job_async_table(tmp_path): db = await lancedb.connect_async(tmp_path) @@ -4869,3 +5603,55 @@ async def test_refresh_column_async_job_async_table(tmp_path): assert result.published_version == 4 assert await job.status() == "finished" assert (await table.to_arrow())["tripled"].to_pylist() == [9] + + +@pytest.mark.experimental_functions +@pytest.mark.parametrize("interval", [None, 300]) +def test_computed_auto_refresh_options(tmp_path, interval): + db = lancedb.connect(tmp_path) + table = db.create_table("refresh_options", [{"x": 1}]) + before = table.version + table.add_columns( + computed={"doubled": "x * 2", "tripled": "x * 3"}, + auto_refresh_enabled=False, + auto_refresh_interval_seconds=interval, + ) + assert table.version == before + 1 + for column in ("doubled", "tripled"): + metadata = table.schema.field(column).metadata + assert metadata[b"computed_column.auto_refresh_enabled"] == b"false" + if interval is None: + assert b"computed_column.auto_refresh_interval_seconds" not in metadata + else: + assert metadata[b"computed_column.auto_refresh_interval_seconds"] == b"300" + table.refresh_column("doubled") + assert table.to_arrow()["doubled"].to_pylist() == [2] + + +@pytest.mark.parametrize("value", [0, -1, True, 1.5, "300", 2**64]) +def test_computed_auto_refresh_rejects_invalid_interval(tmp_path, value): + table = lancedb.connect(tmp_path).create_table("invalid_options", [{"x": 1}]) + with pytest.raises(ValueError, match="auto_refresh_interval_seconds"): + table.add_columns( + computed={"doubled": "x * 2"}, auto_refresh_interval_seconds=value + ) + assert table.schema.names == ["x"] + + +def test_auto_refresh_options_require_computed_columns(tmp_path): + table = lancedb.connect(tmp_path).create_table("invalid_kind", [{"x": 1}]) + with pytest.raises(ValueError, match="require computed"): + table.add_columns({"doubled": "x * 2"}, auto_refresh_enabled=True) + + +@pytest.mark.experimental_functions +@pytest.mark.asyncio +async def test_async_computed_auto_refresh_uses_server_interval(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("server_interval", [{"x": 1}]) + before = await table.version() + await table.add_columns(computed={"doubled": "x * 2"}) + assert await table.version() == before + 1 + metadata = (await table.schema()).field("doubled").metadata + assert metadata[b"computed_column.auto_refresh_enabled"] == b"true" + assert b"computed_column.auto_refresh_interval_seconds" not in metadata diff --git a/python/python/tests/test_table_signatures.py b/python/python/tests/test_table_signatures.py new file mode 100644 index 000000000..346935b2b --- /dev/null +++ b/python/python/tests/test_table_signatures.py @@ -0,0 +1,253 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import timedelta +import inspect +from unittest.mock import AsyncMock, MagicMock + +import lancedb +from lancedb.expr import col +from lancedb.index import BTree, FTS, HnswSq, IvfPq +from lancedb.remote.table import RemoteTable +from lancedb.table import LanceTable, Table +import pyarrow as pa +import pytest + + +@pytest.mark.parametrize( + "method", + [ + "delete", + "drop_index", + "index_stats", + "create_index", + "create_scalar_index", + "create_fts_index", + "search", + "cleanup_old_versions", + "compact_files", + "optimize", + "to_polars", + ], +) +def test_sync_table_signatures(method): + """A Table call must bind the same arguments on either backend.""" + + def parameters(cls): + return [ + (p.name, p.kind, p.default) + for p in inspect.signature(getattr(cls, method)).parameters.values() + ] + + assert parameters(Table) == parameters(LanceTable) == parameters(RemoteTable) + + +@pytest.fixture(params=[LanceTable, RemoteTable], ids=["local", "remote"]) +def sync_table(request, monkeypatch): + """Exercise real sync wrappers with a recording async backend.""" + handle = MagicMock() + handle.name = "test" + handle.create_index = AsyncMock() + handle.delete = AsyncMock() + handle.drop_index = AsyncMock() + handle.index_stats = AsyncMock() + if request.param is RemoteTable: + table = RemoteTable(handle, "test_db") + else: + table = LanceTable.__new__(LanceTable) + table._table = handle + monkeypatch.setattr(table, "_ensure_no_legacy_fts_index", lambda: None) + return table, handle + + +def test_sync_keyword_names(sync_table): + table, handle = sync_table + predicate = col("id") == 1 + table.delete(where=predicate) + handle.delete.assert_awaited_once() + expected = predicate._inner if isinstance(table, LanceTable) else predicate + assert handle.delete.await_args.args[0] is expected + table.drop_index(name="vector_idx") + handle.drop_index.assert_awaited_once_with("vector_idx") + table.index_stats(index_name="vector_idx") + handle.index_stats.assert_awaited_once_with("vector_idx") + + +def test_legacy_vector_positional_arguments(sync_table): + table, handle = sync_table + with pytest.warns(DeprecationWarning): + table.create_index("cosine", 2) + args, kwargs = handle.create_index.await_args + assert args == ("vector",) + assert isinstance(kwargs["config"], IvfPq) + assert kwargs["config"].distance_type == "cosine" + assert kwargs["config"].num_partitions == 2 + assert kwargs["replace"] is True + + +def test_vector_tuning_options(sync_table): + table, handle = sync_table + timeout = timedelta(seconds=2) + with pytest.warns(DeprecationWarning): + table.create_index( + index_type="IVF_HNSW_SQ", + num_partitions=1, + m=10, + ef_construction=50, + max_iterations=12, + sample_rate=64, + target_partition_size=1000, + wait_timeout=timeout, + name="custom_idx", + replace=False, + train=False, + ) + kwargs = handle.create_index.await_args.kwargs + config = kwargs.pop("config") + assert isinstance(config, HnswSq) + for name, value in { + "num_partitions": 1, + "m": 10, + "ef_construction": 50, + "max_iterations": 12, + "sample_rate": 64, + "target_partition_size": 1000, + }.items(): + assert getattr(config, name) == value + assert kwargs == dict( + wait_timeout=timeout, name="custom_idx", replace=False, train=False + ) + + +def test_scalar_defaults_and_wait_timeout(sync_table): + table, handle = sync_table + timeout = timedelta(seconds=2) + with pytest.warns(DeprecationWarning): + table.create_scalar_index("id", wait_timeout=timeout) + kwargs = handle.create_index.await_args.kwargs + assert isinstance(kwargs["config"], BTree) + assert kwargs["replace"] is True + assert kwargs["wait_timeout"] == timeout + + +def test_fts_tokenizer_and_wait_timeout(sync_table): + table, handle = sync_table + timeout = timedelta(seconds=2) + with pytest.warns(DeprecationWarning): + table.create_fts_index( + field_names="text", + tokenizer_name="en_stem", + replace=True, + wait_timeout=timeout, + custom_stop_words=["example"], + ) + args, kwargs = handle.create_index.await_args + assert args == ("text",) + assert kwargs["replace"] is True + assert kwargs["wait_timeout"] == timeout + config = kwargs["config"] + assert isinstance(config, FTS) + assert config.language == "English" + assert config.stem is True + assert config.custom_stop_words == ["example"] + + +@pytest.mark.parametrize( + "kwargs, message", + [ + ({"use_tantivy": True}, "Tantivy-based FTS has been removed"), + ({"ordering_field_names": "id"}, "ordering_field_names"), + ({"writer_heap_size": 123}, "writer_heap_size"), + ({"tokenizer_name": "invalid"}, "Invalid tokenizer name"), + ], +) +def test_fts_unsupported_options(sync_table, kwargs, message): + table, handle = sync_table + with pytest.warns(DeprecationWarning), pytest.raises(ValueError, match=message): + table.create_fts_index("text", **kwargs) + handle.create_index.assert_not_awaited() + + +@pytest.mark.parametrize( + "method, kwargs", + [ + ( + "cleanup_old_versions", + {"older_than": timedelta(days=1), "delete_unverified": True}, + ), + ("compact_files", {"target_rows_per_fragment": 1000}), + ], +) +def test_remote_maintenance_options_warn(method, kwargs): + table = RemoteTable(MagicMock(name="test"), "test_db") + with pytest.warns(UserWarning, match="no-op"): + getattr(table, method)(**kwargs) + + +def test_remote_optimize_options(): + handle = MagicMock() + handle.optimize = AsyncMock(side_effect=NotImplementedError("remote optimize")) + table = RemoteTable(handle, "test_db") + age = timedelta(days=1) + 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 + ) + + +@pytest.mark.parametrize( + "method, old, new, value", + [ + ("delete", "predicate", "where", "id = 1"), + ("drop_index", "index_name", "name", "vector_idx"), + ("index_stats", "index_uuid", "index_name", "vector_idx"), + ("create_fts_index", "column", "field_names", "text"), + ], +) +def test_deprecated_remote_keywords(method, old, new, value): + handle = MagicMock() + handle.name = "test" + target = "create_index" if method == "create_fts_index" else method + setattr(handle, target, AsyncMock()) + table = RemoteTable(handle, "test_db") + with pytest.warns(DeprecationWarning, match=f"{old} is deprecated"): + getattr(table, method)(**{old: value}) + assert getattr(handle, target).await_args.args == (value,) + with pytest.raises(TypeError, match="Cannot specify both"): + getattr(table, method)(**{old: value, new: value}) + + +@pytest.mark.parametrize("remote_wrapper", [False, True], ids=["local", "remote"]) +def test_sync_search_and_polars(tmp_path, remote_wrapper): + """Use the native engine through both sync wrappers, without a cloud service.""" + local = lancedb.connect(tmp_path).create_table( + "test", + [{"id": 1, "text": "quick fox", "vector": [1.0, 1.0]}], + ) + table = RemoteTable(local._table, "test_db") if remote_wrapper else local + table.create_index("text", config=FTS()) + assert table.search("quick", query_type="fts").to_arrow()["id"].to_pylist() == [1] + # Both backends must accept the deprecated ordering argument in the same slot. + with pytest.warns(DeprecationWarning, match="ordering_field_name"): + table.search("quick", None, "fts", "id", ["text"]) + fast = table.search([1.0, 1.0], fast_search=True).to_arrow() + assert len(fast) == 0 # No vector index: fast_search excludes unindexed rows. + assert table.search([1.0, 1.0]).to_arrow()["id"].to_pylist() == [1] + if remote_wrapper: + with pytest.raises(NotImplementedError, match=r"table.search\(\).to_polars"): + table.to_polars(batch_size=1) + assert table.search().to_polars()["id"].to_list() == [1] + else: + assert table.to_polars(batch_size=1).collect()["id"].to_list() == [1] + table.delete(where="id = 1") + assert table.count_rows() == 0 + + +def test_index_replacement_defaults(tmp_path): + local = lancedb.connect(tmp_path).create_table("test", pa.table({"id": [1]})) + table = RemoteTable(local._table, "test_db") + for sync in [local, table]: + with pytest.warns(DeprecationWarning): + sync.create_scalar_index("id") + assert len(list(table.list_indices())) == 1 diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py index 38a367330..befa3c10f 100644 --- a/python/python/tests/test_torch.py +++ b/python/python/tests/test_torch.py @@ -9,13 +9,13 @@ import multiprocessing as mp import pickle import re import sys -import threading import lancedb import pyarrow as pa import pytest from lancedb.permutation import Permutation, Permutations, permutation_builder from lancedb.util import tbl_to_tensor +from utils import start_server_thread torch = pytest.importorskip("torch") @@ -74,17 +74,23 @@ def _remote_dataset_handler(request): body = json.loads(request.rfile.read(content_len)) offsets = _offsets_from_filter(body.get("filter")) requested_columns = body.get("columns") or ["a"] + # A dynamic projection is sent as {output name: source expression}; take + # queries use it to alias `_rowoffset` as `__lancedb_take_row_offset`. if isinstance(requested_columns, dict): - requested_columns = list(requested_columns) + projection = requested_columns + else: + projection = {column: column for column in requested_columns} - data = {} - for column in requested_columns: - if column == "a": - data[column] = [REMOTE_ROWS[offset] for offset in offsets] - elif column == "_rowoffset": - data[column] = offsets - elif column == "_rowid": - data[column] = offsets + sources = { + "a": [REMOTE_ROWS[offset] for offset in offsets], + "_rowoffset": offsets, + "_rowid": offsets, + } + data = { + name: sources[source] + for name, source in projection.items() + if source in sources + } table = pa.table(data) request.send_response(200) @@ -100,16 +106,15 @@ def _remote_dataset_handler(request): @contextlib.contextmanager def _remote_dataset_table(): with http.server.ThreadingHTTPServer( - ("localhost", 0), _make_mock_http_handler(_remote_dataset_handler) + ("127.0.0.1", 0), _make_mock_http_handler(_remote_dataset_handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) try: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -349,7 +354,7 @@ def _remote_multiworker_dataloader_target(port: int, result_queue): db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -419,11 +424,10 @@ def test_permutation_dataloader_fork_workers(tmp_path): ) def test_remote_permutation_dataloader_fork_workers(): with http.server.ThreadingHTTPServer( - ("localhost", 0), _make_mock_http_handler(_remote_dataset_handler) + ("127.0.0.1", 0), _make_mock_http_handler(_remote_dataset_handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) try: ctx = mp.get_context("spawn") queue = ctx.Queue() diff --git a/python/python/tests/test_util.py b/python/python/tests/test_util.py index 741214794..1e470e3be 100644 --- a/python/python/tests/test_util.py +++ b/python/python/tests/test_util.py @@ -4,6 +4,7 @@ import os import pathlib +from datetime import time, timedelta, timezone from decimal import Decimal, localcontext from typing import Optional @@ -21,6 +22,7 @@ from lancedb.table import ( _infer_target_schema, _merge_metadata, _sanitize_data, + has_nan_values, sanitize_create_table, ) import pyarrow as pa @@ -30,6 +32,7 @@ import pytest import lancedb from lancedb.util import ( flatten_columns, + get_uri_location, get_uri_scheme, inf_vector_column_query, join_uri, @@ -86,6 +89,22 @@ def test_normalize_uri(): assert parsed_scheme == expected_scheme +def test_get_uri_scheme_and_location_pathlib(): + # Test pathlib.Path instances + abs_path = pathlib.Path("/tmp/data") + rel_path = pathlib.Path("relative/data") + + assert get_uri_scheme(abs_path) == "file" + assert get_uri_scheme(rel_path) == "file" + + assert get_uri_location(abs_path) == str(abs_path) + assert get_uri_location(rel_path) == str(rel_path) + + # String URIs still behave identically + assert get_uri_scheme("s3://bucket/data") == "s3" + assert get_uri_location("s3://bucket/data") == "bucket/data" + + def test_join_uri_remote(): schemes = ["s3", "az", "gs"] for scheme in schemes: @@ -199,6 +218,106 @@ def test_value_to_sql_decimal_non_finite(value): value_to_sql(Decimal(value)) +def test_value_to_sql_time_and_timedelta(tmp_path): + assert ( + value_to_sql(time(9, 30, 0, 250)) + == "arrow_cast('09:30:00.000250', 'Time64(Microsecond)')" + ) + assert ( + value_to_sql(timedelta(days=1, microseconds=5)) + == "arrow_cast(86400000005, 'Duration(Microsecond)')" + ) + assert ( + value_to_sql(timedelta(seconds=-1)) + == "arrow_cast(-1000000, 'Duration(Microsecond)')" + ) + + # Round trip through update and a filter, including columns whose unit is not + # microseconds. + db = lancedb.connect(tmp_path) + table = db.create_table( + "test", + pa.table( + { + "id": [1, 2], + "starts": pa.array([time(1, 2, 3), time(4, 5, 6)], pa.time64("us")), + "starts_ns": pa.array([time(1, 2, 3), time(4, 5, 6)], pa.time64("ns")), + "duration": pa.array([timedelta(0), timedelta(0)], pa.duration("us")), + "duration_s": pa.array([timedelta(0), timedelta(0)], pa.duration("s")), + } + ), + ) + table.update( + where="id = 1", + values={ + "starts": time(9, 30, 0, 250), + "starts_ns": time(9, 30, 0, 250), + "duration": timedelta(minutes=45, microseconds=5), + "duration_s": timedelta(hours=2), + }, + ) + assert table.to_arrow().sort_by("id").slice(0, 1).to_pylist() == [ + { + "id": 1, + "starts": time(9, 30, 0, 250), + "starts_ns": time(9, 30, 0, 250), + "duration": timedelta(minutes=45, microseconds=5), + "duration_s": timedelta(hours=2), + } + ] + for where in ( + f"starts = {value_to_sql(time(9, 30, 0, 250))}", + f"duration = {value_to_sql(timedelta(minutes=45, microseconds=5))}", + ): + assert table.search().where(where).to_arrow()["id"].to_pylist() == [1] + + +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)')" + ) + assert value_to_sql(pa.scalar(None, pa.duration("ns"))) == "NULL" + + db = lancedb.connect(tmp_path) + table = db.create_table( + "test", + pa.table( + { + "id": [1, 2], + "duration": pa.array([0, 1001], pa.duration("ns")), + "starts": pa.array([0, 34_200_000_000_250], pa.time64("ns")), + } + ), + ) + source = table.to_arrow().sort_by("id") + table.update( + where="id = 1", + values={"duration": source["duration"][1], "starts": source["starts"][1]}, + ) + updated = table.to_arrow().sort_by("id") + assert updated["duration"].cast(pa.int64()).to_pylist() == [1001, 1001] + assert updated["starts"].cast(pa.int64()).to_pylist() == [ + 34_200_000_000_250, + 34_200_000_000_250, + ] + + +def test_value_to_sql_keeps_duration_units(): + for unit, sql_unit in [("s", "Second"), ("ms", "Millisecond")]: + assert ( + value_to_sql(pa.scalar(1500, pa.duration(unit))) + == f"arrow_cast(1500, 'Duration({sql_unit})')" + ) + + +def test_value_to_sql_rejects_time_with_timezone(): + with pytest.raises(ValueError, match="time values with a timezone"): + value_to_sql(time(9, 30, tzinfo=timezone.utc)) + + def test_value_to_sql_dict(): # Simple flat struct assert value_to_sql({"a": 1, "b": "hello"}) == "named_struct('a', 1, 'b', 'hello')" @@ -388,7 +507,7 @@ def test_handle_bad_vectors_jagged(on_bad_vectors): ).read_all() if on_bad_vectors == "drop": - expected = pa.array([[1.0, 2.0], [4.0, 5.0], [None, 9.0]]) + expected = pa.array([[1.0, 2.0], [4.0, 5.0]]) elif on_bad_vectors == "fill": expected = pa.array( [ @@ -396,12 +515,12 @@ def test_handle_bad_vectors_jagged(on_bad_vectors): [3.0, 42.0], [4.0, 5.0], [6.0, 7.0], - [None, 9.0], + [42.0, 9.0], [42.0, 42.0], ] ) elif on_bad_vectors == "null": - expected = pa.array([[1.0, 2.0], None, [4.0, 5.0], None, [None, 9.0], None]) + expected = pa.array([[1.0, 2.0], None, [4.0, 5.0], None, None, None]) assert output["vector"].combine_chunks() == expected @@ -412,17 +531,17 @@ def test_handle_bad_vectors_jagged(on_bad_vectors): ( pa.list_(pa.float64()), [[1.0, float("nan")], [2.0], None, [None, 3.0], [4.0, 5.0, 6.0]], - [[1.0, 42.0], [2.0, 42.0], [42.0, 42.0], [None, 3.0], [4.0, 5.0]], + [[1.0, 42.0], [2.0, 42.0], [42.0, 42.0], [42.0, 3.0], [4.0, 5.0]], ), ( pa.large_list(pa.float64()), [[1.0, float("nan")], [2.0], None, [None, 3.0], [4.0, 5.0, 6.0]], - [[1.0, 42.0], [2.0, 42.0], [42.0, 42.0], [None, 3.0], [4.0, 5.0]], + [[1.0, 42.0], [2.0, 42.0], [42.0, 42.0], [42.0, 3.0], [4.0, 5.0]], ), ( pa.list_(pa.float64(), 2), [[1.0, float("nan")], None, [None, 3.0]], - [[1.0, 42.0], [42.0, 42.0], [None, 3.0]], + [[1.0, 42.0], [42.0, 42.0], [42.0, 3.0]], ), ], ) @@ -449,7 +568,7 @@ def test_handle_bad_vectors_nan(on_bad_vectors): ).read_all() output = exception_output(e) assert output == ( - "ValueError: Vector column 'vector' has NaNs. Set " + "ValueError: Vector column 'vector' has NaNs or null values. Set " "on_bad_vectors='drop' to remove them, set on_bad_vectors='fill' " "and fill_value= to replace them, or set on_bad_vectors='null' " "to replace them with null." @@ -472,6 +591,60 @@ def test_handle_bad_vectors_nan(on_bad_vectors): assert output["vector"].combine_chunks() == expected +@pytest.mark.parametrize("value_type", [pa.float16(), pa.float32(), pa.float64()]) +@pytest.mark.parametrize( + "list_type", [pa.list_, pa.large_list, lambda t: pa.list_(t, 2)] +) +@pytest.mark.parametrize("chunked", [False, True]) +def test_has_nan_values_with_null_elements(value_type, list_type, chunked): + arr = pa.array( + [[None, None], [1.0, 2.0], [None, 3.0], None, [4.0, float("nan")], [5.0, 6.0]], + type=list_type(value_type), + ).slice(1, 5) + if chunked: + arr = pa.chunked_array([arr.slice(0, 2), arr.slice(2)]) + # Whole null vectors have no components to inspect. Their handling is + # separate from missing or NaN components in a valid vector. + assert has_nan_values(arr).to_pylist() == [False, True, False, True, False] + + +@pytest.mark.parametrize("on_bad_vectors", ["error", "drop", "fill", "null"]) +def test_sanitize_vectors_with_only_null_elements(on_bad_vectors): + data = pa.table({"vector": [[None, None]]}) + schema = pa.schema({"vector": pa.list_(pa.float32(), 2)}) + + def sanitize(): + return _sanitize_data( + data, schema, on_bad_vectors=on_bad_vectors, fill_value=42.0 + ).read_all() + + if on_bad_vectors == "error": + with pytest.raises(ValueError, match="null"): + sanitize() + return + + expected = { + "drop": [], + "fill": [{"vector": [42.0, 42.0]}], + "null": [{"vector": None}], + } + assert sanitize().to_pylist() == expected[on_bad_vectors] + + +@pytest.mark.parametrize("dtype", [pa.float16(), pa.float32(), pa.float64()]) +@pytest.mark.parametrize("large", [False, True]) +@pytest.mark.parametrize("chunked", [False, True]) +def test_has_nan_values_skips_hidden_children_of_null_lists(dtype, large, chunked): + array_type = pa.LargeListArray if large else pa.ListArray + values = pa.array([float("nan"), None, float("nan"), 3.0, 4.0, 5.0], type=dtype) + arr = array_type.from_arrays( + [0, 2, 4, 6], values, mask=pa.array([True, False, False]) + ) + if chunked: + arr = pa.chunked_array([arr.slice(0, 2), arr.slice(2, 1)]) + assert has_nan_values(arr).to_pylist() == [False, True, False] + + def test_handle_bad_vectors_noop(): # ChunkedArray should be preserved as-is vector = pa.chunked_array( diff --git a/python/python/tests/test_util_update_values.py b/python/python/tests/test_util_update_values.py new file mode 100644 index 000000000..fdef867da --- /dev/null +++ b/python/python/tests/test_util_update_values.py @@ -0,0 +1,215 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import date, datetime + +import lancedb +import numpy as np +import pyarrow as pa +import pytest + + +ARRAY_VALUES = [ + ((1.0, 2.0), [1.0, 2.0]), + ([1.0, 2.0], [1.0, 2.0]), + (np.array([1.0, 2.0]), [1.0, 2.0]), + (None, None), +] + + +@pytest.mark.parametrize("value,expected", ARRAY_VALUES) +def test_update_array_values(tmp_path, value, expected): + dtype = pa.list_(pa.float64()) + db = lancedb.connect(tmp_path) + table = db.create_table( + "values", pa.table({"array": pa.array([[0.0, 0.0]], type=dtype)}) + ) + table.update(values={"array": value}) + assert table.to_arrow()["array"].to_pylist() == [expected] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("value,expected", ARRAY_VALUES) +async def test_update_array_values_async(tmp_path, value, expected): + dtype = pa.list_(pa.float64()) + db = await lancedb.connect_async(tmp_path) + table = await db.create_table( + "values", pa.table({"array": pa.array([[0.0, 0.0]], type=dtype)}) + ) + await table.update({"array": value}) + assert (await table.to_arrow())["array"].to_pylist() == [expected] + + +TIME_VALUES = [ + np.datetime64("2025", "Y"), + np.datetime64("2025-01", "M"), + np.datetime64("2025-01-02", "D"), + np.datetime64("2025-01-02T03", "h"), + np.datetime64("2025-01-02T03:04", "m"), + np.datetime64("2025-01-02T03:04:05", "s"), + np.datetime64("2025-01-02T03:04:05.123", "ms"), + np.datetime64("2025-01-02T03:04:05.123456", "us"), + np.datetime64("2025-01-02T03:04:05.123456789", "ns"), + np.datetime64("NaT", "ns"), + datetime(2025, 1, 2, 3, 4, 5, 123456), + None, +] + + +def expected_time(value): + if value is None or isinstance(value, np.datetime64) and np.isnat(value): + return None + return int(np.datetime64(value, "ns").astype(np.int64)) + + +@pytest.mark.parametrize("value", TIME_VALUES) +def test_update_timestamp_values(tmp_path, value): + db = lancedb.connect(tmp_path) + data = pa.table({"time": pa.array([datetime(2025, 1, 1)], type=pa.timestamp("ns"))}) + table = db.create_table("times", data) + table.update(values={"time": value}) + assert table.to_arrow()["time"].cast(pa.int64()).to_pylist() == [ + expected_time(value) + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("value", TIME_VALUES) +async def test_update_timestamp_values_async(tmp_path, value): + db = await lancedb.connect_async(tmp_path) + data = pa.table({"time": pa.array([datetime(2025, 1, 1)], type=pa.timestamp("ns"))}) + table = await db.create_table("times", data) + await table.update({"time": value}) + assert (await table.to_arrow())["time"].cast(pa.int64()).to_pylist() == [ + expected_time(value) + ] + + +@pytest.mark.parametrize("values", [[[1, 2], [3, 4]], []]) +def test_nested_array_tuple_matches_list(tmp_path, values): + db = lancedb.connect(tmp_path) + data = pa.table( + {"array": pa.array([[[0, 0]]], type=pa.list_(pa.list_(pa.int64())))} + ) + control = db.create_table("list_values", data) + candidate = db.create_table("tuple_values", data) + tuples = tuple(tuple(value) for value in values) + try: + control.update(values={"array": values}) + except ValueError as error: + reason = ( + "Expected a literal value in array" if values else "concat requires input" + ) + assert reason in str(error) + with pytest.raises(ValueError, match=reason): + candidate.update(values={"array": tuples}) + assert control.to_arrow().equals(data) + assert candidate.to_arrow().equals(data) + else: + candidate.update(values={"array": tuples}) + assert candidate.to_arrow().equals(control.to_arrow()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("values", [[[1, 2], [3, 4]], []]) +async def test_nested_array_tuple_matches_list_async(tmp_path, values): + db = await lancedb.connect_async(tmp_path) + data = pa.table( + {"array": pa.array([[[0, 0]]], type=pa.list_(pa.list_(pa.int64())))} + ) + control = await db.create_table("list_values", data) + candidate = await db.create_table("tuple_values", data) + tuples = tuple(tuple(value) for value in values) + try: + await control.update({"array": values}) + except ValueError as error: + reason = ( + "Expected a literal value in array" if values else "concat requires input" + ) + assert reason in str(error) + with pytest.raises(ValueError, match=reason): + await candidate.update({"array": tuples}) + assert (await control.to_arrow()).equals(data) + assert (await candidate.to_arrow()).equals(data) + else: + await candidate.update({"array": tuples}) + assert (await candidate.to_arrow()).equals(await control.to_arrow()) + + +@pytest.mark.parametrize("unit", ["ps", "fs", "as"]) +def test_subnanosecond_update_does_not_round(tmp_path, unit): + db = lancedb.connect(tmp_path) + data = pa.table({"time": pa.array([datetime(1970, 1, 1)], type=pa.timestamp("ns"))}) + table = db.create_table("precise", data) + with pytest.raises(ValueError, match="cannot preserve sub-nanosecond precision"): + table.update(values={"time": np.datetime64(1, unit)}) + assert table.to_arrow()["time"].cast(pa.int64()).to_pylist() == [0] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("unit", ["ps", "fs", "as"]) +async def test_subnanosecond_update_does_not_round_async(tmp_path, unit): + db = await lancedb.connect_async(tmp_path) + data = pa.table({"time": pa.array([datetime(1970, 1, 1)], type=pa.timestamp("ns"))}) + table = await db.create_table("precise", data) + with pytest.raises(ValueError, match="cannot preserve sub-nanosecond precision"): + await table.update({"time": np.datetime64(1, unit)}) + assert (await table.to_arrow())["time"].cast(pa.int64()).to_pylist() == [0] + + +@pytest.mark.parametrize("unit", ["Y", "M", "W", "D"]) +def test_update_numpy_date_column(tmp_path, unit): + value = np.datetime64("2025-01-02", unit) + db = lancedb.connect(tmp_path) + table = db.create_table( + "dates", pa.table({"day": pa.array([date(1970, 1, 1)], type=pa.date32())}) + ) + table.update(values={"day": value}) + assert table.to_arrow()["day"].to_pylist() == [value.astype("datetime64[D]").item()] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("unit", ["Y", "M", "W", "D"]) +async def test_update_numpy_date_column_async(tmp_path, unit): + value = np.datetime64("2025-01-02", unit) + db = await lancedb.connect_async(tmp_path) + table = await db.create_table( + "dates", pa.table({"day": pa.array([date(1970, 1, 1)], type=pa.date32())}) + ) + await table.update({"day": value}) + assert (await table.to_arrow())["day"].to_pylist() == [ + value.astype("datetime64[D]").item() + ] + + +@pytest.mark.parametrize("timezone", [None, "UTC", "America/New_York", "Asia/Tokyo"]) +@pytest.mark.parametrize( + "value", + [np.datetime64("2025-01-02T03:04:05.123456789", "ns"), np.datetime64("NaT", "ns")], +) +def test_update_numpy_timestamp_matches_arrow_ingestion(tmp_path, timezone, value): + dtype = pa.timestamp("ns", tz=timezone) + ingested = pa.array(np.array([value]), type=dtype) + db = lancedb.connect(tmp_path) + table = db.create_table("timestamps", pa.table({"time": ingested})) + expected = table.to_arrow()["time"].cast(pa.int64()).to_pylist() + table.update(values={"time": value}) + assert table.to_arrow()["time"].cast(pa.int64()).to_pylist() == expected + + +@pytest.mark.asyncio +@pytest.mark.parametrize("timezone", [None, "UTC", "America/New_York", "Asia/Tokyo"]) +@pytest.mark.parametrize( + "value", + [np.datetime64("2025-01-02T03:04:05.123456789", "ns"), np.datetime64("NaT", "ns")], +) +async def test_update_numpy_timestamp_matches_arrow_ingestion_async( + tmp_path, timezone, value +): + dtype = pa.timestamp("ns", tz=timezone) + ingested = pa.array(np.array([value]), type=dtype) + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("timestamps", pa.table({"time": ingested})) + expected = (await table.to_arrow())["time"].cast(pa.int64()).to_pylist() + await table.update({"time": value}) + assert (await table.to_arrow())["time"].cast(pa.int64()).to_pylist() == expected diff --git a/python/python/tests/test_voyageai_embeddings.py b/python/python/tests/test_voyageai_embeddings.py index 040cade1f..d49978fb3 100644 --- a/python/python/tests/test_voyageai_embeddings.py +++ b/python/python/tests/test_voyageai_embeddings.py @@ -6,6 +6,8 @@ These tests verify model registration and configuration without requiring API calls. """ +import numpy as np +import pyarrow as pa import pytest from unittest.mock import MagicMock, patch @@ -122,3 +124,58 @@ class TestVoyageAIModelRegistration: assert "voyage-4" not in func.multimodal_embedding_models assert "voyage-4-lite" not in func.multimodal_embedding_models assert "voyage-4-large" not in func.multimodal_embedding_models + + +@pytest.mark.parametrize( + "inputs", + [ + ["first", "second"], + np.array(["first", "second"]), + pa.array(["first", "second"]), + pa.chunked_array([["first"], ["second"]]), + ], + ids=["list", "numpy", "arrow", "chunked-arrow"], +) +def test_text_source_embeddings_accept_batch_containers(inputs): + from lancedb.embeddings.voyageai import VoyageAIEmbeddingFunction + + client = MagicMock() + client.tokenize.return_value = [[1], [2]] + client.embed.return_value.embeddings = [[0.1, 0.2], [0.3, 0.4]] + VoyageAIEmbeddingFunction.client = client + func = get_registry().get("voyageai").create(name="voyage-3") + + assert func.compute_source_embeddings(inputs) == [[0.1, 0.2], [0.3, 0.4]] + client.embed.assert_called_once_with( + texts=["first", "second"], model="voyage-3", input_type="document" + ) + + +@pytest.mark.parametrize("inputs", [[], np.array([], dtype=str)]) +def test_text_source_embeddings_accept_empty_batch(inputs): + from lancedb.embeddings.voyageai import VoyageAIEmbeddingFunction + + client = MagicMock() + VoyageAIEmbeddingFunction.client = client + func = get_registry().get("voyageai").create(name="voyage-3") + + assert func.compute_source_embeddings(inputs) == [] + client.tokenize.assert_not_called() + client.embed.assert_not_called() + + +@pytest.mark.parametrize( + "inputs", + [["text", 42], np.array(["text", None]), np.array([["first", "second"]])], +) +def test_text_source_embeddings_reject_non_text_batch_entries(inputs): + from lancedb.embeddings.voyageai import VoyageAIEmbeddingFunction + + client = MagicMock() + VoyageAIEmbeddingFunction.client = client + func = get_registry().get("voyageai").create(name="voyage-3") + + with pytest.raises(ValueError, match="Each input should be str"): + func.compute_source_embeddings(inputs) + client.tokenize.assert_not_called() + client.embed.assert_not_called() diff --git a/python/python/tests/test_voyageai_image_inputs.py b/python/python/tests/test_voyageai_image_inputs.py new file mode 100644 index 000000000..885f94821 --- /dev/null +++ b/python/python/tests/test_voyageai_image_inputs.py @@ -0,0 +1,88 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import base64 +from io import BytesIO +from unittest.mock import MagicMock + +import pytest + +from lancedb.embeddings import get_registry +from lancedb.embeddings.voyageai import VoyageAIEmbeddingFunction + + +@pytest.mark.parametrize("model_name", ["voyage-multimodal-3", "voyage-multimodal-3.5"]) +@pytest.mark.parametrize("input_kind", ["pil", "bytes", "path"]) +@pytest.mark.parametrize( + "mode,color,expected_rgb", + [ + ("RGBA", (64, 128, 192, 128), (64, 128, 192)), + ("LA", (96, 128), (96, 96, 96)), + ("P", 0, (64, 128, 192)), + ("RGB", (64, 128, 192), (64, 128, 192)), + ], +) +def test_multimodal_source_embeddings_encode_image_modes( + model_name, input_kind, mode, color, expected_rgb, tmp_path, monkeypatch +): + Image = pytest.importorskip("PIL.Image") + image = Image.new(mode, (8, 6), color) + if mode == "P": + image.putpalette([64, 128, 192] + [0, 0, 0] * 255) + image.info["transparency"] = 0 + original_pixels = image.tobytes() + image_input = image + if input_kind != "pil": + png = BytesIO() + image.save(png, format="PNG") + if input_kind == "bytes": + image_input = png.getvalue() + else: + image_input = tmp_path / "image.png" + image_input.write_bytes(png.getvalue()) + + client = MagicMock() + client.multimodal_embed.return_value.embeddings = [[0.1, 0.2]] + monkeypatch.setattr(VoyageAIEmbeddingFunction, "client", client) + func = get_registry().get("voyageai").create(name=model_name) + + assert func.compute_source_embeddings(image_input) == [[0.1, 0.2]] + + client.multimodal_embed.assert_called_once() + request = client.multimodal_embed.call_args.kwargs + assert request["model"] == model_name + assert request["input_type"] == "document" + assert len(request["inputs"]) == 1 + (content,) = request["inputs"][0]["content"] + assert content["type"] == "image_base64" + prefix, encoded = content["image_base64"].split(",", 1) + assert prefix == "data:image/jpeg;base64" + with Image.open(BytesIO(base64.b64decode(encoded, validate=True))) as decoded: + assert decoded.format == "JPEG" + assert decoded.mode == "RGB" + assert decoded.size == (8, 6) + assert decoded.getpixel((0, 0)) == pytest.approx(expected_rgb, abs=3) + assert image.mode == mode + assert image.tobytes() == original_pixels + client.embed.assert_not_called() + + +@pytest.mark.parametrize("input_kind", ["bytes", "path"]) +def test_multimodal_source_embeddings_reject_invalid_image( + input_kind, tmp_path, monkeypatch +): + PIL = pytest.importorskip("PIL") + image_input = b"not an image" + if input_kind == "path": + image_input = tmp_path / "invalid.png" + image_input.write_bytes(b"not an image") + + client = MagicMock() + monkeypatch.setattr(VoyageAIEmbeddingFunction, "client", client) + func = get_registry().get("voyageai").create(name="voyage-multimodal-3") + + with pytest.raises(PIL.UnidentifiedImageError): + func.compute_source_embeddings(image_input) + + client.multimodal_embed.assert_not_called() + client.embed.assert_not_called() diff --git a/python/python/tests/utils.py b/python/python/tests/utils.py index ca72a4dfd..7c4c30b71 100644 --- a/python/python/tests/utils.py +++ b/python/python/tests/utils.py @@ -153,6 +153,15 @@ class MockPermutationServer: return self._arrow(request, pa.table({"id": pa.array([], pa.int64())})) +def start_server_thread(server, daemon=False) -> threading.Thread: + """Serve on a thread; a short poll interval lets ``shutdown()`` return promptly.""" + thread = threading.Thread( + target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=daemon + ) + thread.start() + return thread + + def _make_handler(serve): class MockLanceDBHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): @@ -175,15 +184,14 @@ def mock_remote_table(server): serialize, hiding the prefetch overlap under test. """ with http.server.ThreadingHTTPServer( - ("localhost", 0), _make_handler(server) + ("127.0.0.1", 0), _make_handler(server) ) as srv: - thread = threading.Thread(target=srv.serve_forever) - thread.start() + thread = start_server_thread(srv) try: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{srv.server_address[1]}", + host_override=f"http://127.0.0.1:{srv.server_address[1]}", client_config={"timeout_config": {"connect_timeout": 5}}, ) yield db.open_table(server.name) diff --git a/python/src/catalog.rs b/python/src/catalog.rs index 9e375b314..fb2e7e8a0 100644 --- a/python/src/catalog.rs +++ b/python/src/catalog.rs @@ -60,16 +60,21 @@ impl Catalog { }) } - #[pyo3(signature = (name, *, ignore_missing=false))] + #[pyo3(signature = (name, *, ignore_missing=false, cascade=false))] fn drop_database<'py>( self_: PyRef<'py, Self>, name: String, ignore_missing: bool, + cascade: bool, ) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { inner - .drop_database(DropDatabaseRequest::new(name).ignore_missing(ignore_missing)) + .drop_database( + DropDatabaseRequest::new(name) + .ignore_missing(ignore_missing) + .cascade(cascade), + ) .await .infer_error() }) diff --git a/python/src/connection.rs b/python/src/connection.rs index 9ac081b9d..54ea615de 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -49,6 +49,18 @@ impl Connection { } } +fn parse_read_consistency_interval(interval: Option) -> PyResult> { + interval + .map(|seconds| { + Duration::try_from_secs_f64(seconds).map_err(|_| { + PyValueError::new_err( + "read_consistency_interval must be finite, non-negative, and within the supported range", + ) + }) + }) + .transpose() +} + fn parse_namespace_client_pushdown_operations( operations: Option>, ) -> PyResult> { @@ -412,7 +424,8 @@ impl Connection { }) } - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, @@ -421,10 +434,18 @@ impl Connection { filter: Option, limit: Option, with_no_data: bool, + auto_refresh_enabled: Option, + auto_refresh_interval_seconds: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { let mut builder = inner.create_materialized_view(name, source); + if let Some(enabled) = auto_refresh_enabled { + builder = builder.auto_refresh_enabled(enabled); + } + if let Some(seconds) = auto_refresh_interval_seconds { + builder = builder.auto_refresh_interval_seconds(seconds); + } if let Some(projections) = projections { builder = builder.select(projections); } @@ -440,7 +461,8 @@ impl Connection { }) } - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, @@ -449,10 +471,18 @@ impl Connection { filter: Option, limit: Option, with_no_data: bool, + auto_refresh_enabled: Option, + auto_refresh_interval_seconds: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { let mut builder = inner.create_materialized_view(name, source); + if let Some(enabled) = auto_refresh_enabled { + builder = builder.auto_refresh_enabled(enabled); + } + if let Some(seconds) = auto_refresh_interval_seconds { + builder = builder.auto_refresh_interval_seconds(seconds); + } if let Some(projections) = projections { builder = builder.select(projections); } @@ -560,29 +590,17 @@ impl Connection { #[pyo3(signature = (namespace_path=None, page_token=None, limit=None))] pub fn list_namespaces( - self_: PyRef<'_, Self>, + &self, namespace_path: Option>, page_token: Option, limit: Option, - ) -> PyResult> { - let inner = self_.get_inner()?.clone(); - let py = self_.py(); - future_into_py(py, async move { - use lance_namespace::models::ListNamespacesRequest; - let request = ListNamespacesRequest { - id: namespace_path, - page_token, - limit: limit.map(|l| l as i32), - ..Default::default() - }; - let response = inner.list_namespaces(request).await.infer_error()?; - Python::attach(|py| -> PyResult> { - let dict = PyDict::new(py); - dict.set_item("namespaces", response.namespaces)?; - dict.set_item("page_token", response.page_token)?; - Ok(dict.unbind()) - }) - }) + ) -> PyResult { + Ok(crate::listing::NameListing::new( + self.get_inner()?.list_namespaces( + &namespace_path.unwrap_or_default(), + crate::listing::options(page_token, limit), + ), + )) } #[pyo3(signature = (namespace_path, mode=None, properties=None))] @@ -693,31 +711,66 @@ impl Connection { }) } + pub fn namespace_exists( + self_: PyRef<'_, Self>, + namespace_id: Vec, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let request = lance_namespace::models::DescribeNamespaceRequest { + id: Some(namespace_id), + ..Default::default() + }; + match inner.describe_namespace(request).await { + Ok(_) => Ok(true), + Err(lancedb::Error::Http { + status_code: Some(status), + .. + }) if status.as_u16() == 404 => Ok(false), + Err(lancedb::Error::Lance { + source: lance_core::Error::Namespace { ref source, .. }, + }) if matches!( + source.downcast_ref::(), + Some(lance_namespace::NamespaceError::NamespaceNotFound { .. }) + ) => + { + Ok(false) + } + Err(err) => Err(err).infer_error(), + } + }) + } + + pub fn table_exists( + self_: PyRef<'_, Self>, + mut table_id: Vec, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let name = table_id + .pop() + .ok_or_else(|| PyValueError::new_err("table_id must include a table name"))?; + future_into_py(self_.py(), async move { + match inner.open_table(name).namespace(table_id).execute().await { + Ok(_) => Ok(true), + Err(lancedb::Error::TableNotFound { .. }) => Ok(false), + Err(err) => Err(err).infer_error(), + } + }) + } + #[pyo3(signature = (namespace_path=None, page_token=None, limit=None))] pub fn list_tables( - self_: PyRef<'_, Self>, + &self, namespace_path: Option>, page_token: Option, limit: Option, - ) -> PyResult> { - let inner = self_.get_inner()?.clone(); - let py = self_.py(); - future_into_py(py, async move { - use lance_namespace::models::ListTablesRequest; - let request = ListTablesRequest { - id: namespace_path, - page_token, - limit: limit.map(|l| l as i32), - ..Default::default() - }; - let response = inner.list_tables(request).await.infer_error()?; - Python::attach(|py| -> PyResult> { - let dict = PyDict::new(py); - dict.set_item("tables", response.tables)?; - dict.set_item("page_token", response.page_token)?; - Ok(dict.unbind()) - }) - }) + ) -> PyResult { + Ok(crate::listing::NameListing::new( + self.get_inner()?.list_tables( + &namespace_path.unwrap_or_default(), + crate::listing::options(page_token, limit), + ), + )) } /// Get the configuration for constructing an equivalent namespace client. @@ -1059,6 +1112,7 @@ pub fn connect( namespace_client_properties: Option>, oauth_config: Option, ) -> PyResult> { + let read_consistency_interval = parse_read_consistency_interval(read_consistency_interval)?; future_into_py(py, async move { let mut builder = lancedb::connect(&uri); if let Some(api_key) = api_key { @@ -1077,7 +1131,6 @@ pub fn connect( #[cfg(not(feature = "remote"))] let _ = sql_host_override; if let Some(read_consistency_interval) = read_consistency_interval { - let read_consistency_interval = Duration::from_secs_f64(read_consistency_interval); builder = builder.read_consistency_interval(read_consistency_interval); } if let Some(storage_options) = storage_options { @@ -1126,7 +1179,7 @@ pub fn connect_namespace_client( namespace_client_impl: Option, namespace_client_properties: Option>, ) -> PyResult { - let read_consistency_interval = read_consistency_interval.map(Duration::from_secs_f64); + let read_consistency_interval = parse_read_consistency_interval(read_consistency_interval)?; let namespace_client_pushdown_operations = parse_namespace_client_pushdown_operations(namespace_client_pushdown_operations)?; let ns_properties = namespace_client_properties.unwrap_or_default(); @@ -1183,7 +1236,7 @@ pub fn connect_namespace( session: Option, namespace_client_pushdown_operations: Option>, ) -> PyResult { - let read_consistency_interval = read_consistency_interval.map(Duration::from_secs_f64); + let read_consistency_interval = parse_read_consistency_interval(read_consistency_interval)?; let namespace_client_pushdown_operations = parse_namespace_client_pushdown_operations(namespace_client_pushdown_operations)?; diff --git a/python/src/expr.rs b/python/src/expr.rs index 79b448fdf..bb779bc1d 100644 --- a/python/src/expr.rs +++ b/python/src/expr.rs @@ -240,22 +240,60 @@ pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult { fn parse_decimal(s: &str) -> PyResult<(i128, u8, i8)> { let s = s.trim(); - let dot_pos = s.find('.'); - let scale = if let Some(pos) = dot_pos { - (s.len() - pos - 1) as i8 - } else { - 0 + let (mantissa, exponent) = match s.split_once(['e', 'E']) { + Some((mantissa, exponent)) => ( + mantissa, + exponent.parse::().map_err(|e| { + PyValueError::new_err(format!("failed to parse decimal exponent: {}", e)) + })?, + ), + None => (s, 0), }; + let fractional_digits = mantissa.find('.').map_or(0, |pos| mantissa.len() - pos - 1); + // Keep the coefficient intact instead of expanding an exponent into zeros. + // Arrow Decimal128 has at most 38 digits and an i8 scale (at most 38). + let mut scale = i64::try_from(fractional_digits) + .ok() + .and_then(|fractional_digits| fractional_digits.checked_sub(exponent)) + .and_then(|scale| i8::try_from(scale).ok()) + .filter(|scale| *scale <= 38) + .ok_or_else(|| PyValueError::new_err("decimal scale is outside Decimal128 range"))?; - let digits = s.replace('.', ""); - let val = digits + let digits = mantissa.replace('.', ""); + let mut val = digits .parse::() .map_err(|e| PyValueError::new_err(format!("failed to parse decimal digits: {}", e)))?; - // Precision is total number of digits - let precision = digits.trim_start_matches('-').len() as u8; + // Positive scale cannot exceed precision, including for tiny values such as 1E-38. + let mut precision = digits + .trim_start_matches('-') + .len() + .max(usize::try_from(scale).unwrap_or(0)); + if scale < 0 { + // Arrow cannot cast SQL text to a decimal with negative scale. Normalize + // positive exponents within Decimal128's bounded coefficient range. + if val != 0 { + let shift = -i16::from(scale) as u32; + precision += shift as usize; + if precision > 38 { + return Err(PyValueError::new_err( + "decimal precision exceeds Decimal128 maximum of 38", + )); + } + val = 10_i128 + .checked_pow(shift) + .and_then(|factor| val.checked_mul(factor)) + .ok_or_else(|| PyValueError::new_err("decimal coefficient exceeds i128 range"))?; + } + scale = 0; + } + if precision > 38 { + return Err(PyValueError::new_err( + "decimal precision exceeds Decimal128 maximum of 38", + )); + } - Ok((val, precision, scale)) + Ok((val, precision as u8, scale)) } /// Call an arbitrary registered SQL function by name. diff --git a/python/src/index.rs b/python/src/index.rs index d4e16a67e..c6c3fe17d 100644 --- a/python/src/index.rs +++ b/python/src/index.rs @@ -136,8 +136,10 @@ pub fn extract_index_params(source: &Option>) -> PyResult, - num_bits: u32, + num_bits: Option, max_iterations: u32, sample_rate: u32, target_partition_size: Option, diff --git a/python/src/job.rs b/python/src/job.rs index e22b2f897..1740b3e00 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -81,6 +81,11 @@ impl Job { self.inner.id().map(str::to_string) } + #[getter] + pub fn job_type(&self) -> Option { + self.inner.job_type() + } + pub fn status(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py( diff --git a/python/src/lib.rs b/python/src/lib.rs index 3814f2caf..71662add1 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -132,6 +132,10 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(expr_lit, m)?)?; m.add_function(wrap_pyfunction!(expr_func, m)?)?; m.add("__version__", env!("CARGO_PKG_VERSION"))?; + m.add( + "_experimental_functions_enabled", + cfg!(feature = "experimental-functions"), + )?; // Give the shared runtime a coordinated, bounded shutdown at normal // process exit -- see `shutdown_runtime` and `runtime::shutdown` for why. py.import("atexit")? diff --git a/python/src/listing.rs b/python/src/listing.rs index 2d1a3916e..79a7effdd 100644 --- a/python/src/listing.rs +++ b/python/src/listing.rs @@ -3,10 +3,11 @@ use crate::error::PythonErrorExt; use crate::runtime::future_into_py; -use futures::{StreamExt, future::poll_fn}; +use futures::{Future, StreamExt, future::poll_fn}; use lancedb::listing::{Listing, ListingOptions}; use pyo3::exceptions::PyStopAsyncIteration; -use pyo3::{Bound, PyAny, PyRef, PyResult, Python, pyclass, pymethods}; +use pyo3::types::{PyDict, PyDictMethods}; +use pyo3::{Bound, Py, PyAny, PyRef, PyResult, Python, pyclass, pymethods}; use std::sync::{Arc, Mutex}; pub fn options(page_token: Option, page_limit: Option) -> ListingOptions { @@ -52,6 +53,31 @@ impl NameListing { Ok(value) }) } + + fn next_page(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + let next_lock = self_.next_lock.clone(); + future_into_py(self_.py(), async move { + let _guard = next_lock.lock().await; + let page = futures::future::poll_fn(|cx| { + let mut inner = inner.lock().unwrap(); + let future = inner.next_page(); + futures::pin_mut!(future); + future.poll(cx) + }) + .await + .infer_error()?; + Python::attach(|py| -> PyResult>> { + page.map(|page| { + let dict = PyDict::new(py); + dict.set_item("items", page.items)?; + dict.set_item("page_token", page.page_token)?; + Ok(dict.unbind()) + }) + .transpose() + }) + }) + } } #[pyclass] diff --git a/python/src/permutation.rs b/python/src/permutation.rs index 24ca2b5a3..4e07d439e 100644 --- a/python/src/permutation.rs +++ b/python/src/permutation.rs @@ -178,6 +178,50 @@ impl PyAsyncPermutationBuilder { }) } + #[pyo3(signature = (num_samples, *, ratios=None, counts=None, fixed=None, seed=None, split_names=None))] + pub fn bootstrap_sample( + slf: PyRefMut<'_, Self>, + num_samples: u64, + ratios: Option>, + counts: Option>, + fixed: Option, + seed: Option, + split_names: Option>, + ) -> PyResult { + // Check that exactly one split type is provided + let split_args_count = [ratios.is_some(), counts.is_some(), fixed.is_some()] + .iter() + .filter(|&&x| x) + .count(); + + if split_args_count != 1 { + return Err(pyo3::exceptions::PyValueError::new_err( + "Exactly one of 'ratios', 'counts', or 'fixed' must be provided", + )); + } + + let sizes = if let Some(ratios) = ratios { + SplitSizes::Percentages(ratios) + } else if let Some(counts) = counts { + SplitSizes::Counts(counts) + } else if let Some(fixed) = fixed { + SplitSizes::Fixed(fixed) + } else { + unreachable!("One of the split arguments must be provided"); + }; + + slf.modify(|builder| { + builder.with_split_strategy( + SplitStrategy::Bootstrap { + num_samples, + sizes, + seed, + }, + split_names, + ) + }) + } + pub fn split_calculated( slf: PyRefMut<'_, Self>, calculation: String, diff --git a/python/src/query.rs b/python/src/query.rs index c9c4905c9..8687b3756 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -17,8 +17,8 @@ use arrow::pyarrow::FromPyArrow; use arrow::pyarrow::IntoPyArrow; use arrow::pyarrow::ToPyArrow; use lancedb::index::scalar::{ - BooleanQuery, BoostQuery, DocumentGranularity, FtsQuery, FullTextSearchQuery, MatchQuery, - MultiMatchQuery, Occur, Operator, PhraseQuery, + BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery, + FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery, }; use lancedb::query::AnalyzePlanDistributedMetrics; use lancedb::query::QueryBase; @@ -103,7 +103,7 @@ impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { } "PhraseQuery" => { let query = ob.getattr("query")?.extract()?; - let column = ob.getattr("column")?.extract()?; + let column = ob.getattr("column")?.extract::>()?; let slop = ob.getattr("slop")?.extract()?; let document_granularity = ob .getattr("document_granularity")? @@ -114,9 +114,7 @@ impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { }) .transpose()?; - let mut query = PhraseQuery::new(query) - .with_column(Some(column)) - .with_slop(slop); + let mut query = PhraseQuery::new(query).with_column(column).with_slop(slop); if let Some(document_granularity) = document_granularity { query = query.with_document_granularity(document_granularity); } @@ -150,6 +148,26 @@ impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { Ok(Self(q.with_operator(op).into())) } + "CombinedFieldsQuery" => { + let query = ob.getattr("query")?.extract()?; + let columns = ob.getattr("columns")?.extract()?; + let boosts: Option> = ob.getattr("boosts")?.extract()?; + let operator: String = ob.getattr("operator")?.extract()?; + + let q = CombinedFieldsQuery::try_new(query, columns) + .map_err(|e| PyValueError::new_err(format!("Invalid query: {}", e)))?; + let q = if let Some(boosts) = boosts { + q.try_with_boosts(boosts) + .map_err(|e| PyValueError::new_err(format!("Invalid boosts: {}", e)))? + } else { + q + }; + + let op = Operator::try_from(operator.as_str()) + .map_err(|e| PyValueError::new_err(format!("Invalid operator: {}", e)))?; + + Ok(Self(q.with_operator(op).into())) + } "BooleanQuery" => { let queries: Vec<(String, Self)> = ob.getattr("queries")?.extract()?; let mut sub_queries = Vec::with_capacity(queries.len()); @@ -180,9 +198,6 @@ impl<'py> IntoPyObject<'py> for PyLanceDB { .expect("Failed to import namespace"); match self.0 { - FtsQuery::CombinedFields(_) => Err(PyValueError::new_err( - "Combined-fields FTS queries are not yet supported in Python", - )), FtsQuery::Match(query) => { let kwargs = PyDict::new(py); kwargs.set_item("boost", query.boost)?; @@ -213,7 +228,7 @@ impl<'py> IntoPyObject<'py> for PyLanceDB { } namespace .getattr(intern!(py, "PhraseQuery"))? - .call((query.terms, query.column.unwrap()), Some(&kwargs)) + .call((query.terms, query.column), Some(&kwargs)) } FtsQuery::Boost(query) => { let positive = Self(query.positive.as_ref().clone()).into_pyobject(py)?; @@ -238,6 +253,18 @@ impl<'py> IntoPyObject<'py> for PyLanceDB { .getattr(intern!(py, "MultiMatchQuery"))? .call((first.terms.clone(), columns), Some(&kwargs)) } + FtsQuery::CombinedFields(query) => { + let (columns, boosts): (Vec<_>, Vec<_>) = query + .weighted_columns() + .map(|(column, boost)| (column.to_string(), boost)) + .unzip(); + let kwargs = PyDict::new(py); + kwargs.set_item("boosts", boosts)?; + kwargs.set_item::<_, &str>("operator", query.operator().into())?; + namespace + .getattr(intern!(py, "CombinedFieldsQuery"))? + .call((query.terms(), columns), Some(&kwargs)) + } FtsQuery::Boolean(query) => { let mut queries: Vec<(&str, Bound<'py, PyAny>)> = Vec::with_capacity( query.should.len() + query.must.len() + query.must_not.len(), @@ -379,7 +406,7 @@ impl From for PyQueryRequest { refine_factor: None, distance_type: None, bypass_vector_index: None, - postfilter: None, + postfilter: (!query_request.prefilter).then_some(true), norm: None, order_by: query_request .order_by diff --git a/python/src/table.rs b/python/src/table.rs index e3d7d8e66..e7e72bd73 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use lancedb::table::computed_columns::ComputedColumnOptions; use std::{ collections::HashMap, sync::{ @@ -23,11 +24,13 @@ use arrow::{ ffi_stream::ArrowArrayStreamReader, pyarrow::{FromPyArrow, PyArrowType, ToPyArrow}, }; -use lancedb::blob::{BlobFile, BlobRangeRequest}; +use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest}; +use lancedb::connection::LanceFileVersion; use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ - AddDataMode, ColumnAlteration, Duration, FieldMetadataUpdate, FtsToken as LanceDbFtsToken, - NewColumnTransform, OptimizeAction, OptimizeOptions, Ref, Table as LanceDbTable, + AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration, + FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform, + OptimizeAction, OptimizeOptions, Ref, Table as LanceDbTable, }; use lancedb::tokenize as lancedb_tokenize; use pyo3::{ @@ -106,6 +109,136 @@ enum PredicateArg { Sql(String), } +fn validate_positive_u32(value: u64, name: &str) -> PyResult { + if !(1..=u32::MAX as u64).contains(&value) { + return Err(PyValueError::new_err(format!( + "{name} must be between 1 and {}", + u32::MAX + ))); + } + Ok(value as usize) +} + +fn positive_u32(value: &Bound<'_, PyAny>, name: &str) -> PyResult { + validate_positive_u32(value.extract()?, name) +} + +fn optional_positive_u32(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + value + .extract::>()? + .map(|value| validate_positive_u32(value, name)) + .transpose() +} + +fn optional_positive_usize(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + let value: Option = value.extract()?; + if value == Some(0) { + return Err(PyValueError::new_err(format!( + "{name} must be greater than 0" + ))); + } + Ok(value) +} + +fn optional_positive_u64(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + let value: Option = value.extract()?; + if value == Some(0) { + return Err(PyValueError::new_err(format!( + "{name} must be greater than 0" + ))); + } + Ok(value) +} + +fn u32_list(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + value + .extract::>()? + .into_iter() + .map(|value| { + u32::try_from(value).map_err(|_| { + PyValueError::new_err(format!( + "{name} must contain values between 0 and {}", + u32::MAX + )) + }) + }) + .collect() +} + +fn optional_i64_bounded_u64(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + let value: Option = value.extract()?; + if value.is_some_and(|value| value > i64::MAX as u64) { + return Err(PyValueError::new_err(format!( + "{name} must be at most {}", + i64::MAX + ))); + } + Ok(value) +} + +fn parse_compaction_options(options: Option<&Bound<'_, PyDict>>) -> PyResult { + let mut parsed = CompactionOptions::default(); + let Some(options) = options else { + return Ok(parsed); + }; + + for (key, value) in options.iter() { + let key: String = key.extract()?; + match key.as_str() { + "target_rows_per_fragment" => { + parsed.target_rows_per_fragment = positive_u32(&value, &key)? + } + "max_rows_per_group" => parsed.max_rows_per_group = positive_u32(&value, &key)?, + "max_bytes_per_file" => parsed.max_bytes_per_file = value.extract()?, + "materialize_deletions" => parsed.materialize_deletions = value.extract()?, + "materialize_deletions_threshold" => { + parsed.materialize_deletions_threshold = value.extract()? + } + "num_threads" => parsed.num_threads = optional_positive_usize(&value, &key)?, + "batch_size" => parsed.batch_size = optional_positive_u32(&value, &key)?, + "io_buffer_size" => parsed.io_buffer_size = optional_i64_bounded_u64(&value, &key)?, + "defer_index_remap" => parsed.defer_index_remap = value.extract()?, + "index_remap_mode" => { + let mode: String = value.extract()?; + parsed.index_remap_mode = IndexRemapMode::try_from(mode.as_str()) + .map_err(|err| PyValueError::new_err(err.to_string()))?; + } + "compaction_mode" => { + let mode: Option = value.extract()?; + parsed.compaction_mode = mode + .map(|mode| { + CompactionMode::try_from(mode.as_str()) + .map_err(|err| PyValueError::new_err(err.to_string())) + }) + .transpose()?; + } + "binary_copy_read_batch_bytes" => { + parsed.binary_copy_read_batch_bytes = value.extract()? + } + "max_source_fragments" => parsed.max_source_fragments = value.extract()?, + "max_source_rows" => parsed.max_source_rows = optional_positive_usize(&value, &key)?, + "max_source_bytes" => parsed.max_source_bytes = optional_positive_u64(&value, &key)?, + "excluded_fragment_ids" => parsed.excluded_fragment_ids = u32_list(&value, &key)?, + "max_overlays_per_fragment" => parsed.max_overlays_per_fragment = value.extract()?, + "data_storage_version" => { + let version: String = value.extract()?; + parsed.data_storage_version = Some( + version + .parse::() + .map_err(|err| PyValueError::new_err(err.to_string()))?, + ); + } + _ => { + return Err(PyValueError::new_err(format!( + "Invalid compaction option: {key}" + ))); + } + } + } + + Ok(parsed) +} + /// Statistics about a compaction operation. #[pyclass(get_all, from_py_object)] #[derive(Clone, Debug)] @@ -561,9 +694,9 @@ impl From for FunctionErrors { #[pyclass(get_all, from_py_object)] #[derive(Clone, Debug)] pub struct RefreshMaterializedViewResult { - pub mode: String, - pub rows_written: u64, - pub source_version: u64, + pub mode: Option, + pub rows_written: Option, + pub source_version: Option, pub version: u64, } @@ -583,18 +716,23 @@ impl RefreshMaterializedViewResult { pub fn __repr__(&self) -> String { format!( "RefreshMaterializedViewResult(mode={}, rows_written={}, source_version={}, version={})", - self.mode, self.rows_written, self.source_version, self.version + self.mode.as_deref().unwrap_or("None"), + self.rows_written + .map_or_else(|| "None".into(), |value| value.to_string()), + self.source_version + .map_or_else(|| "None".into(), |value| value.to_string()), + self.version ) } } impl From for RefreshMaterializedViewResult { fn from(result: lancedb::RefreshMaterializedViewResult) -> Self { - let mode = match result.mode { + let mode = result.mode.map(|mode| match mode { lancedb::RefreshMode::Rebuild => "rebuild", - }; + }); Self { - mode: mode.to_string(), + mode: mode.map(str::to_string), rows_written: result.rows_written, source_version: result.source_version, version: result.version, @@ -1133,7 +1271,9 @@ impl Table { train: Option, ) -> PyResult> { let index = extract_index_params(&index)?; - let timeout = wait_timeout.map(|t| t.extract::().unwrap()); + let timeout = wait_timeout + .map(|t| t.extract::()) + .transpose()?; let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); @@ -1164,7 +1304,9 @@ impl Table { train: Option, ) -> PyResult> { let index = extract_index_params(&index)?; - let timeout = wait_timeout.map(|t| t.extract::().unwrap()); + let timeout = wait_timeout + .map(|t| t.extract::()) + .transpose()?; let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); @@ -1427,8 +1569,8 @@ impl Table { }) } - pub fn query(&self) -> Query { - Query::new(self.inner_ref().unwrap().query()) + pub fn query(&self) -> PyResult { + Ok(Query::new(self.inner_ref()?.query())) } #[getter] @@ -1546,14 +1688,33 @@ impl Table { }) } + #[pyo3(signature = (descriptor))] + pub fn open_blob_file<'py>( + self_: PyRef<'py, Self>, + descriptor: &str, + ) -> PyResult> { + let descriptor: BlobDescriptor = serde_json::from_str(descriptor) + .map_err(|error| PyValueError::new_err(format!("invalid blob descriptor: {error}")))?; + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let file = inner.open_blob_file(&descriptor).await.infer_error()?; + Ok(PyBlobFile { + inner: Arc::new(file), + closed: AtomicBool::new(false), + }) + }) + } + /// Optimize the on-disk data by compacting and pruning old data, for better performance. - #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None))] - pub fn optimize( - self_: PyRef<'_, Self>, + #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None))] + pub fn optimize<'py>( + self_: PyRef<'py, Self>, cleanup_since_ms: Option, delete_unverified: Option, - ) -> PyResult> { + compaction_options: Option<&Bound<'py, PyDict>>, + ) -> PyResult> { let inner = self_.inner_ref()?.clone(); + let compaction_options = parse_compaction_options(compaction_options)?; let older_than = if let Some(ms) = cleanup_since_ms { if ms > i64::MAX as u64 { return Err(PyValueError::new_err(format!( @@ -1569,7 +1730,7 @@ impl Table { future_into_py(self_.py(), async move { let compaction_stats = inner .optimize(OptimizeAction::Compact { - options: lancedb::table::CompactionOptions::default(), + options: compaction_options, remap_options: None, }) .await @@ -1764,7 +1925,8 @@ impl Table { inner .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "uses_v2_manifest_paths is not supported for remote tables.".into(), + message: "uses_v2_manifest_paths is not supported in LanceDB Distributed." + .into(), }) .infer_error()? .uses_v2_manifest_paths() @@ -1779,7 +1941,8 @@ impl Table { inner .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "migrate_manifest_paths_v2 is not supported for remote tables.".into(), + message: "migrate_manifest_paths_v2 is not supported in LanceDB Distributed." + .into(), }) .infer_error()? .migrate_manifest_paths_v2() @@ -1806,35 +1969,59 @@ impl Table { }) } + #[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] pub fn add_computed_columns( self_: PyRef<'_, Self>, columns: Vec<(String, String)>, + auto_refresh_enabled: Option, + auto_refresh_interval_seconds: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); + let options = ComputedColumnOptions { + auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), + auto_refresh_interval_seconds, + }; + options.validate().infer_error()?; future_into_py(self_.py(), async move { let mut builder = inner.add_columns(); for (name, expression) in columns { builder = builder.computed(name, expression); } - let result = builder.execute().await.infer_error()?; + let result = builder + .computed_options(options) + .execute() + .await + .infer_error()?; Ok(AddColumnsResult::from(result)) }) } + #[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] pub fn add_function_columns( self_: PyRef<'_, Self>, application_json: String, output_name: Option, + auto_refresh_enabled: Option, + auto_refresh_interval_seconds: Option, ) -> PyResult> { let application = lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?; let inner = self_.inner_ref()?.clone(); + let options = ComputedColumnOptions { + auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), + auto_refresh_interval_seconds, + }; + options.validate().infer_error()?; future_into_py(self_.py(), async move { let builder = match output_name { Some(name) => inner.add_columns().function_as(name, application), None => inner.add_columns().function(application), }; - let result = builder.execute().await.infer_error()?; + let result = builder + .computed_options(options) + .execute() + .await + .infer_error()?; Ok(AddColumnsResult::from(result)) }) } @@ -1877,17 +2064,18 @@ impl Table { }) } - #[pyo3(signature = (source_version=None))] + #[pyo3(signature = (source_version=None, *, full=false))] pub fn refresh_materialized_view( self_: PyRef<'_, Self>, source_version: Option, + full: bool, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let view = lancedb::MaterializedView::from_table(inner) .await .infer_error()?; - let mut builder = view.refresh(); + let mut builder = view.refresh().full(full); if let Some(version) = source_version { builder = builder.source_version(version); } @@ -1896,17 +2084,18 @@ impl Table { }) } - #[pyo3(signature = (source_version=None))] + #[pyo3(signature = (source_version=None, *, full=false))] pub fn refresh_materialized_view_async( self_: PyRef<'_, Self>, source_version: Option, + full: bool, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let view = lancedb::MaterializedView::from_table(inner) .await .infer_error()?; - let mut builder = view.refresh(); + let mut builder = view.refresh().full(full); if let Some(version) = source_version { builder = builder.source_version(version); } diff --git a/python/uv.lock b/python/uv.lock index ace8b98b9..9101dba74 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -443,11 +443,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.6.17" +version = "2026.10.19" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c9/c7/424b75da314c1045981bd9777432fad05a9e0c69daa4ed7e308bbaffe405/certifi-2026.6.17.tar.gz", hash = "sha256:024c88eeec92ca068db80f02b8b07c9cef7b9fe261d1d535abfd5abd6f6af432", size = 134594, upload-time = "2026-06-17T10:31:07.894Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ef/2f/c5464532e965badff2f4c4c1a3a83f5697f0d7c407ed0cda44aaa99bb451/certifi-2026.6.17-py3-none-any.whl", hash = "sha256:2227dcbaafe0d2f59279d1762ddddc37783ed4354594f194ffc31d20f41fc3db", size = 133289, upload-time = "2026-06-17T10:31:06.348Z" }, + { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, ] [[package]] @@ -799,7 +799,7 @@ name = "cuda-bindings" version = "13.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cuda-pathfinder", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "cuda-pathfinder" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/a9/21/8464d133752951c154feafb3b65c297e7d80f301183d220bec4c830f1441/cuda_bindings-13.3.1-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:120fcc53d57903df529c3486962c56528cba5b7d6c57c99537320ed9922c8b86", size = 6073403, upload-time = "2026-05-29T23:11:36.22Z" }, @@ -834,37 +834,37 @@ wheels = [ [package.optional-dependencies] cublas = [ - { name = "nvidia-cublas", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cublas" }, ] cudart = [ - { name = "nvidia-cuda-runtime", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cuda-runtime" }, ] cufft = [ - { name = "nvidia-cufft", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cufft" }, ] cufile = [ - { name = "nvidia-cufile", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cufile" }, ] cupti = [ - { name = "nvidia-cuda-cupti", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cuda-cupti" }, ] curand = [ - { name = "nvidia-curand", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-curand" }, ] cusolver = [ - { name = "nvidia-cusolver", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cusolver" }, ] cusparse = [ - { name = "nvidia-cusparse", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cusparse" }, ] nvjitlink = [ - { name = "nvidia-nvjitlink", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-nvjitlink" }, ] nvrtc = [ - { name = "nvidia-cuda-nvrtc", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cuda-nvrtc" }, ] nvtx = [ - { name = "nvidia-nvtx", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-nvtx" }, ] [[package]] @@ -1023,7 +1023,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -1440,16 +1440,16 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "cachetools", marker = "python_full_version < '3.11'" }, - { name = "certifi", marker = "python_full_version < '3.11'" }, - { name = "httpx", marker = "python_full_version < '3.11'" }, - { name = "ibm-cos-sdk", marker = "python_full_version < '3.11'" }, - { name = "lomond", marker = "python_full_version < '3.11'" }, - { name = "packaging", marker = "python_full_version < '3.11'" }, - { name = "pandas", version = "2.2.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "requests", marker = "python_full_version < '3.11'" }, - { name = "tabulate", marker = "python_full_version < '3.11'" }, - { name = "urllib3", marker = "python_full_version < '3.11'" }, + { name = "cachetools" }, + { name = "certifi" }, + { name = "httpx" }, + { name = "ibm-cos-sdk" }, + { name = "lomond" }, + { name = "packaging" }, + { name = "pandas", version = "2.2.3", source = { registry = "https://pypi.org/simple" } }, + { name = "requests" }, + { name = "tabulate" }, + { name = "urllib3" }, ] sdist = { url = "https://files.pythonhosted.org/packages/c7/56/2e3df38a1f13062095d7bde23c87a92f3898982993a15186b1bfecbd206f/ibm_watsonx_ai-1.3.42.tar.gz", hash = "sha256:ee5be59009004245d957ce97d1227355516df95a2640189749487614fef674ff", size = 688651, upload-time = "2025-10-01T13:35:41.527Z" } wheels = [ @@ -1468,17 +1468,17 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "cachetools", marker = "python_full_version >= '3.11'" }, - { name = "certifi", marker = "python_full_version >= '3.11'" }, - { name = "httpx", marker = "python_full_version >= '3.11'" }, - { name = "ibm-cos-sdk", marker = "python_full_version >= '3.11'" }, - { name = "lomond", marker = "python_full_version >= '3.11'" }, - { name = "packaging", marker = "python_full_version >= '3.11'" }, - { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, + { name = "cachetools" }, + { name = "certifi" }, + { name = "httpx" }, + { name = "ibm-cos-sdk" }, + { name = "lomond" }, + { name = "packaging" }, + { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14'" }, { name = "pandas", version = "3.0.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, - { name = "requests", marker = "python_full_version >= '3.11'" }, - { name = "tabulate", marker = "python_full_version >= '3.11'" }, - { name = "urllib3", marker = "python_full_version >= '3.11'" }, + { name = "requests" }, + { name = "tabulate" }, + { name = "urllib3" }, ] sdist = { url = "https://files.pythonhosted.org/packages/29/a3/c756b534696ab2f3f29882fdb7ca7198b7a5c94e10c0a3a327853d6d6b79/ibm_watsonx_ai-1.5.14.tar.gz", hash = "sha256:a756488bd57e87c0fc51be42dcba871143cfe0ac1e805c497c5047e1e4f13e9d", size = 735804, upload-time = "2026-06-22T12:32:43.85Z" } wheels = [ @@ -1554,17 +1554,17 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "colorama", marker = "python_full_version < '3.11' and sys_platform == 'win32'" }, - { name = "decorator", marker = "python_full_version < '3.11'" }, - { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, - { name = "jedi", marker = "python_full_version < '3.11'" }, - { name = "matplotlib-inline", marker = "python_full_version < '3.11'" }, - { name = "pexpect", marker = "python_full_version < '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "prompt-toolkit", marker = "python_full_version < '3.11'" }, - { name = "pygments", marker = "python_full_version < '3.11'" }, - { name = "stack-data", marker = "python_full_version < '3.11'" }, - { name = "traitlets", marker = "python_full_version < '3.11'" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "decorator" }, + { name = "exceptiongroup" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/40/18/f8598d287006885e7136451fdea0755af4ebcbfe342836f24deefaed1164/ipython-8.39.0.tar.gz", hash = "sha256:4110ae96012c379b8b6db898a07e186c40a2a1ef5d57a7fa83166047d9da7624", size = 5513971, upload-time = "2026-03-27T10:02:13.94Z" } wheels = [ @@ -1583,18 +1583,18 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "colorama", marker = "python_full_version >= '3.11' and sys_platform == 'win32'" }, - { name = "decorator", marker = "python_full_version >= '3.11'" }, - { name = "ipython-pygments-lexers", marker = "python_full_version >= '3.11'" }, - { name = "jedi", marker = "python_full_version >= '3.11'" }, - { name = "matplotlib-inline", marker = "python_full_version >= '3.11'" }, - { name = "pexpect", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "prompt-toolkit", marker = "python_full_version >= '3.11'" }, - { name = "psutil", marker = "python_full_version >= '3.11' and sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, - { name = "pygments", marker = "python_full_version >= '3.11'" }, - { name = "stack-data", marker = "python_full_version >= '3.11'" }, - { name = "traitlets", marker = "python_full_version >= '3.11'" }, - { name = "typing-extensions", marker = "python_full_version == '3.11.*'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "decorator" }, + { name = "ipython-pygments-lexers" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "psutil", marker = "sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, + { name = "typing-extensions", marker = "python_full_version < '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/53/59/165d3b4d75cc34add3122c4417ecb229085140ac573103c223cd01dde96f/ipython-9.15.0.tar.gz", hash = "sha256:da2819ce2aa83135257df830660b1176d986c3d2876db24df01974fa955b2756", size = 4442580, upload-time = "2026-06-26T11:03:35.913Z" } wheels = [ @@ -1606,7 +1606,7 @@ name = "ipython-pygments-lexers" version = "1.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pygments", marker = "python_full_version >= '3.11'" }, + { name = "pygments" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" } wheels = [ @@ -1854,9 +1854,9 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "lance-namespace-urllib3-client" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c0/e7/d5d46594678ee479c0eda830c47b2f5c46133bd100e84e9aa6e01306eca7/lance_namespace-0.13.0.tar.gz", hash = "sha256:24554a0997bdb39595c6e4cb3ac6722069f6cd3bd1a74e7acbba7bfaf774a40d", size = 11636, upload-time = "2026-09-14T02:47:03.871523Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c0/e7/d5d46594678ee479c0eda830c47b2f5c46133bd100e84e9aa6e01306eca7/lance_namespace-0.13.0.tar.gz", hash = "sha256:24554a0997bdb39595c6e4cb3ac6722069f6cd3bd1a74e7acbba7bfaf774a40d", size = 11636, upload-time = "2026-09-14T02:47:03.871Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e7/47/cfa33cca1ba7c749fd2918cfc5c8ded788f378cc6424d23e4fead5a14125/lance_namespace-0.13.0-py3-none-any.whl", hash = "sha256:438c7b17aef421c21c138196e715f2510d62f07e865372047f87c1e75e618c7a", size = 13507, upload-time = "2026-09-14T02:47:01.765655Z" }, + { url = "https://files.pythonhosted.org/packages/e7/47/cfa33cca1ba7c749fd2918cfc5c8ded788f378cc6424d23e4fead5a14125/lance_namespace-0.13.0-py3-none-any.whl", hash = "sha256:438c7b17aef421c21c138196e715f2510d62f07e865372047f87c1e75e618c7a", size = 13507, upload-time = "2026-09-14T02:47:01.765Z" }, ] [[package]] @@ -1869,9 +1869,9 @@ dependencies = [ { name = "typing-extensions" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/69/25/9aaa4a5e8999693fb0f227c2c0c4b97bd8f0539066408cdff0b89d41b2d5/lance_namespace_urllib3_client-0.13.0.tar.gz", hash = "sha256:1e8a79c6e4e6277033597fd76aa0e2f33d909ca1436c935936e9e569221f43ef", size = 238348, upload-time = "2026-09-14T02:47:04.521878Z" } +sdist = { url = "https://files.pythonhosted.org/packages/69/25/9aaa4a5e8999693fb0f227c2c0c4b97bd8f0539066408cdff0b89d41b2d5/lance_namespace_urllib3_client-0.13.0.tar.gz", hash = "sha256:1e8a79c6e4e6277033597fd76aa0e2f33d909ca1436c935936e9e569221f43ef", size = 238348, upload-time = "2026-09-14T02:47:04.521Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/60/4c/7b8f0712a7fe1b8655b711342bc4989696635a79e7027ee56ba3cae23e99/lance_namespace_urllib3_client-0.13.0-py3-none-any.whl", hash = "sha256:fb361eb4f6c7f2d1f9e92809609657b73e38241393e9c4516e12d6b6ee643a0a", size = 406848, upload-time = "2026-09-14T02:47:02.715954Z" }, + { url = "https://files.pythonhosted.org/packages/60/4c/7b8f0712a7fe1b8655b711342bc4989696635a79e7027ee56ba3cae23e99/lance_namespace_urllib3_client-0.13.0-py3-none-any.whl", hash = "sha256:fb361eb4f6c7f2d1f9e92809609657b73e38241393e9c4516e12d6b6ee643a0a", size = 406848, upload-time = "2026-09-14T02:47:02.715Z" }, ] [[package]] @@ -2006,8 +2006,8 @@ requires-dist = [ { name = "pyarrow", marker = "extra == 'tests'", specifier = "<25" }, { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, - { name = "pylance", marker = "extra == 'pylance'", specifier = ">=5.0.0b5" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==14.0.0b12" }, + { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b6" }, { 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" }, @@ -2884,7 +2884,7 @@ name = "nvidia-cudnn-cu13" version = "9.19.0.56" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "nvidia-cublas" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f1/84/26025437c1e6b61a707442184fa0c03d083b661adf3a3eecfd6d21677740/nvidia_cudnn_cu13-9.19.0.56-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:6ed29ffaee1176c612daf442e4dd6cfeb6a0caa43ddcbeb59da94953030b1be4", size = 433781201, upload-time = "2026-02-03T20:40:53.805Z" }, @@ -2896,7 +2896,7 @@ name = "nvidia-cufft" version = "12.0.0.61" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, @@ -2926,9 +2926,9 @@ name = "nvidia-cusolver" version = "12.0.4.66" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, - { name = "nvidia-cusparse", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, - { name = "nvidia-nvjitlink", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "nvidia-cublas" }, + { name = "nvidia-cusparse" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, @@ -2940,7 +2940,7 @@ name = "nvidia-cusparse" version = "12.6.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, @@ -3117,10 +3117,10 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "python-dateutil", marker = "python_full_version < '3.11'" }, - { name = "pytz", marker = "python_full_version < '3.11'" }, - { name = "tzdata", marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, + { name = "python-dateutil" }, + { name = "pytz" }, + { name = "tzdata" }, ] sdist = { url = "https://files.pythonhosted.org/packages/9c/d6/9f8431bacc2e19dca897724cd097b1bb224a6ad5433784a44b587c7c13af/pandas-2.2.3.tar.gz", hash = "sha256:4f18ba62b61d7e192368b84517265a99b4d7ee8912f8708660fb4a366cc82667", size = 4399213, upload-time = "2024-09-20T13:10:04.827Z" } wheels = [ @@ -3169,11 +3169,11 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12' or python_full_version >= '3.14'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12' and python_full_version < '3.14'" }, - { name = "python-dateutil", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, - { name = "pytz", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, - { name = "tzdata", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, + { name = "python-dateutil" }, + { name = "pytz" }, + { name = "tzdata" }, ] sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" } wheels = [ @@ -3236,9 +3236,9 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, - { name = "python-dateutil", marker = "python_full_version >= '3.14'" }, - { name = "tzdata", marker = "(python_full_version >= '3.14' and sys_platform == 'emscripten') or (python_full_version >= '3.14' and sys_platform == 'win32')" }, + { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" } }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f8/87/4341c6252d1c47b08768c3d25ac487362bf403f0313ddae4a2a26c9b1b4c/pandas-3.0.3.tar.gz", hash = "sha256:696a4a00a2a2a35d4e5deb3fc946641b96c944f02230e4f76137fe35d806c4fc", size = 4651414, upload-time = "2026-05-11T18:54:29.21Z" } wheels = [ @@ -3346,7 +3346,7 @@ name = "pexpect" version = "4.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ptyprocess", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "ptyprocess" }, ] sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } wheels = [ @@ -3938,7 +3938,7 @@ crypto = [ [[package]] name = "pylance" -version = "14.0.0b12" +version = "15.0.0b6" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -3948,12 +3948,10 @@ dependencies = [ { name = "pyarrow" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_1Ixasc/pylance-14.0.0b12-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:84350a3c5c1eea3398f4c4fad7cfe85b831d831a5e43b5ca2a783dbdb0e11969" }, - { url = "https://pypi.fury.io/lance-format/-/ver_sCEkG/pylance-14.0.0b12-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:76b386c182a6a8e7b86fbef28f84d1dd39e4626ac8681a0cf36f40a45dd7cb87" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1vdT1C/pylance-14.0.0b12-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6aa548c7937fcdfa8f1943a2d59041a42f8b500199880dbb509c7195fa253381" }, - { url = "https://pypi.fury.io/lance-format/-/ver_2fXu1V/pylance-14.0.0b12-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:79f82d6a6c50f37aab338470e3733436e6a27fbb5972d29fcf453ece56d3b3c6" }, - { url = "https://pypi.fury.io/lance-format/-/ver_24UavN/pylance-14.0.0b12-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:de0305999257002785f60169e6926896584d66f1da050bb5afd1d48c6e3d9bb9" }, - { url = "https://pypi.fury.io/lance-format/-/ver_XNynX/pylance-14.0.0b12-cp310-abi3-win_amd64.whl", hash = "sha256:4d0cdb689e898ce71e8e434d00a3b97639cea8fb97da21f1c921543be363268f" }, + { 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" }, ] [[package]] @@ -4709,10 +4707,10 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "joblib", marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "threadpoolctl", marker = "python_full_version < '3.11'" }, + { name = "joblib" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, + { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" } }, + { name = "threadpoolctl" }, ] sdist = { url = "https://files.pythonhosted.org/packages/98/c2/a7855e41c9d285dfe86dc50b250978105dce513d6e459ea66a6aeb0e1e0c/scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda", size = 7193136, upload-time = "2025-09-09T08:21:29.075Z" } wheels = [ @@ -4760,13 +4758,13 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "joblib", marker = "python_full_version >= '3.11'" }, - { name = "narwhals", marker = "python_full_version >= '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "joblib" }, + { name = "narwhals" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "scipy", version = "1.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "threadpoolctl", marker = "python_full_version >= '3.11'" }, + { name = "threadpoolctl" }, ] sdist = { url = "https://files.pythonhosted.org/packages/fa/6f/37092bdb25f712817231799fc5674d8e704066a8a70c1d2d40517e18b4ab/scikit_learn-1.9.0.tar.gz", hash = "sha256:8833266989d3a5110178a9fae30783675460724d0e1efb13b14901d2c660c557", size = 7750767, upload-time = "2026-06-02T11:54:32.706Z" } wheels = [ @@ -4810,7 +4808,7 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, ] sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214, upload-time = "2025-05-08T16:13:05.955Z" } wheels = [ @@ -4869,7 +4867,7 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, ] sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" } wheels = [ @@ -4946,7 +4944,7 @@ resolution-markers = [ "python_full_version >= '3.12' and python_full_version < '3.14'", ] dependencies = [ - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" } }, ] sdist = { url = "https://files.pythonhosted.org/packages/a7/25/c2700dfaf6442b4effaa91af24ebce5dc9d31bb4a69706313aae70d72cd0/scipy-1.18.0.tar.gz", hash = "sha256:67b2ad2ad54c72ca6d04975a9b2df8c3638c34ddd5b28738e94fc2b57929d378", size = 30774447, upload-time = "2026-06-19T15:01:43.456Z" } wheels = [ diff --git a/python/vendor/lance-arrow/Cargo.toml b/python/vendor/lance-arrow/Cargo.toml new file mode 100644 index 000000000..f5852a2c0 --- /dev/null +++ b/python/vendor/lance-arrow/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "lance-arrow" +version = "15.0.0-beta.3" +edition = "2024" +authors = ["Lance Devs "] +license = "Apache-2.0" +repository = "https://github.com/lance-format/lance" +readme = "README.md" +description = "Arrow Extension for Lance" +keywords = ["data-format", "data-science", "machine-learning", "apache-arrow", "data-analytics"] +categories = ["database-implementations"] + +[dependencies] +arrow-array.workspace = true +arrow-buffer.workspace = true +arrow-data.workspace = true +arrow-ipc = { workspace = true, features = ["zstd"] } +arrow-ord.workspace = true +arrow-schema.workspace = true +arrow-select.workspace = true +bytemuck = { version = "1", default-features = false, features = ["extern_crate_alloc"] } +bytes.workspace = true +futures.workspace = true +half = { workspace = true, features = ["std", "bytemuck"] } +lance-jsonb.workspace = true +num-traits.workspace = true +rand = { workspace = true, features = ["small_rng"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +getrandom = { version = "0.2", features = ["js"] } diff --git a/python/vendor/lance-arrow/README.lancedb.md b/python/vendor/lance-arrow/README.lancedb.md new file mode 100644 index 000000000..b0d6419fd --- /dev/null +++ b/python/vendor/lance-arrow/README.lancedb.md @@ -0,0 +1,7 @@ +This directory contains `rust/lance-arrow` from Lance tag `v15.0.0-beta.3` +(commit `2e22bb984d6cc6f5990f188cabb0b586b7bb51bc`), licensed under Apache-2.0. + +LanceDB carries a local fix in `src/lib.rs` for sliced child validity bitmaps +until a Lance release includes the fix. The patch is selected in the root +`Cargo.toml`; the rest of Lance stays on the pinned release. An explicit unsafe +block in `src/bfloat16.rs` lets this copy pass LanceDB's Rust 2024 warning gate. diff --git a/python/vendor/lance-arrow/README.md b/python/vendor/lance-arrow/README.md new file mode 100644 index 000000000..e0f129a3a --- /dev/null +++ b/python/vendor/lance-arrow/README.md @@ -0,0 +1,6 @@ +# lance-arrow + +`lance-arrow` is an internal sub-crate, containing [Apache-Arrow](https://github.com/apache/arrow-rs) +extensions used by [Lance](https://github.com/lance-format/lance). + +**Important Note**: This crate is **not intended for external usage**. diff --git a/python/vendor/lance-arrow/src/bfloat16.rs b/python/vendor/lance-arrow/src/bfloat16.rs new file mode 100644 index 000000000..1a60e5ece --- /dev/null +++ b/python/vendor/lance-arrow/src/bfloat16.rs @@ -0,0 +1,406 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! bfloat16 support for Apache Arrow. + +use std::fmt::Formatter; +use std::slice; + +use arrow_array::{Array, FixedSizeBinaryArray, builder::BooleanBufferBuilder}; +use arrow_buffer::{Buffer, MutableBuffer}; +use arrow_data::ArrayData; +use arrow_schema::{ArrowError, DataType, Field as ArrowField}; +use half::bf16; + +use crate::{ARROW_EXT_NAME_KEY, FloatArray}; + +/// The name of the bfloat16 extension in Arrow metadata +pub const BFLOAT16_EXT_NAME: &str = "lance.bfloat16"; + +/// Check whether the given field is a bfloat16 field +/// +/// A field is a bfloat16 field if it has a data type of `FixedSizeBinary(2)` and the metadata +/// contains the bfloat16 extension name. +pub fn is_bfloat16_field(field: &ArrowField) -> bool { + field.data_type() == &DataType::FixedSizeBinary(2) + && field + .metadata() + .get(ARROW_EXT_NAME_KEY) + .map(|name| name == BFLOAT16_EXT_NAME) + .unwrap_or_default() +} + +/// The bfloat16 data type +/// +/// This implements the [`ArrowFloatType`](crate::floats::ArrowFloatType) trait for bfloat16 values. +#[derive(Debug)] +pub struct BFloat16Type {} + +/// An array of bfloat16 values +/// +/// Note that bfloat16 is not the same thing as fp16 which is supported natively by arrow-rs. +#[derive(Clone)] +pub struct BFloat16Array { + inner: FixedSizeBinaryArray, +} + +impl std::fmt::Debug for BFloat16Array { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "BFloat16Array\n[\n")?; + from_arrow::print_long_array(&self.inner, f, |array, i, f| { + if array.is_null(i) { + write!(f, "null") + } else { + let binary_values = array.value(i); + let value = + bf16::from_bits(u16::from_le_bytes([binary_values[0], binary_values[1]])); + write!(f, "{:?}", value) + } + })?; + write!(f, "]") + } +} + +impl BFloat16Array { + pub fn from_iter_values(iter: impl IntoIterator) -> Self { + let values: Vec = iter.into_iter().collect(); + values.into() + } + + pub fn len(&self) -> usize { + self.inner.len() + } + + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + pub fn is_null(&self, i: usize) -> bool { + self.inner.is_null(i) + } + + pub fn null_count(&self) -> usize { + self.inner.null_count() + } + + pub fn iter(&self) -> BFloat16Iter<'_> { + BFloat16Iter { + array: self, + index: 0, + } + } + + pub fn value(&self, i: usize) -> bf16 { + assert!( + i < self.len(), + "Trying to access an element at index {} from a BFloat16Array of length {}", + i, + self.len() + ); + // Safety: + // `i < self.len() + unsafe { self.value_unchecked(i) } + } + + /// # Safety + /// Caller must ensure that `i < self.len()` + pub unsafe fn value_unchecked(&self, i: usize) -> bf16 { + // SAFETY: the caller guarantees that `i` is within this array's bounds. + let binary_value = unsafe { self.inner.value_unchecked(i) }; + bf16::from_bits(u16::from_le_bytes([binary_value[0], binary_value[1]])) + } + + pub fn into_inner(self) -> FixedSizeBinaryArray { + self.inner + } +} + +impl FromIterator> for BFloat16Array { + fn from_iter>>(iter: I) -> Self { + let mut buffer = MutableBuffer::new(10); + // No null buffer builder :( + let mut nulls = BooleanBufferBuilder::new(10); + let mut len = 0; + + for maybe_value in iter { + if let Some(value) = maybe_value { + let bytes = value.to_le_bytes(); + buffer.extend(bytes); + } else { + buffer.extend([0u8, 0u8]); + } + nulls.append(maybe_value.is_some()); + len += 1; + } + + let null_buffer = nulls.finish(); + let num_valid = null_buffer.count_set_bits(); + let null_buffer = if num_valid == len { + None + } else { + Some(null_buffer.into_inner()) + }; + + let array_data = ArrayData::builder(DataType::FixedSizeBinary(2)) + .len(len) + .add_buffer(buffer.into()) + .null_bit_buffer(null_buffer); + // SAFETY: the value buffer contains exactly `2 * len` bytes (two bytes + // pushed per iteration of the loop above, including the zero-fill for + // null slots), which matches the `FixedSizeBinary(2)` storage layout. + // The null bit buffer, when present, has `len` bits appended above, so + // its length covers the array's logical range. + let array_data = unsafe { array_data.build_unchecked() }; + Self { + inner: FixedSizeBinaryArray::from(array_data), + } + } +} + +impl FromIterator for BFloat16Array { + fn from_iter>(iter: I) -> Self { + Self::from_iter_values(iter) + } +} + +impl From> for BFloat16Array { + fn from(data: Vec) -> Self { + let len = data.len(); + // Zero-copy: `bf16` is `#[repr(transparent)]` over `u16` and derives + // `bytemuck::Pod`, so `cast_vec` reinterprets the allocation in place — + // no per-element copy or heap alloc. The crate-root `compile_error!` + // pins `target_endian = "little"`, so the resulting bytes match the + // `FixedSizeBinary(2)` on-disk order Lance writes elsewhere. + let raw: Vec = bytemuck::cast_vec(data); + let array_data = ArrayData::builder(DataType::FixedSizeBinary(2)) + .len(len) + .add_buffer(Buffer::from_vec(raw)); + // SAFETY: the value buffer contains exactly `2 * len` bytes — one + // `u16` per element after the layout-compatible cast — matching the + // `FixedSizeBinary(2)` storage layout. No null buffer is attached, so + // every element is logically valid. + let array_data = unsafe { array_data.build_unchecked() }; + Self { + inner: FixedSizeBinaryArray::from(array_data), + } + } +} + +impl TryFrom for BFloat16Array { + type Error = ArrowError; + + fn try_from(value: FixedSizeBinaryArray) -> Result { + if value.value_length() == 2 { + Ok(Self { inner: value }) + } else { + Err(ArrowError::InvalidArgumentError( + "FixedSizeBinaryArray must have a value length of 2".to_string(), + )) + } + } +} + +impl PartialEq for BFloat16Array { + fn eq(&self, other: &Self) -> bool { + self.inner.eq(&other.inner) + } +} + +pub struct BFloat16Iter<'a> { + array: &'a BFloat16Array, + index: usize, +} + +impl<'a> Iterator for BFloat16Iter<'a> { + type Item = Option; + + fn next(&mut self) -> Option { + if self.index >= self.array.len() { + return None; + } + let i = self.index; + self.index += 1; + if self.array.is_null(i) { + Some(None) + } else { + Some(Some(self.array.value(i))) + } + } +} + +/// Methods that are lifted from arrow-rs temporarily until they are made public. +mod from_arrow { + use arrow_array::Array; + + /// Helper function for printing potentially long arrays. + pub(super) fn print_long_array( + array: &A, + f: &mut std::fmt::Formatter, + print_item: F, + ) -> std::fmt::Result + where + A: Array, + F: Fn(&A, usize, &mut std::fmt::Formatter) -> std::fmt::Result, + { + let head = std::cmp::min(10, array.len()); + + for i in 0..head { + if array.is_null(i) { + writeln!(f, " null,")?; + } else { + write!(f, " ")?; + print_item(array, i, f)?; + writeln!(f, ",")?; + } + } + if array.len() > 10 { + if array.len() > 20 { + writeln!(f, " ...{} elements...,", array.len() - 20)?; + } + + let tail = std::cmp::max(head, array.len() - 10); + + for i in tail..array.len() { + if array.is_null(i) { + writeln!(f, " null,")?; + } else { + write!(f, " ")?; + print_item(array, i, f)?; + writeln!(f, ",")?; + } + } + } + Ok(()) + } +} + +impl FloatArray for FixedSizeBinaryArray { + type FloatType = BFloat16Type; + + /// Returns the underlying `bf16` values as a borrowed slice. + /// + /// # Preconditions + /// + /// - `value_length()` must be 2 (the `FixedSizeBinary(2)` storage shape + /// used by [`BFloat16Array`]). Asserted at entry. + /// - The value buffer must be at least 2-byte aligned. Lance's in-tree + /// constructors always satisfy this: value buffers are built either via + /// `MutableBuffer` (aligned to arrow-buffer's `ALIGNMENT` constant, ≥32 + /// bytes) or via `Buffer::from_vec::` (aligned to `align_of::()` + /// == 2); both meet `bf16`'s 2-byte requirement. Externally-built + /// `FixedSizeBinaryArray`s arriving via FFI, IPC, or + /// `Buffer::from_custom_allocation` are not required by arrow-rs to be + /// aligned beyond a single byte; passing one to this method violates the + /// precondition. A `debug_assert` below catches such inputs in debug and + /// test builds. + /// + /// # Endianness + /// + /// `lance-arrow` is gated on `target_endian = "little"` at the crate root, + /// so this method always returns values in the same byte order Lance writes + /// (see [`BFloat16Array::value`] and the [`FromIterator`] impls). + fn as_slice(&self) -> &[bf16] { + assert_eq!( + self.value_length(), + 2, + "BFloat16 arrays must use FixedSizeBinary(2) storage" + ); + debug_assert_eq!( + (self.value_data().as_ptr() as usize) % std::mem::align_of::(), + 0, + "BFloat16 value buffer must be at least 2-byte aligned" + ); + // SAFETY: + // - The assert above pins `value_size == 2`, so `value_data().len() / 2` + // equals the array's logical element count. + // `FixedSizeBinaryArray::From` constructs its value buffer + // as `buffers[0].slice_with_length(offset * 2, len * 2)` (arrow-array + // `fixed_size_binary_array.rs`), so `value_data()` already returns + // the offset-adjusted slice. Do not replace `value_data()` with an + // accessor that returns the un-sliced backing buffer. + // - `bf16` is `#[repr(transparent)]` over `u16` (size 2, alignment 2); + // every `u16` bit pattern is a valid `bf16`, so any byte content + // yields a defined value — never UB. + // - Alignment is the caller's responsibility per the precondition + // documented above. The `debug_assert_eq!` immediately preceding this + // block catches violations in debug and test builds only — release + // builds rely on callers honoring the precondition. arrow-rs + // declares `FixedSizeBinary(n)`'s + // `BufferSpec::FixedWidth { alignment: align_of::() == 1 }` + // (arrow-data `data.rs`), so arrow-rs alone does not guarantee + // 2-byte alignment. Lance's in-tree construction paths build value + // buffers via `MutableBuffer` (arrow-buffer `ALIGNMENT` constant, + // ≥32 bytes) or `Buffer::from_vec::` (2-byte aligned), both of + // which satisfy `bf16`'s 2-byte requirement. + // - The returned slice borrows from `self`; the underlying ref-counted, + // immutable Arrow buffer cannot be mutated or freed for the slice's + // lifetime. + unsafe { + slice::from_raw_parts( + self.value_data().as_ptr() as *const bf16, + self.value_data().len() / 2, + ) + } + } + + fn from_values(values: Vec) -> Self { + BFloat16Array::from(values).into_inner() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_basics() { + let values: Vec = vec![1.0, 2.0, 3.0]; + let values: Vec = values.iter().map(|v| bf16::from_f32(*v)).collect(); + + let array = BFloat16Array::from_iter_values(values.clone()); + let array2 = BFloat16Array::from(values.clone()); + assert_eq!(array, array2); + assert_eq!(array.len(), 3); + + // Pin the raw little-endian bytes emitted by `From>` (rewritten to + // reinterpret the Vec via `bytemuck::cast_vec`), so a layout/byte-order + // regression is caught directly rather than only through Debug formatting. + // bf16 is the high 16 bits of the f32: 1.0->0x3F80, 2.0->0x4000, 3.0->0x4040. + let inner = array2.clone().into_inner(); + let raw_bytes: Vec = (0..inner.len()) + .flat_map(|i| inner.value(i).to_vec()) + .collect(); + assert_eq!(raw_bytes, vec![0x80, 0x3F, 0x00, 0x40, 0x40, 0x40]); + + let expected_fmt = "BFloat16Array\n[\n 1.0,\n 2.0,\n 3.0,\n]"; + assert_eq!(expected_fmt, format!("{:?}", array)); + + for (expected, value) in values.iter().zip(array.iter()) { + assert_eq!(Some(*expected), value); + } + + for (expected, value) in values.as_slice().iter().zip(array2.iter()) { + assert_eq!(Some(*expected), value); + } + + let arrow_array = array.into_inner(); + assert_eq!(arrow_array.as_slice(), values.as_slice()); + } + + #[test] + fn test_nulls() { + let values: Vec> = + vec![Some(bf16::from_f32(1.0)), None, Some(bf16::from_f32(3.0))]; + let array = BFloat16Array::from_iter(values.clone()); + assert_eq!(array.len(), 3); + assert_eq!(array.null_count(), 1); + + let expected_fmt = "BFloat16Array\n[\n 1.0,\n null,\n 3.0,\n]"; + assert_eq!(expected_fmt, format!("{:?}", array)); + + for (expected, value) in values.iter().zip(array.iter()) { + assert_eq!(*expected, value); + } + } +} diff --git a/python/vendor/lance-arrow/src/deepcopy.rs b/python/vendor/lance-arrow/src/deepcopy.rs new file mode 100644 index 000000000..5df4339b5 --- /dev/null +++ b/python/vendor/lance-arrow/src/deepcopy.rs @@ -0,0 +1,356 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::sync::Arc; + +use arrow_array::{Array, RecordBatch, make_array}; +use arrow_buffer::{BooleanBuffer, Buffer, NullBuffer}; +use arrow_data::{ArrayData, ArrayDataBuilder, transform::MutableArrayData}; +use arrow_schema::DataType; + +pub fn deep_copy_buffer(buffer: &Buffer) -> Buffer { + Buffer::from(buffer.as_slice()) +} + +pub fn deep_copy_nulls(nulls: Option<&NullBuffer>) -> Option { + let nulls = nulls?; + let bit_buffer = deep_copy_buffer(nulls.inner().inner()); + // SAFETY: `null_count` is taken from the source `NullBuffer`, which already + // upheld `NullBuffer::new_unchecked`'s invariant — the unset-bit count over + // the logical bit slice `[bit_offset, bit_offset + bit_len)`. `NullBuffer::slice` + // adjusts only `BooleanBuffer::bit_offset` / `bit_len` and never byte-advances + // the inner `Buffer`, so `deep_copy_buffer` (which copies the source `Buffer`'s + // `as_slice()` view from byte 0) reproduces the exact bit pattern at the same + // bit offsets; the unset-bit count is therefore preserved. `BooleanBuffer::new` + // panics (does not UB) if `bit_offset + bit_len > 8 * buffer.len()`, and the + // copy has the same length, so that check still passes. + Some(unsafe { + NullBuffer::new_unchecked( + BooleanBuffer::new(bit_buffer, nulls.offset(), nulls.len()), + nulls.null_count(), + ) + }) +} + +pub fn deep_copy_array_data(data: &ArrayData) -> ArrayData { + let data_type = data.data_type().clone(); + let len = data.len(); + let nulls = deep_copy_nulls(data.nulls()); + let offset = data.offset(); + let buffers = data + .buffers() + .iter() + .map(deep_copy_buffer) + .collect::>(); + let child_data = data + .child_data() + .iter() + .map(deep_copy_array_data) + .collect::>(); + // SAFETY: `build_unchecked` inherits `ArrayData::new_unchecked`'s contract — + // `(data_type, len, offset, nulls, buffers, child_data)` must form a valid + // Arrow array. This call reproduces `data` structurally: `data_type`, `len`, + // and `offset` are forwarded unchanged; each buffer is replaced by a byte- + // identical copy of its offset-applied `as_slice()` view (the output buffer + // is `MutableBuffer`-allocated, at least as aligned as the source); `nulls` + // is deep-copied with the same bit offset/length and unset-bit count (see + // `deep_copy_nulls`); `child_data` is recursively cloned with the same + // guarantee. Every value-level invariant the source upheld — UTF-8 validity, + // monotonic offsets, in-bounds dictionary indices, run-end monotonicity, + // struct child-length matching — therefore transfers to the copy. If the + // source `ArrayData` was itself constructed via `new_unchecked` with an + // invalid payload, this function faithfully reproduces that invalidity. + unsafe { + ArrayDataBuilder::new(data_type) + .len(len) + .nulls(nulls) + .offset(offset) + .buffers(buffers) + .child_data(child_data) + .build_unchecked() + } +} + +pub fn deep_copy_array(array: &dyn Array) -> Arc { + let data = array.to_data(); + let data = deep_copy_array_data(&data); + make_array(data) +} + +pub fn deep_copy_batch(batch: &RecordBatch) -> crate::Result { + let arrays = batch + .columns() + .iter() + .map(|array| deep_copy_array(array)) + .collect::>(); + RecordBatch::try_new(batch.schema(), arrays) +} + +/// Deep copy array data, extracting only the sliced portion using MutableArrayData +/// This is the most efficient and correct way to copy just the sliced data +pub fn deep_copy_array_data_sliced(data: &ArrayData) -> ArrayData { + // Use MutableArrayData to efficiently copy just the slice + let mut mutable = MutableArrayData::new(vec![data], false, data.len()); + + // Which index this takes depends on the layout, because arrow's extenders + // disagree about who applies `ArrayData::offset()`. The bit-packed one adds + // it to the raw values buffer itself, so an offset-applied index there + // reads from twice the offset and runs off the end of the buffer. Every + // other layout either reads through an already-offset-applied view or + // forwards the index to children carrying their own offsets, and takes the + // absolute index it has always been given. + let start = match data.data_type() { + DataType::Boolean => 0, + _ => data.offset(), + }; + mutable.extend(0, start, start + data.len()); + + // Freeze into immutable ArrayData + mutable.freeze() +} + +/// Deep copy an array, extracting only the sliced portion using MutableArrayData +pub fn deep_copy_array_sliced(array: &dyn Array) -> Arc { + let data = array.to_data(); + let data = deep_copy_array_data_sliced(&data); + make_array(data) +} + +/// Deep copy a RecordBatch, extracting only the sliced portion using MutableArrayData +pub fn deep_copy_batch_sliced(batch: &RecordBatch) -> crate::Result { + let arrays = batch + .columns() + .iter() + .map(|array| deep_copy_array_sliced(array)) + .collect::>(); + RecordBatch::try_new(batch.schema(), arrays) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::{Array, BooleanArray, Int32Array, RecordBatch, StringArray}; + use arrow_data::ArrayDataBuilder; + use arrow_schema::{DataType, Field, Schema}; + + #[test] + fn raw_sliced_fixed_size_list_data_keeps_its_child_offset() { + // `ArrayData::slice` records the offset on the parent and leaves the + // child whole -- a shape `FixedSizeListArray::slice` never produces, + // but a legal one this public helper can be handed directly. Arrow's + // extender forwards `start * size` to that unsliced child and adds + // nothing, so the index it gets has to be the absolute one; this is + // here to stop the boolean fix from being generalised over it. + let child = Int32Array::from(vec![10, 11, 20, 21]).to_data(); + let field = Arc::new(Field::new_list_field(DataType::Int32, false)); + let data = ArrayDataBuilder::new(DataType::FixedSizeList(field, 2)) + .len(2) + .add_child_data(child) + .build() + .unwrap(); + let sliced = data.slice(1, 1); + + let copied = super::deep_copy_array_data_sliced(&sliced); + let copied_child = Int32Array::from(copied.child_data()[0].clone()); + assert_eq!(copied_child.values().as_ref(), &[20, 21]); + } + + #[test] + fn raw_sliced_struct_of_fixed_size_list_reaches_the_right_values() { + // Slicing raw struct data pushes the window into the struct's children, + // and a fixed-size-list child takes it as its own parent offset with + // its values left whole. Two levels of offset, and the absolute index + // has to remain right through both of them. + let values = Int32Array::from(vec![10, 11, 20, 21, 30, 31]).to_data(); + let item = Arc::new(Field::new_list_field(DataType::Int32, false)); + let list = ArrayDataBuilder::new(DataType::FixedSizeList(item, 2)) + .len(3) + .add_child_data(values) + .build() + .unwrap(); + let field = Arc::new(Field::new("l", list.data_type().clone(), false)); + let data = ArrayDataBuilder::new(DataType::Struct(vec![field].into())) + .len(3) + .add_child_data(list) + .build() + .unwrap(); + let sliced = data.slice(2, 1); + + let copied = super::deep_copy_array_data_sliced(&sliced); + let copied_values = Int32Array::from(copied.child_data()[0].child_data()[0].clone()); + assert_eq!(copied_values.values().as_ref(), &[30, 31]); + } + + #[test] + fn raw_parent_offset_struct_keeps_the_selected_child_row() { + // A struct whose children are whole and whose window is the parent + // offset: arrow's struct extender forwards the index to those children + // untouched, so it has to be the absolute one. + let field = Arc::new(Field::new("a", DataType::Int32, false)); + let data = ArrayDataBuilder::new(DataType::Struct(vec![field].into())) + .len(1) + .offset(1) + .add_child_data(Int32Array::from(vec![10, 20]).to_data()) + .build() + .unwrap(); + + let copied = super::deep_copy_array_data_sliced(&data); + let copied_child = Int32Array::from(copied.child_data()[0].clone()); + assert_eq!(copied_child.values().as_ref(), &[20]); + } + + #[test] + fn sliced_boolean_deep_copy_reads_from_the_slice() { + // A boolean slice keeps its `ArrayData::offset()` -- the buffer cannot + // advance by a fraction of a byte -- so a copy that adds the offset on + // top of what `MutableArrayData` already applies reads past the end of + // the values buffer and panics. + let array = BooleanArray::from(vec![true, false, true, false, true, false, true, false]); + for (offset, len) in [(0usize, 8usize), (1, 7), (3, 5), (7, 1)] { + let sliced = array.slice(offset, len); + let copied = super::deep_copy_array_sliced(&sliced); + let copied = copied.as_any().downcast_ref::().unwrap(); + let expected: Vec = (0..len).map(|i| sliced.value(i)).collect(); + let actual: Vec = (0..len).map(|i| copied.value(i)).collect(); + assert_eq!(actual, expected, "offset={offset} len={len}"); + } + } + + #[test] + fn sliced_boolean_deep_copy_keeps_its_nulls() { + let array = BooleanArray::from(vec![ + Some(true), + None, + Some(false), + Some(true), + None, + Some(false), + ]); + let sliced = array.slice(1, 4); + let copied = super::deep_copy_array_sliced(&sliced); + let copied = copied.as_any().downcast_ref::().unwrap(); + let expected: Vec> = (0..sliced.len()) + .map(|i| (!sliced.is_null(i)).then(|| sliced.value(i))) + .collect(); + let actual: Vec> = (0..copied.len()) + .map(|i| (!copied.is_null(i)).then(|| copied.value(i))) + .collect(); + assert_eq!(actual, expected); + } + + #[test] + fn test_deep_copy_sliced_array_with_nulls() { + let array = Arc::new(Int32Array::from(vec![ + Some(1), + None, + Some(3), + None, + Some(5), + ])); + let sliced_array = array.slice(1, 3); + let copied_array = super::deep_copy_array(&sliced_array); + assert_eq!(sliced_array.len(), copied_array.len()); + assert_eq!(sliced_array.nulls(), copied_array.nulls()); + } + + #[test] + fn test_deep_copy_array_data_sliced() { + let array = Int32Array::from((0..1000).collect::>()); + let sliced = array.slice(100, 10); + + let sliced_data = sliced.to_data(); + let copied_data = super::deep_copy_array_data_sliced(&sliced_data); + + assert_eq!(copied_data.len(), 10); + assert_eq!(copied_data.offset(), 0); + + // Verify data correctness + let copied_array = Int32Array::from(copied_data); + for i in 0..10 { + assert_eq!(copied_array.value(i), 100 + i as i32); + } + } + + #[test] + fn test_deep_copy_array_sliced() { + let array = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])); + let sliced = array.slice(1, 3); + + let copied = super::deep_copy_array_sliced(&sliced); + + assert_eq!(copied.len(), 3); + let copied_int = copied.as_any().downcast_ref::().unwrap(); + assert_eq!(copied_int.value(0), 2); + assert_eq!(copied_int.value(1), 3); + assert_eq!(copied_int.value(2), 4); + } + + #[test] + fn test_deep_copy_batch_sliced() { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("name", DataType::Utf8, false), + ])); + + let id_array = Arc::new(Int32Array::from((0..100).collect::>())); + let name_array = Arc::new(StringArray::from( + (0..100) + .map(|i| format!("name_{}", i)) + .collect::>(), + )); + + let batch = RecordBatch::try_new( + schema, + vec![id_array as Arc, name_array as Arc], + ) + .unwrap(); + + let sliced = batch.slice(10, 5); + let copied = super::deep_copy_batch_sliced(&sliced).unwrap(); + + assert_eq!(copied.num_rows(), 5); + assert_eq!(copied.num_columns(), 2); + + // Verify data correctness + let id_col = copied + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let name_col = copied + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + + for i in 0..5 { + assert_eq!(id_col.value(i), 10 + i as i32); + assert_eq!(name_col.value(i), format!("name_{}", 10 + i)); + } + } + + #[test] + fn test_deep_copy_array_sliced_with_nulls() { + let array = Arc::new(Int32Array::from(vec![ + Some(1), + None, + Some(3), + None, + Some(5), + ])); + let sliced = array.slice(1, 3); // [None, Some(3), None] + + let copied = super::deep_copy_array_sliced(&sliced); + + assert_eq!(copied.len(), 3); + assert_eq!(copied.null_count(), 2); // Two nulls in the slice + + let copied_int = copied.as_any().downcast_ref::().unwrap(); + assert!(!copied_int.is_valid(0)); // None + assert!(copied_int.is_valid(1)); // Some(3) + assert!(!copied_int.is_valid(2)); // None + assert_eq!(copied_int.value(1), 3); + } +} diff --git a/python/vendor/lance-arrow/src/floats.rs b/python/vendor/lance-arrow/src/floats.rs new file mode 100644 index 000000000..0024fbb02 --- /dev/null +++ b/python/vendor/lance-arrow/src/floats.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Floats Array + +use std::fmt::{Debug, Display}; +use std::iter::Sum; +use std::sync::Arc; +use std::{ + fmt::Formatter, + ops::{AddAssign, DivAssign}, +}; + +use arrow_array::{ + Array, FixedSizeBinaryArray, Float16Array, Float32Array, Float64Array, + types::{Float16Type, Float32Type, Float64Type}, +}; +use arrow_schema::{DataType, Field}; +use half::{bf16, f16}; +use num_traits::{AsPrimitive, Bounded, Float, FromPrimitive}; + +use super::bfloat16::{BFloat16Array, BFloat16Type}; +use crate::Result; +use crate::bfloat16::is_bfloat16_field; + +/// Float data type. +/// +/// This helps differentiate between the different float types, +/// because bf16 is not officially supported [DataType] in arrow-rs. +#[derive(Debug)] +pub enum FloatType { + BFloat16, + Float16, + Float32, + Float64, +} + +impl std::fmt::Display for FloatType { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + Self::BFloat16 => write!(f, "bfloat16"), + Self::Float16 => write!(f, "float16"), + Self::Float32 => write!(f, "float32"), + Self::Float64 => write!(f, "float64"), + } + } +} + +/// Try to convert a [DataType] to a [FloatType]. To support bfloat16, always +/// prefer using the `TryFrom<&Field>` implementation. +impl TryFrom<&DataType> for FloatType { + type Error = crate::ArrowError; + + fn try_from(value: &DataType) -> Result { + match *value { + DataType::Float16 => Ok(Self::Float16), + DataType::Float32 => Ok(Self::Float32), + DataType::Float64 => Ok(Self::Float64), + _ => Err(crate::ArrowError::InvalidArgumentError(format!( + "{:?} is not a floating type", + value + ))), + } + } +} + +impl TryFrom<&Field> for FloatType { + type Error = crate::ArrowError; + + fn try_from(field: &Field) -> Result { + match field.data_type() { + DataType::FixedSizeBinary(2) if is_bfloat16_field(field) => Ok(Self::BFloat16), + _ => Self::try_from(field.data_type()), + } + } +} + +/// Trait for float types used in Lance indexes +/// +/// This mimics the utilities provided by [`arrow_array::ArrowPrimitiveType`] +/// but applies to all float types (including bfloat16) +pub trait ArrowFloatType: Debug { + type Native: FromPrimitive + + FloatToArrayType + + AsPrimitive + + Debug + + Display; + + const FLOAT_TYPE: FloatType; + const MIN: Self::Native; + const MAX: Self::Native; + + /// Arrow Float Array Type. + type ArrayType: FloatArray; + + /// Returns empty array of this type. + fn empty_array() -> Self::ArrayType { + >::from_values(Vec::new()) + } +} + +/// Trait to be implemented by native types that have a corresponding [`ArrowFloatType`] +/// implementation. +/// +/// This helps define what operations are supported by native floats and also helps convert +/// from a native type back to the corresponding Arrow float type. +pub trait FloatToArrayType: + Float + + Bounded + + Sum + + AddAssign + + AsPrimitive + + AsPrimitive + + DivAssign + + Send + + Sync + + Copy +{ + /// The corresponding [`ArrowFloatType`] implementation for this native type + type ArrowType: ArrowFloatType; +} + +impl FloatToArrayType for bf16 { + type ArrowType = BFloat16Type; +} + +impl FloatToArrayType for f16 { + type ArrowType = Float16Type; +} + +impl FloatToArrayType for f32 { + type ArrowType = Float32Type; +} + +impl FloatToArrayType for f64 { + type ArrowType = Float64Type; +} + +impl ArrowFloatType for BFloat16Type { + type Native = bf16; + + const FLOAT_TYPE: FloatType = FloatType::BFloat16; + const MIN: Self::Native = bf16::MIN; + const MAX: Self::Native = bf16::MAX; + + type ArrayType = FixedSizeBinaryArray; +} + +impl ArrowFloatType for Float16Type { + type Native = f16; + + const FLOAT_TYPE: FloatType = FloatType::Float16; + const MIN: Self::Native = f16::MIN; + const MAX: Self::Native = f16::MAX; + + type ArrayType = Float16Array; +} + +impl ArrowFloatType for Float32Type { + type Native = f32; + + const FLOAT_TYPE: FloatType = FloatType::Float32; + const MIN: Self::Native = f32::MIN; + const MAX: Self::Native = f32::MAX; + + type ArrayType = Float32Array; +} + +impl ArrowFloatType for Float64Type { + type Native = f64; + + const FLOAT_TYPE: FloatType = FloatType::Float64; + const MIN: Self::Native = f64::MIN; + const MAX: Self::Native = f64::MAX; + + type ArrayType = Float64Array; +} + +/// [FloatArray] is a trait that is implemented by all float type arrays +/// +/// This is similar to [`arrow_array::PrimitiveArray`] but applies to all float types (including bfloat16) +/// and is implemented as a trait and not a struct +pub trait FloatArray: Array + Clone + 'static { + type FloatType: ArrowFloatType; + + /// Returns a reference to the underlying data as a slice. + /// + /// # Panics + /// + /// Implementations may panic if the array's storage shape does not match + /// the expected element layout. In particular, the `bf16` impl panics if + /// `value_length() != 2` (the `FixedSizeBinary(2)` shape required by + /// `BFloat16Array`). + /// + /// # Preconditions + /// + /// Implementations may impose additional invariants on the underlying + /// buffer. The `bf16` impl requires the value buffer to be at least + /// 2-byte aligned — satisfied automatically by every in-tree Lance + /// constructor, but external callers passing externally-built arrays + /// (FFI, IPC, `Buffer::from_custom_allocation`) must ensure alignment. + /// See the impl's docstring for details. + fn as_slice(&self) -> &[T::Native]; + + /// Construct an array from a vector of values. + fn from_values(values: Vec) -> Self; + + /// Construct an array from an iterator of values. + fn from_iter_values(values: impl IntoIterator) -> Self + where + Self: Sized, + { + Self::from_values(values.into_iter().collect()) + } +} + +impl FloatArray for Float16Array { + type FloatType = Float16Type; + + fn as_slice(&self) -> &[::Native] { + self.values() + } + + fn from_values(values: Vec<::Native>) -> Self { + Self::from(values) + } +} + +impl FloatArray for Float32Array { + type FloatType = Float32Type; + + fn as_slice(&self) -> &[::Native] { + self.values() + } + + fn from_values(values: Vec<::Native>) -> Self { + Self::from(values) + } +} + +impl FloatArray for Float64Array { + type FloatType = Float64Type; + + fn as_slice(&self) -> &[::Native] { + self.values() + } + + fn from_values(values: Vec<::Native>) -> Self { + Self::from(values) + } +} + +/// Convert a float32 array to another float array +/// +/// This is used during queries as query vectors are always provided as float32 arrays +/// and need to be converted to the appropriate float type for the index. +pub fn coerce_float_vector(input: &Float32Array, float_type: FloatType) -> Result> { + match float_type { + FloatType::BFloat16 => Ok(Arc::new( + BFloat16Array::from_iter_values(input.values().iter().map(|v| bf16::from_f32(*v))) + .into_inner(), + )), + FloatType::Float16 => Ok(Arc::new(Float16Array::from_iter_values( + input.values().iter().map(|v| f16::from_f32(*v)), + ))), + FloatType::Float32 => Ok(Arc::new(input.clone())), + FloatType::Float64 => Ok(Arc::new(Float64Array::from_iter_values( + input.values().iter().map(|v| *v as f64), + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_coerce_float_vector_bfloat16() { + let input = Float32Array::from(vec![1.0f32, 2.0, 3.0]); + let array = coerce_float_vector(&input, FloatType::BFloat16).unwrap(); + + assert_eq!(array.data_type(), &DataType::FixedSizeBinary(2)); + + let fixed = array + .as_any() + .downcast_ref::() + .unwrap(); + let expected: Vec = input.values().iter().map(|v| bf16::from_f32(*v)).collect(); + assert_eq!(fixed.as_slice(), expected.as_slice()); + } +} diff --git a/python/vendor/lance-arrow/src/ipc.rs b/python/vendor/lance-arrow/src/ipc.rs new file mode 100644 index 000000000..099c362b4 --- /dev/null +++ b/python/vendor/lance-arrow/src/ipc.rs @@ -0,0 +1,621 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Zero-copy Arrow IPC stream read/write utilities. +//! +//! Provides helpers for serializing and deserializing [`RecordBatch`]es as +//! self-delimiting Arrow IPC streams using synchronous [`Read`]/[`Write`] I/O. +//! +//! These are designed for embedding IPC streams inside larger binary formats +//! (e.g. a cache entry that contains multiple IPC sections). Each stream is +//! self-delimiting (schema + batches + EOS marker) and can be read back +//! independently. +//! +//! # Zero-copy reads +//! +//! [`read_ipc_stream`] and [`read_ipc_stream_single`] take `&Bytes` and use +//! [`Bytes::slice`] to produce each message buffer. Because `Bytes::slice` +//! increments a reference count rather than copying, the resulting +//! [`Buffer`]s — and the array data decoded from them by [`FileDecoder`] — +//! are all backed by the same allocation as the input. + +use std::io::{Read, Write}; +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_buffer::Buffer; +use arrow_ipc::convert::fb_to_schema; +use arrow_ipc::reader::FileDecoder; +use arrow_ipc::root_as_message; +use arrow_ipc::writer::StreamWriter; +use arrow_schema::ArrowError; +use bytes::Bytes; + +// --------------------------------------------------------------------------- +// Length-prefixed byte utilities +// --------------------------------------------------------------------------- + +/// Write `data` prefixed by its length as a little-endian `u64`. +/// +/// Paired with [`read_len_prefixed_bytes`]. +pub fn write_len_prefixed_bytes(writer: &mut dyn Write, data: &[u8]) -> Result<(), ArrowError> { + writer + .write_all(&(data.len() as u64).to_le_bytes()) + .map_err(|e| ArrowError::IoError(e.to_string(), e))?; + writer + .write_all(data) + .map_err(|e| ArrowError::IoError(e.to_string(), e)) +} + +/// Read a byte slice written by [`write_len_prefixed_bytes`]. +/// +/// Reads an 8-byte little-endian length then exactly that many bytes. +pub fn read_len_prefixed_bytes(reader: &mut dyn Read) -> Result, ArrowError> { + let mut len_buf = [0u8; 8]; + reader + .read_exact(&mut len_buf) + .map_err(|e| ArrowError::IoError(e.to_string(), e))?; + let len = u64::from_le_bytes(len_buf) as usize; + let mut buf = vec![0u8; len]; + reader + .read_exact(&mut buf) + .map_err(|e| ArrowError::IoError(e.to_string(), e))?; + Ok(buf) +} + +// --------------------------------------------------------------------------- +// IPC stream utilities +// --------------------------------------------------------------------------- + +// 4-byte continuation marker used by modern Arrow IPC streams. +const IPC_CONTINUATION: [u8; 4] = [0xff; 4]; + +/// Write `batch` as a single-batch Arrow IPC stream to `writer`. +pub fn write_ipc_stream(batch: &RecordBatch, writer: &mut dyn Write) -> Result<(), ArrowError> { + let mut sw = StreamWriter::try_new(&mut *writer, batch.schema_ref())?; + sw.write(batch)?; + sw.finish() +} + +/// Write all batches from `iter` as a single Arrow IPC stream to `writer`. +/// +/// `iter` must yield at least one batch; the schema is inferred from the first +/// batch. Returns `ArrowError::InvalidArgumentError` if the iterator is empty. +/// If you need to write an empty stream (schema only, no rows), construct a +/// `StreamWriter` directly. +pub fn write_ipc_stream_batches(iter: I, writer: &mut dyn Write) -> Result<(), ArrowError> +where + I: IntoIterator, +{ + let mut iter = iter.into_iter(); + let first = iter + .next() + .ok_or_else(|| ArrowError::InvalidArgumentError("no batches to serialize".into()))?; + let mut sw = StreamWriter::try_new(&mut *writer, first.schema_ref())?; + sw.write(&first)?; + for batch in iter { + sw.write(&batch)?; + } + sw.finish() +} + +/// Read one complete Arrow IPC stream message from `data` as a zero-copy [`Buffer`]. +/// +/// Parses the first message starting at byte 0 of `data`. Returns `None` on +/// EOS (size field == 0) or empty input. The returned [`Buffer`] is backed by +/// `data`'s allocation — no bytes are copied. +/// +/// The caller should advance its position by `buf.len()` after each call. +fn read_one_ipc_message(data: &Bytes) -> Result, ArrowError> { + let bytes = data.as_ref(); + + if bytes.is_empty() { + return Ok(None); + } + if bytes.len() < 4 { + return Err(ArrowError::IoError( + "IPC: truncated header".into(), + std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated IPC header"), + )); + } + + let has_continuation = bytes[..4] == IPC_CONTINUATION; + let (size_bytes, prefix_len): ([u8; 4], usize) = if has_continuation { + if bytes.len() < 8 { + return Err(ArrowError::IoError( + "IPC: truncated header after continuation".into(), + std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "truncated after continuation", + ), + )); + } + (bytes[4..8].try_into().unwrap(), 8) + } else { + (bytes[..4].try_into().unwrap(), 4) + }; + + let meta_size = u32::from_le_bytes(size_bytes) as usize; + if meta_size == 0 { + return Ok(None); // EOS + } + + let meta_end = prefix_len + meta_size; + if bytes.len() < meta_end { + return Err(ArrowError::IoError( + "IPC: truncated metadata".into(), + std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated IPC metadata"), + )); + } + + let msg = root_as_message(&bytes[prefix_len..meta_end]) + .map_err(|e| ArrowError::ParseError(format!("IPC message parse error: {e}")))?; + let body_len = msg.bodyLength() as usize; + + let total = meta_end + body_len; + if bytes.len() < total { + return Err(ArrowError::IoError( + "IPC: truncated body".into(), + std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated IPC body"), + )); + } + + // Zero-copy: Bytes::slice shares the backing allocation; Buffer::from + // wraps it without copying. + Ok(Some(Buffer::from(data.slice(0..total)))) +} + +/// Read a length-prefixed byte slice at `offset` in `data`, advancing `offset`. +/// +/// Reads an 8-byte little-endian length, then slices exactly that many bytes +/// from `data`. The returned [`Bytes`] is zero-copy (shares `data`'s allocation). +pub fn read_len_prefixed_bytes_at(data: &Bytes, offset: &mut usize) -> Result { + let bytes = data.as_ref(); + let len_end = offset + .checked_add(8) + .filter(|&e| e <= bytes.len()) + .ok_or_else(|| { + ArrowError::IoError( + "length-prefixed bytes: truncated length field".into(), + std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated length"), + ) + })?; + let len = u64::from_le_bytes(bytes[*offset..len_end].try_into().unwrap()) as usize; + *offset = len_end; + let data_end = offset + .checked_add(len) + .filter(|&e| e <= bytes.len()) + .ok_or_else(|| { + ArrowError::IoError( + "length-prefixed bytes: truncated data".into(), + std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated data"), + ) + })?; + let result = data.slice(*offset..data_end); + *offset = data_end; + Ok(result) +} + +/// Read all [`RecordBatch`]es from one Arrow IPC stream starting at `offset`, +/// advancing `offset` past the stream (including the EOS marker). +/// +/// Zero-copy: array buffers borrow from `data`'s allocation. +pub fn read_ipc_stream_at( + data: &Bytes, + offset: &mut usize, +) -> Result, ArrowError> { + let batches = read_ipc_stream(&data.slice(*offset..))?; + + // Recompute how many bytes were consumed by re-parsing message sizes. + // We can't get this from read_ipc_stream directly, so we re-walk the + // message headers (metadata only, no body re-read) to sum up lengths. + let slice = &data.as_ref()[*offset..]; + let mut consumed = 0usize; + loop { + let rem = &slice[consumed..]; + if rem.is_empty() { + break; + } + let has_cont = rem.len() >= 4 && rem[..4] == IPC_CONTINUATION; + let (size_bytes, prefix_len): ([u8; 4], usize) = if has_cont { + if rem.len() < 8 { + break; + } + (rem[4..8].try_into().unwrap(), 8) + } else { + if rem.len() < 4 { + break; + } + (rem[..4].try_into().unwrap(), 4) + }; + let meta_size = u32::from_le_bytes(size_bytes) as usize; + if meta_size == 0 { + // EOS — consume it and stop. + consumed += prefix_len; + break; + } + let meta_end = prefix_len + meta_size; + if rem.len() < meta_end { + break; + } + let msg = root_as_message(&rem[prefix_len..meta_end]) + .map_err(|e| ArrowError::ParseError(format!("IPC message parse error: {e}")))?; + let body_len = msg.bodyLength() as usize; + consumed += meta_end + body_len; + } + *offset += consumed; + + Ok(batches) +} + +/// Read exactly one [`RecordBatch`] from one Arrow IPC stream starting at `offset`, +/// advancing `offset` past the stream (including the EOS marker). +/// +/// Zero-copy: array buffers borrow from `data`'s allocation. +pub fn read_ipc_stream_single_at( + data: &Bytes, + offset: &mut usize, +) -> Result { + let mut batches = read_ipc_stream_at(data, offset)?; + match batches.len() { + 1 => Ok(batches.remove(0)), + n => Err(ArrowError::ParseError(format!( + "expected exactly 1 IPC record batch, got {n}" + ))), + } +} + +/// Extract the prefix length and metadata size from a raw IPC message buffer. +/// +/// Modern IPC streams have an 8-byte prefix `[continuation: 4][size: 4]`. +/// Legacy streams have a 4-byte prefix `[size: 4]`. Returns `(prefix_len, meta_size)`. +fn parse_ipc_message_prefix(buf: &Buffer) -> Result<(usize, usize), ArrowError> { + let has_continuation = buf.len() >= 4 && buf[..4] == IPC_CONTINUATION; + if has_continuation { + if buf.len() < 8 { + return Err(ArrowError::ParseError( + "IPC message buffer too short".into(), + )); + } + let meta_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()) as usize; + Ok((8, meta_size)) + } else { + if buf.len() < 4 { + return Err(ArrowError::ParseError( + "IPC message buffer too short".into(), + )); + } + let meta_size = u32::from_le_bytes(buf[..4].try_into().unwrap()) as usize; + Ok((4, meta_size)) + } +} + +/// Read all [`RecordBatch`]es from one Arrow IPC stream. +/// +/// Zero-copy: each batch's array data buffers are borrowed from the input +/// message buffer(s) and not copied during decoding. +/// +/// Uses [`FileDecoder`] directly (rather than `StreamDecoder`) to avoid a +/// known edge case where `StreamDecoder` does not produce a batch for messages +/// with a zero-length body when the message exactly fills the decode buffer. +pub fn read_ipc_stream(data: &Bytes) -> Result, ArrowError> { + let mut offset = 0usize; + + let schema_buf = read_one_ipc_message(&data.slice(offset..))?.ok_or_else(|| { + ArrowError::ParseError("IPC stream: expected schema message, got EOS".into()) + })?; + offset += schema_buf.len(); + + let (prefix_len, meta_size) = parse_ipc_message_prefix(&schema_buf)?; + let schema_msg = root_as_message(&schema_buf[prefix_len..prefix_len + meta_size]) + .map_err(|e| ArrowError::ParseError(format!("IPC schema parse error: {e}")))?; + let schema = Arc::new(fb_to_schema(schema_msg.header_as_schema().ok_or_else( + || ArrowError::ParseError("IPC stream: first message is not a schema".into()), + )?)); + let mut decoder = FileDecoder::new(schema, schema_msg.version()); + + let mut batches = Vec::new(); + + loop { + let Some(buf) = read_one_ipc_message(&data.slice(offset..))? else { + break; + }; + offset += buf.len(); + + let (prefix_len, meta_size) = parse_ipc_message_prefix(&buf)?; + let msg = root_as_message(&buf[prefix_len..prefix_len + meta_size]) + .map_err(|e| ArrowError::ParseError(format!("IPC message parse error: {e}")))?; + let body_len = msg.bodyLength() as usize; + + // Block offset = 0 since the buffer starts at the message boundary. + // metaDataLength = prefix_len + meta_size (prefix + flatbuf + padding). + let block = arrow_ipc::Block::new(0, (prefix_len + meta_size) as i32, body_len as i64); + + match msg.header_type() { + arrow_ipc::MessageHeader::RecordBatch => { + if let Some(batch) = decoder.read_record_batch(&block, &buf)? { + batches.push(batch); + } + } + arrow_ipc::MessageHeader::DictionaryBatch => { + decoder.read_dictionary(&block, &buf)?; + } + _ => break, + } + } + + Ok(batches) +} + +/// Read exactly one [`RecordBatch`] from one Arrow IPC stream. +pub fn read_ipc_stream_single(data: &Bytes) -> Result { + let mut batches = read_ipc_stream(data)?; + match batches.len() { + 1 => Ok(batches.remove(0)), + n => Err(ArrowError::ParseError(format!( + "expected exactly 1 IPC record batch, got {n}" + ))), + } +} + +// --------------------------------------------------------------------------- +// Aligned IPC sections +// --------------------------------------------------------------------------- + +/// Byte alignment that each IPC section's stream start is padded to. +/// +/// When several IPC streams are concatenated into one larger blob (e.g. a +/// cache entry), a section that starts at an arbitrary offset would leave its +/// array data misaligned. [`FileDecoder`] with `require_alignment = false` +/// then silently copies each buffer into a freshly aligned allocation on +/// every read, defeating zero-copy. Padding each section start to a 64-byte +/// boundary keeps the decoded buffers borrowed directly from the input. +pub const IPC_SECTION_ALIGNMENT: usize = 64; + +/// Number of zero-padding bytes needed to advance `pos` to the next +/// [`IPC_SECTION_ALIGNMENT`] boundary. +fn section_padding(pos: usize) -> usize { + (IPC_SECTION_ALIGNMENT - (pos % IPC_SECTION_ALIGNMENT)) % IPC_SECTION_ALIGNMENT +} + +/// A [`Write`] adapter that counts the bytes written through it. +struct CountingWriter<'a> { + inner: &'a mut dyn Write, + count: usize, +} + +impl Write for CountingWriter<'_> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let n = self.inner.write(buf)?; + self.count += n; + Ok(n) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } +} + +/// Write zero padding so the next byte lands on an [`IPC_SECTION_ALIGNMENT`] +/// boundary, advancing `pos` past it. +fn write_section_padding(writer: &mut dyn Write, pos: &mut usize) -> Result<(), ArrowError> { + let pad = section_padding(*pos); + if pad > 0 { + const ZEROS: [u8; IPC_SECTION_ALIGNMENT] = [0u8; IPC_SECTION_ALIGNMENT]; + writer + .write_all(&ZEROS[..pad]) + .map_err(|e| ArrowError::IoError(e.to_string(), e))?; + *pos += pad; + } + Ok(()) +} + +/// Write `batch` as a 64-byte-aligned single-batch Arrow IPC section. +/// +/// `pos` is the absolute byte offset of `writer` within the enclosing blob. +/// Zero padding is written first so the IPC stream begins on an +/// [`IPC_SECTION_ALIGNMENT`] boundary, then the stream itself. `pos` is +/// advanced past both the padding and the stream so the caller can write +/// further aligned sections. +/// +/// Paired with [`read_ipc_section_at`]. For the decoded buffers to be borrowed +/// zero-copy, the blob must ultimately be read back from a buffer whose base +/// address is at least 64-byte aligned. +pub fn write_ipc_section( + writer: &mut dyn Write, + pos: &mut usize, + batch: &RecordBatch, +) -> Result<(), ArrowError> { + write_section_padding(writer, pos)?; + + let mut counting = CountingWriter { + inner: writer, + count: 0, + }; + write_ipc_stream(batch, &mut counting)?; + *pos += counting.count; + Ok(()) +} + +/// Read a single [`RecordBatch`] from an aligned IPC section at `offset`. +/// +/// Skips the alignment padding written by [`write_ipc_section`], then reads +/// the stream, advancing `offset` past the section (padding + stream + EOS). +/// +/// Zero-copy: array buffers borrow from `data`'s allocation when `data`'s base +/// address is at least 64-byte aligned (see [`write_ipc_section`]). +pub fn read_ipc_section_at(data: &Bytes, offset: &mut usize) -> Result { + *offset += section_padding(*offset); + read_ipc_stream_single_at(data, offset) +} + +/// Write `batches` as a single 64-byte-aligned multi-batch Arrow IPC section. +/// +/// Like [`write_ipc_section`] but emits every batch from `iter` into one IPC +/// stream (schema + N batches + EOS). `iter` must yield at least one batch. +/// Paired with [`read_ipc_section_batches_at`]. +pub fn write_ipc_section_batches( + writer: &mut dyn Write, + pos: &mut usize, + iter: I, +) -> Result<(), ArrowError> +where + I: IntoIterator, +{ + write_section_padding(writer, pos)?; + + let mut counting = CountingWriter { + inner: writer, + count: 0, + }; + write_ipc_stream_batches(iter, &mut counting)?; + *pos += counting.count; + Ok(()) +} + +/// Read all [`RecordBatch`]es from an aligned multi-batch IPC section at +/// `offset`, advancing `offset` past the section (padding + stream + EOS). +/// +/// Zero-copy: array buffers borrow from `data`'s allocation when `data`'s base +/// address is at least 64-byte aligned (see [`write_ipc_section_batches`]). +pub fn read_ipc_section_batches_at( + data: &Bytes, + offset: &mut usize, +) -> Result, ArrowError> { + *offset += section_padding(*offset); + read_ipc_stream_at(data, offset) +} + +#[cfg(test)] +mod tests { + use arrow_array::{ArrayRef, record_batch}; + + use super::*; + + #[test] + fn test_ipc_roundtrip() { + let batch1 = record_batch!( + ("int", Int32, [1, 2, 3]), + ("str", Utf8, ["foo", "bar", "baz"]) + ) + .unwrap(); + let batch2 = record_batch!(("int", Int32, [4, 5]), ("str", Utf8, ["qux", "quux"])).unwrap(); + let batches = vec![batch1.clone(), batch2.clone()]; + + let mut buf = Vec::new(); + write_ipc_stream_batches(batches, &mut buf).unwrap(); + + let data = Bytes::from(buf); + + let batches = read_ipc_stream(&data).unwrap(); + assert_eq!(batches.len(), 2); + assert_eq!(batches[0], batch1); + assert_eq!(batches[1], batch2); + + let data_base = data.as_ptr() as usize; + let data_end = data_base + data.len(); + let assert_col_zero_copy = |array: &ArrayRef| { + for buffer in array.to_data().buffers() { + let ptr = buffer.as_ptr() as usize; + assert!( + ptr >= data_base && ptr < data_end, + "buffer at {ptr:#x} is not backed by the input Bytes allocation \ + [{data_base:#x}..{data_end:#x})" + ); + } + }; + + for batch in &batches { + assert_eq!(batch.schema(), batch1.schema()); + assert_col_zero_copy(batch.column(0)); + assert_col_zero_copy(batch.column(1)); + } + } + + /// Allocate a [`Bytes`] whose base address is 64-byte aligned, modelling a + /// backend that reads cache entries into an aligned buffer. A plain + /// `Bytes::from(vec)` only guarantees the allocator's alignment for `u8`. + fn aligned_bytes(payload: &[u8]) -> Bytes { + let mut v = vec![0u8; payload.len() + IPC_SECTION_ALIGNMENT]; + let pad = section_padding(v.as_ptr() as usize); + v[pad..pad + payload.len()].copy_from_slice(payload); + Bytes::from(v).slice(pad..pad + payload.len()) + } + + #[test] + fn test_aligned_ipc_sections_are_zero_copy() { + // A LargeBinary column exercises the i64-offset buffer whose 8-byte + // alignment requirement triggers a realigning memcpy when misaligned. + let blocks = arrow_array::LargeBinaryArray::from_vec(vec![&b"hello"[..], b"world"]); + let section_a = RecordBatch::try_from_iter([("a", Arc::new(blocks) as ArrayRef)]).unwrap(); + let section_b = record_batch!(("b", Int64, [10i64, 20, 30, 40, 50])).unwrap(); + + let mut buf = Vec::new(); + // Arbitrary, deliberately non-64-aligned preamble so the first section + // must be padded rather than landing at offset 0 by luck. + buf.extend_from_slice(&[0xABu8; 7]); + let mut pos = buf.len(); + // The first section's stream begins after padding the 7-byte preamble + // up to the next 64-byte boundary. + assert_eq!(7 + section_padding(7), IPC_SECTION_ALIGNMENT); + write_ipc_section(&mut buf, &mut pos, §ion_a).unwrap(); + write_ipc_section(&mut buf, &mut pos, §ion_b).unwrap(); + + let data = aligned_bytes(&buf); + assert_eq!( + section_padding(data.as_ptr() as usize), + 0, + "base not aligned" + ); + + let mut offset = 7; + let read_a = read_ipc_section_at(&data, &mut offset).unwrap(); + let read_b = read_ipc_section_at(&data, &mut offset).unwrap(); + assert_eq!(read_a, section_a); + assert_eq!(read_b, section_b); + + let data_base = data.as_ptr() as usize; + let data_end = data_base + data.len(); + for batch in [&read_a, &read_b] { + for buffer in batch.column(0).to_data().buffers() { + let ptr = buffer.as_ptr() as usize; + assert!( + ptr >= data_base && ptr < data_end, + "section buffer at {ptr:#x} was realigned out of the input \ + [{data_base:#x}..{data_end:#x}) — misaligned section", + ); + } + } + } + + #[test] + fn test_aligned_multi_batch_section_roundtrip_zero_copy() { + // A multi-batch section (e.g. IVF SQ storage chunks) must round-trip + // every batch and decode the first batch's buffers zero-copy. + let b1 = record_batch!(("v", Int64, [1i64, 2, 3])).unwrap(); + let b2 = record_batch!(("v", Int64, [4i64, 5])).unwrap(); + let b3 = record_batch!(("v", Int64, [6i64])).unwrap(); + + let mut buf = vec![0xCDu8; 5]; + let mut pos = buf.len(); + write_ipc_section_batches(&mut buf, &mut pos, [b1.clone(), b2.clone(), b3.clone()]) + .unwrap(); + + let data = aligned_bytes(&buf); + let mut offset = 5; + let read = read_ipc_section_batches_at(&data, &mut offset).unwrap(); + assert_eq!(read, vec![b1, b2, b3]); + assert_eq!(offset, buf.len(), "offset should land at section end"); + + let data_base = data.as_ptr() as usize; + let data_end = data_base + data.len(); + for buffer in read[0].column(0).to_data().buffers() { + let ptr = buffer.as_ptr() as usize; + assert!( + ptr >= data_base && ptr < data_end, + "first batch buffer at {ptr:#x} was realigned out of the input", + ); + } + } +} diff --git a/python/vendor/lance-arrow/src/json.rs b/python/vendor/lance-arrow/src/json.rs new file mode 100644 index 000000000..df908c4cb --- /dev/null +++ b/python/vendor/lance-arrow/src/json.rs @@ -0,0 +1,1538 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! JSON support for Apache Arrow. + +use std::convert::TryFrom; +use std::sync::Arc; + +use arrow_array::builder::{GenericStringBuilder, LargeBinaryBuilder}; +use arrow_array::cast::AsArray; +use arrow_array::{ + Array, ArrayRef, FixedSizeListArray, GenericStringArray, LargeBinaryArray, LargeListArray, + LargeStringArray, ListArray, MapArray, OffsetSizeTrait, RecordBatch, StringArray, StructArray, +}; +use arrow_schema::{ArrowError, DataType, Field as ArrowField, Fields, Schema}; +use lance_jsonb::OwnedJsonb; +use lance_jsonb::jsonpath::{JsonPath, Selector}; + +use crate::ARROW_EXT_NAME_KEY; + +/// Arrow extension type name for JSON data (Lance internal) +pub const JSON_EXT_NAME: &str = "lance.json"; + +/// Arrow extension type name for JSON data (Arrow official) +pub const ARROW_JSON_EXT_NAME: &str = "arrow.json"; + +/// Check if a field is a JSON extension field (Lance internal JSONB storage) +pub fn is_json_field(field: &ArrowField) -> bool { + field.data_type() == &DataType::LargeBinary + && field + .metadata() + .get(ARROW_EXT_NAME_KEY) + .map(|name| name == JSON_EXT_NAME) + .unwrap_or_default() +} + +/// Check if a field is an Arrow JSON extension field (PyArrow pa.json() type) +pub fn is_arrow_json_field(field: &ArrowField) -> bool { + // Arrow JSON extension type uses Utf8 or LargeUtf8 as storage type + (field.data_type() == &DataType::Utf8 || field.data_type() == &DataType::LargeUtf8) + && field + .metadata() + .get(ARROW_EXT_NAME_KEY) + .map(|name| name == ARROW_JSON_EXT_NAME) + .unwrap_or_default() +} + +/// Check if a field or any of its descendants is a JSON field +pub fn has_json_fields(field: &ArrowField) -> bool { + if is_json_field(field) { + return true; + } + + match field.data_type() { + DataType::Struct(fields) => fields.iter().any(|f| has_json_fields(f)), + DataType::List(f) | DataType::LargeList(f) | DataType::FixedSizeList(f, _) => { + has_json_fields(f) + } + DataType::Map(f, _) => has_json_fields(f), + _ => false, + } +} + +/// Check if a field or any of its descendants is an Arrow JSON field +pub fn has_arrow_json_fields(field: &ArrowField) -> bool { + if is_arrow_json_field(field) { + return true; + } + + match field.data_type() { + DataType::Struct(fields) => fields.iter().any(|f| has_arrow_json_fields(f)), + DataType::List(f) | DataType::LargeList(f) | DataType::FixedSizeList(f, _) => { + has_arrow_json_fields(f) + } + DataType::Map(f, _) => has_arrow_json_fields(f), + _ => false, + } +} + +/// The Arrow representation holding a JSON field's values. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum JsonEncoding { + /// JSONB bytes: [`JSON_EXT_NAME`] over `LargeBinary`. Lance stores JSON + /// this way. + Jsonb, + /// JSON text: [`ARROW_JSON_EXT_NAME`] over `Utf8` or `LargeUtf8`. Callers + /// write JSON this way, and reads return it this way by default. + Text, +} + +impl JsonEncoding { + /// The encoding of `field`'s values, or `None` when `field` does not hold + /// JSON. + pub fn of_field(field: &ArrowField) -> Option { + if is_json_field(field) { + Some(Self::Jsonb) + } else if is_arrow_json_field(field) { + Some(Self::Text) + } else { + None + } + } +} + +/// The values of a JSON column, readable as JSONB or as text whichever +/// encoding they arrived in. +/// +/// Code that computes on JSON, such as tokenizers and indices, reads values +/// through this type, so its behavior does not depend on whether they come +/// from storage or from a caller. +#[derive(Debug, Clone, Copy)] +pub struct JsonValues<'a> { + encoding: JsonEncoding, + array: &'a ArrayRef, +} + +impl<'a> JsonValues<'a> { + /// Read `array` as the values of `field`, or `None` when `field` does not + /// hold JSON. + pub fn try_new(field: &ArrowField, array: &'a ArrayRef) -> Option { + JsonEncoding::of_field(field).map(|encoding| Self { encoding, array }) + } + + pub fn encoding(&self) -> JsonEncoding { + self.encoding + } + + /// The values as JSONB. Text values are parsed, so invalid JSON fails. + pub fn to_jsonb(&self) -> Result { + match self.encoding { + JsonEncoding::Jsonb => Ok(self.array.as_binary::().clone()), + JsonEncoding::Text => Ok(JsonArray::try_from(self.array.clone())?.into_inner()), + } + } + + /// The values as JSON text: the input array when it already holds text, + /// otherwise `LargeUtf8` decoded from JSONB. + pub fn to_text(&self) -> ArrayRef { + match self.encoding { + JsonEncoding::Jsonb => Arc::new(decode_jsonb_array::(self.array.as_binary())), + JsonEncoding::Text => self.array.clone(), + } + } +} + +/// Create a JSON field with the appropriate extension metadata +pub fn json_field(name: &str, nullable: bool) -> ArrowField { + let mut field = ArrowField::new(name, DataType::LargeBinary, nullable); + let mut metadata = std::collections::HashMap::new(); + metadata.insert(ARROW_EXT_NAME_KEY.to_string(), JSON_EXT_NAME.to_string()); + field.set_metadata(metadata); + field +} + +/// A specialized array for JSON data stored as JSONB binary format +#[derive(Debug, Clone)] +pub struct JsonArray { + inner: LargeBinaryArray, +} + +impl JsonArray { + /// Create a new JsonArray from an iterator of JSON strings + pub fn try_from_iter(iter: I) -> Result + where + I: IntoIterator>, + S: AsRef, + { + let mut builder = LargeBinaryBuilder::new(); + + for json_str in iter { + match json_str { + Some(s) => { + let encoded = encode_json(s.as_ref()).map_err(|e| { + ArrowError::InvalidArgumentError(format!("Failed to encode JSON: {}", e)) + })?; + builder.append_value(&encoded); + } + None => builder.append_null(), + } + } + + Ok(Self { + inner: builder.finish(), + }) + } + + /// Get the underlying LargeBinaryArray + pub fn into_inner(self) -> LargeBinaryArray { + self.inner + } + + /// Get a reference to the underlying LargeBinaryArray + pub fn inner(&self) -> &LargeBinaryArray { + &self.inner + } + + /// Get the value at index i as decoded JSON string + pub fn value(&self, i: usize) -> Result { + if self.inner.is_null(i) { + return Err(ArrowError::InvalidArgumentError( + "Value is null".to_string(), + )); + } + + let jsonb_bytes = self.inner.value(i); + Ok(decode_json(jsonb_bytes)) + } + + /// Get the value at index i as raw JSONB bytes + pub fn value_bytes(&self, i: usize) -> &[u8] { + self.inner.value(i) + } + + /// Get JSONPath value from the JSON at index i + pub fn json_path(&self, i: usize, path: &str) -> Result, ArrowError> { + if self.inner.is_null(i) { + return Ok(None); + } + + let path = parse_json_path(path)?; + Ok(select_json_path(self.inner.value(i), &path)?.map(|value| value.to_string())) + } + + /// Convert to Arrow string array (JSON as UTF-8) + pub fn to_arrow_json(&self) -> ArrayRef { + Arc::new(decode_jsonb_array::(&self.inner)) + } + + pub fn len(&self) -> usize { + self.inner.len() + } + + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + pub fn is_null(&self, i: usize) -> bool { + self.inner.is_null(i) + } +} + +// TryFrom implementations for string arrays +impl TryFrom for JsonArray { + type Error = ArrowError; + + fn try_from(array: StringArray) -> Result { + Self::try_from(&array) + } +} + +impl TryFrom<&StringArray> for JsonArray { + type Error = ArrowError; + + fn try_from(array: &StringArray) -> Result { + encode_json_text_array(array) + } +} + +impl TryFrom for JsonArray { + type Error = ArrowError; + + fn try_from(array: LargeStringArray) -> Result { + Self::try_from(&array) + } +} + +impl TryFrom<&LargeStringArray> for JsonArray { + type Error = ArrowError; + + fn try_from(array: &LargeStringArray) -> Result { + encode_json_text_array(array) + } +} + +fn encode_json_text_array( + array: &GenericStringArray, +) -> Result { + let mut builder = LargeBinaryBuilder::with_capacity(array.len(), array.value_data().len()); + for value in array { + match value { + Some(json_str) => { + let encoded = encode_json(json_str).map_err(|e| { + ArrowError::InvalidArgumentError(format!("Failed to encode JSON: {}", e)) + })?; + builder.append_value(&encoded); + } + None => builder.append_null(), + } + } + Ok(JsonArray { + inner: builder.finish(), + }) +} + +fn decode_jsonb_array(array: &LargeBinaryArray) -> GenericStringArray { + let mut builder = + GenericStringBuilder::::with_capacity(array.len(), array.value_data().len()); + for value in array { + match value { + Some(jsonb_bytes) => builder.append_value(decode_json(jsonb_bytes)), + None => builder.append_null(), + } + } + builder.finish() +} + +impl TryFrom for JsonArray { + type Error = ArrowError; + + fn try_from(array_ref: ArrayRef) -> Result { + match array_ref.data_type() { + DataType::Utf8 => { + // Downcast is guaranteed to succeed after matching on DataType::Utf8 + let string_array = array_ref + .as_any() + .downcast_ref::() + .expect("DataType::Utf8 array must be StringArray"); + Self::try_from(string_array) + } + DataType::LargeUtf8 => { + // Downcast is guaranteed to succeed after matching on DataType::LargeUtf8 + let large_string_array = array_ref + .as_any() + .downcast_ref::() + .expect("DataType::LargeUtf8 array must be LargeStringArray"); + Self::try_from(large_string_array) + } + dt => Err(ArrowError::InvalidArgumentError(format!( + "Unsupported array type for JSON: {:?}. Expected Utf8 or LargeUtf8", + dt + ))), + } + } +} + +/// Encode JSON string to JSONB format +pub fn encode_json(json_str: &str) -> Result, Box> { + let value = lance_jsonb::parse_value(json_str.as_bytes())?; + Ok(value.to_vec()) +} + +/// Decode JSONB bytes to JSON string +pub fn decode_json(jsonb_bytes: &[u8]) -> String { + let raw_jsonb = lance_jsonb::RawJsonb::new(jsonb_bytes); + raw_jsonb.to_string() +} + +/// Parse a JSONPath expression. +pub fn parse_json_path(path: &str) -> Result, ArrowError> { + lance_jsonb::jsonpath::parse_json_path(path.as_bytes()) + .map_err(|e| ArrowError::InvalidArgumentError(format!("Invalid JSONPath '{path}': {e}"))) +} + +/// Select the value at `path` in a JSONB value. +/// +/// A path matching several values selects them together as one JSON array, +/// so no match is silently dropped. +pub fn select_json_path( + jsonb_bytes: &[u8], + path: &JsonPath<'_>, +) -> Result, ArrowError> { + Selector::new(lance_jsonb::RawJsonb::new(jsonb_bytes)) + .select_value(path) + .map_err(|e| { + ArrowError::InvalidArgumentError(format!("Failed to select JSONPath {path}: {e}")) + }) +} + +/// Whether `path` matches any value in a JSONB value. +pub fn json_path_exists(jsonb_bytes: &[u8], path: &JsonPath<'_>) -> Result { + Selector::new(lance_jsonb::RawJsonb::new(jsonb_bytes)) + .exists(path) + .map_err(|e| { + ArrowError::InvalidArgumentError(format!("Failed to match JSONPath {path}: {e}")) + }) +} + +/// Select every value matched by `path` in a JSONB value. +pub fn select_json_path_values( + jsonb_bytes: &[u8], + path: &JsonPath<'_>, +) -> Result, ArrowError> { + Selector::new(lance_jsonb::RawJsonb::new(jsonb_bytes)) + .select_values(path) + .map_err(|e| { + ArrowError::InvalidArgumentError(format!("Failed to select JSONPath {path}: {e}")) + }) +} + +/// Convert an Arrow JSON field to Lance JSON field (with JSONB storage) +pub fn arrow_json_to_lance_json(field: &ArrowField) -> ArrowField { + if is_arrow_json_field(field) { + return field_with_extension(field, DataType::LargeBinary, JSON_EXT_NAME); + } + + let data_type = match field.data_type() { + DataType::Struct(fields) => { + let fields = fields + .iter() + .map(|field| Arc::new(arrow_json_to_lance_json(field))) + .collect::>(); + DataType::Struct(Fields::from(fields)) + } + DataType::List(item) => DataType::List(Arc::new(arrow_json_to_lance_json(item))), + DataType::LargeList(item) => DataType::LargeList(Arc::new(arrow_json_to_lance_json(item))), + DataType::FixedSizeList(item, size) => { + DataType::FixedSizeList(Arc::new(arrow_json_to_lance_json(item)), *size) + } + DataType::Map(entries, keys_sorted) => { + DataType::Map(Arc::new(arrow_json_to_lance_json(entries)), *keys_sorted) + } + _ => return field.clone(), + }; + + field_with_data_type(field, data_type) +} + +/// Convert a Lance JSON field to Arrow JSON field. +pub fn lance_json_to_arrow_json(field: &ArrowField) -> ArrowField { + if is_json_field(field) { + return field_with_extension(field, DataType::Utf8, ARROW_JSON_EXT_NAME); + } + + let data_type = match field.data_type() { + DataType::Struct(fields) => { + let fields = fields + .iter() + .map(|field| Arc::new(lance_json_to_arrow_json(field))) + .collect::>(); + DataType::Struct(Fields::from(fields)) + } + DataType::List(item) => DataType::List(Arc::new(lance_json_to_arrow_json(item))), + DataType::LargeList(item) => DataType::LargeList(Arc::new(lance_json_to_arrow_json(item))), + DataType::FixedSizeList(item, size) => { + DataType::FixedSizeList(Arc::new(lance_json_to_arrow_json(item)), *size) + } + DataType::Map(entries, keys_sorted) => { + DataType::Map(Arc::new(lance_json_to_arrow_json(entries)), *keys_sorted) + } + _ => return field.clone(), + }; + + field_with_data_type(field, data_type) +} + +fn field_with_data_type(field: &ArrowField, data_type: DataType) -> ArrowField { + ArrowField::new(field.name(), data_type, field.is_nullable()) + .with_metadata(field.metadata().clone()) +} + +fn field_with_extension( + field: &ArrowField, + data_type: DataType, + extension_name: &str, +) -> ArrowField { + let mut metadata = field.metadata().clone(); + metadata.insert(ARROW_EXT_NAME_KEY.to_string(), extension_name.to_string()); + ArrowField::new(field.name(), data_type, field.is_nullable()).with_metadata(metadata) +} + +fn convert_json_array( + field: &ArrowField, + array: &ArrayRef, + convert_leaf: &F, +) -> Result<(ArrowField, ArrayRef, bool), ArrowError> +where + F: Fn(&ArrowField, &ArrayRef) -> Result, ArrowError>, +{ + if let Some((field, array)) = convert_leaf(field, array)? { + return Ok((field, array, true)); + } + + match field.data_type() { + DataType::Struct(fields) => { + let struct_array = array.as_struct(); + let mut new_fields = Vec::with_capacity(fields.len()); + let mut new_columns = Vec::with_capacity(fields.len()); + let mut changed = false; + + for (field, column) in fields.iter().zip(struct_array.columns()) { + let (new_field, new_column, field_changed) = + convert_json_array(field, column, convert_leaf)?; + changed |= field_changed; + new_fields.push(Arc::new(new_field)); + new_columns.push(new_column); + } + + if changed { + let fields = Fields::from(new_fields); + let new_field = field_with_data_type(field, DataType::Struct(fields.clone())); + let new_array = + StructArray::new(fields, new_columns, struct_array.nulls().cloned()); + Ok((new_field, Arc::new(new_array) as ArrayRef, true)) + } else { + Ok((field.clone(), array.clone(), false)) + } + } + DataType::List(item) => { + let list_array: &ListArray = array.as_list(); + let (new_item, new_values, changed) = + convert_json_array(item, list_array.values(), convert_leaf)?; + if changed { + let new_field = + field_with_data_type(field, DataType::List(Arc::new(new_item.clone()))); + let new_array = ListArray::new( + Arc::new(new_item), + list_array.offsets().clone(), + new_values, + list_array.nulls().cloned(), + ); + Ok((new_field, Arc::new(new_array) as ArrayRef, true)) + } else { + Ok((field.clone(), array.clone(), false)) + } + } + DataType::LargeList(item) => { + let list_array: &LargeListArray = array.as_list(); + let (new_item, new_values, changed) = + convert_json_array(item, list_array.values(), convert_leaf)?; + if changed { + let new_field = + field_with_data_type(field, DataType::LargeList(Arc::new(new_item.clone()))); + let new_array = LargeListArray::new( + Arc::new(new_item), + list_array.offsets().clone(), + new_values, + list_array.nulls().cloned(), + ); + Ok((new_field, Arc::new(new_array) as ArrayRef, true)) + } else { + Ok((field.clone(), array.clone(), false)) + } + } + DataType::FixedSizeList(item, size) => { + let list_array: &FixedSizeListArray = array.as_fixed_size_list(); + let (new_item, new_values, changed) = + convert_json_array(item, list_array.values(), convert_leaf)?; + if changed { + let new_field = field_with_data_type( + field, + DataType::FixedSizeList(Arc::new(new_item.clone()), *size), + ); + let new_array = FixedSizeListArray::try_new_with_length( + Arc::new(new_item), + *size, + new_values, + list_array.nulls().cloned(), + list_array.len(), + )?; + Ok((new_field, Arc::new(new_array) as ArrayRef, true)) + } else { + Ok((field.clone(), array.clone(), false)) + } + } + DataType::Map(entries, keys_sorted) => { + let map_array = array + .as_any() + .downcast_ref::() + .expect("DataType::Map array must be MapArray"); + let entries_array = Arc::new(map_array.entries().clone()) as ArrayRef; + let (new_entries, new_entries_array, changed) = + convert_json_array(entries, &entries_array, convert_leaf)?; + if changed { + let entries_struct = new_entries_array + .as_any() + .downcast_ref::() + .expect("Map entries must be StructArray") + .clone(); + let new_field = field_with_data_type( + field, + DataType::Map(Arc::new(new_entries.clone()), *keys_sorted), + ); + let new_array = MapArray::new( + Arc::new(new_entries), + map_array.offsets().clone(), + entries_struct, + map_array.nulls().cloned(), + *keys_sorted, + ); + Ok((new_field, Arc::new(new_array) as ArrayRef, true)) + } else { + Ok((field.clone(), array.clone(), false)) + } + } + _ => Ok((field.clone(), array.clone(), false)), + } +} + +fn convert_arrow_json_array( + field: &ArrowField, + array: &ArrayRef, +) -> Result<(ArrowField, ArrayRef, bool), ArrowError> { + convert_json_array(field, array, &|field, array| { + if is_arrow_json_field(field) { + let json_array = JsonArray::try_from(array.clone())?; + Ok(Some(( + arrow_json_to_lance_json(field), + Arc::new(json_array.into_inner()) as ArrayRef, + ))) + } else { + Ok(None) + } + }) +} + +fn convert_lance_json_array( + field: &ArrowField, + array: &ArrayRef, +) -> Result<(ArrowField, ArrayRef, bool), ArrowError> { + convert_json_array(field, array, &|field, array| { + if is_json_field(field) { + Ok(Some(( + lance_json_to_arrow_json(field), + Arc::new(decode_jsonb_array::(array.as_binary())) as ArrayRef, + ))) + } else { + Ok(None) + } + }) +} + +/// Convert a RecordBatch with Lance JSON columns (JSONB) back to Arrow JSON format (strings) +pub fn convert_lance_json_to_arrow( + batch: &arrow_array::RecordBatch, +) -> Result { + let schema = batch.schema(); + let mut needs_conversion = false; + let mut new_fields = Vec::with_capacity(schema.fields().len()); + let mut new_columns = Vec::with_capacity(batch.num_columns()); + + for (i, field) in schema.fields().iter().enumerate() { + let column = batch.column(i); + let (new_field, new_column, changed) = convert_lance_json_array(field, column)?; + + needs_conversion |= changed; + new_fields.push(new_field); + new_columns.push(new_column); + } + + if needs_conversion { + let new_schema = Arc::new(Schema::new_with_metadata( + new_fields, + schema.metadata().clone(), + )); + RecordBatch::try_new(new_schema, new_columns) + } else { + // No conversion needed, return original batch + Ok(batch.clone()) + } +} + +/// Convert a RecordBatch with Arrow JSON columns to Lance JSON format (JSONB) +pub fn convert_json_columns( + batch: &arrow_array::RecordBatch, +) -> Result { + let schema = batch.schema(); + let mut needs_conversion = false; + let mut new_fields = Vec::with_capacity(schema.fields().len()); + let mut new_columns = Vec::with_capacity(batch.num_columns()); + + for (i, field) in schema.fields().iter().enumerate() { + let column = batch.column(i); + let (new_field, new_column, changed) = convert_arrow_json_array(field, column)?; + + needs_conversion |= changed; + new_fields.push(new_field); + new_columns.push(new_column); + } + + if needs_conversion { + let new_schema = Arc::new(Schema::new_with_metadata( + new_fields, + schema.metadata().clone(), + )); + RecordBatch::try_new(new_schema, new_columns) + } else { + // No conversion needed, return original batch + Ok(batch.clone()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_json_field_creation() { + let field = json_field("data", true); + assert_eq!(field.name(), "data"); + assert_eq!(field.data_type(), &DataType::LargeBinary); + assert!(field.is_nullable()); + assert!(is_json_field(&field)); + } + + #[test] + fn test_json_array_from_strings() { + let json_strings = vec![ + Some(r#"{"name": "Alice", "age": 30}"#), + None, + Some(r#"{"name": "Bob", "age": 25}"#), + ]; + + let array = JsonArray::try_from_iter(json_strings).unwrap(); + assert_eq!(array.len(), 3); + assert!(!array.is_null(0)); + assert!(array.is_null(1)); + assert!(!array.is_null(2)); + + let decoded = array.value(0).unwrap(); + assert!(decoded.contains("Alice")); + } + + #[test] + fn test_json_array_from_string_array() { + let string_array = StringArray::from(vec![ + Some(r#"{"name": "Alice"}"#), + Some(r#"{"name": "Bob"}"#), + None, + ]); + + let json_array = JsonArray::try_from(string_array).unwrap(); + assert_eq!(json_array.len(), 3); + assert!(!json_array.is_null(0)); + assert!(!json_array.is_null(1)); + assert!(json_array.is_null(2)); + } + + #[test] + fn test_json_path_extraction() { + let json_array = JsonArray::try_from_iter(vec![ + Some(r#"{"user": {"name": "Alice", "age": 30}}"#), + Some(r#"{"user": {"name": "Bob"}}"#), + ]) + .unwrap(); + + let name = json_array.json_path(0, "$.user.name").unwrap(); + assert_eq!(name, Some("\"Alice\"".to_string())); + + let age = json_array.json_path(1, "$.user.age").unwrap(); + assert_eq!(age, None); + + // Several matches are selected together, as the SQL JSON functions do. + let json_array = + JsonArray::try_from_iter(vec![Some(r#"{"a": [{"b": 1}, {"b": 2}]}"#)]).unwrap(); + let bs = json_array.json_path(0, "$.a[*].b").unwrap(); + assert_eq!(bs, Some("[1,2]".to_string())); + } + + #[test] + fn test_json_values_read_either_encoding() { + let docs = vec![Some(r#"{"a":1}"#), None]; + let text: ArrayRef = Arc::new(StringArray::from(docs.clone())); + let jsonb: ArrayRef = Arc::new(JsonArray::try_from_iter(docs).unwrap().into_inner()); + let mut text_field = ArrowField::new("j", DataType::Utf8, true); + text_field.set_metadata(std::collections::HashMap::from([( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + )])); + let jsonb_field = json_field("j", true); + + let from_text = JsonValues::try_new(&text_field, &text).unwrap(); + let from_jsonb = JsonValues::try_new(&jsonb_field, &jsonb).unwrap(); + assert_eq!(from_text.encoding(), JsonEncoding::Text); + assert_eq!(from_jsonb.encoding(), JsonEncoding::Jsonb); + + assert_eq!(&from_text.to_jsonb().unwrap(), jsonb.as_binary::()); + assert_eq!(&from_jsonb.to_jsonb().unwrap(), jsonb.as_binary::()); + assert_eq!(&from_text.to_text(), &text); + let decoded = from_jsonb.to_text(); + let decoded = decoded.as_string::(); + assert_eq!(decoded.value(0), r#"{"a":1}"#); + assert!(decoded.is_null(1)); + + let plain = ArrowField::new("j", DataType::Utf8, true); + assert!(JsonValues::try_new(&plain, &text).is_none()); + } + + #[test] + fn test_convert_json_columns() { + // Create a batch with Arrow JSON column + let json_strings = vec![Some(r#"{"name": "Alice"}"#), Some(r#"{"name": "Bob"}"#)]; + let json_arr = StringArray::from(json_strings); + + // Create field with arrow.json extension + let mut field = ArrowField::new("data", DataType::Utf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(json_arr) as ArrayRef]).unwrap(); + + // Convert the batch + let converted = convert_json_columns(&batch).unwrap(); + + // Check the converted schema + assert_eq!(converted.num_columns(), 1); + let converted_schema = converted.schema(); + let converted_field = converted_schema.field(0); + assert_eq!(converted_field.data_type(), &DataType::LargeBinary); + assert_eq!( + converted_field.metadata().get(ARROW_EXT_NAME_KEY), + Some(&JSON_EXT_NAME.to_string()) + ); + + // Check the data was converted + let converted_column = converted.column(0); + assert_eq!(converted_column.data_type(), &DataType::LargeBinary); + assert_eq!(converted_column.len(), 2); + + // Verify the data is valid JSONB + let binary_array = converted_column + .as_any() + .downcast_ref::() + .unwrap(); + for i in 0..binary_array.len() { + let jsonb_bytes = binary_array.value(i); + let decoded = decode_json(jsonb_bytes); + assert!(decoded.contains("name")); + } + } + + #[test] + fn test_convert_nested_json_columns() { + use arrow_buffer::{OffsetBuffer, ScalarBuffer}; + + let uri_field = Arc::new(ArrowField::new("uri", DataType::Utf8, false)); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + let extra_field = + Arc::new(ArrowField::new("extra", DataType::Utf8, true).with_metadata(metadata)); + let item_fields = Fields::from(vec![uri_field, extra_field]); + + let values = StructArray::new( + item_fields.clone(), + vec![ + Arc::new(StringArray::from(vec![Some("a.jpg"), Some("b.jpg")])) as ArrayRef, + Arc::new(StringArray::from(vec![ + Some(r#"{"codec":"h264"}"#), + None::<&str>, + ])) as ArrayRef, + ], + None, + ); + let item = Arc::new(ArrowField::new("item", DataType::Struct(item_fields), true)); + let media = ListArray::new( + item, + OffsetBuffer::new(ScalarBuffer::from(vec![0, 1, 2])), + Arc::new(values), + None, + ); + let schema = Arc::new(Schema::new(vec![ArrowField::new( + "media", + media.data_type().clone(), + true, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(media) as ArrayRef]).unwrap(); + + assert!(has_arrow_json_fields(batch.schema().field(0))); + + let converted = convert_json_columns(&batch).unwrap(); + let converted_schema = converted.schema(); + let DataType::List(item) = converted_schema.field(0).data_type() else { + panic!("expected list field"); + }; + let DataType::Struct(fields) = item.data_type() else { + panic!("expected struct item"); + }; + assert!(is_json_field(&fields[1])); + + let list_array: &ListArray = converted.column(0).as_list(); + let values = list_array.values().as_struct(); + let extra = values + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(decode_json(extra.value(0)).contains("h264")); + assert!(extra.is_null(1)); + + let logical = convert_lance_json_to_arrow(&converted).unwrap(); + let logical_schema = logical.schema(); + let DataType::List(item) = logical_schema.field(0).data_type() else { + panic!("expected list field"); + }; + let DataType::Struct(fields) = item.data_type() else { + panic!("expected struct item"); + }; + assert!(is_arrow_json_field(&fields[1])); + + let list_array: &ListArray = logical.column(0).as_list(); + let values = list_array.values().as_struct(); + let extra = values + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(extra.value(0).contains("h264")); + assert!(extra.is_null(1)); + } + + #[test] + fn test_convert_fixed_size_list_zero_json_preserves_length() { + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + let item = Arc::new(ArrowField::new("item", DataType::Utf8, true).with_metadata(metadata)); + let values = Arc::new(StringArray::from(Vec::>::new())) as ArrayRef; + let lists = FixedSizeListArray::try_new_with_length(item, 0, values, None, 3).unwrap(); + let schema = Arc::new(Schema::new(vec![ArrowField::new( + "lists", + lists.data_type().clone(), + true, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(lists) as ArrayRef]).unwrap(); + + let converted = convert_json_columns(&batch).unwrap(); + assert_eq!(converted.num_rows(), 3); + assert_eq!(converted.column(0).len(), 3); + + let converted_schema = converted.schema(); + let DataType::FixedSizeList(item, size) = converted_schema.field(0).data_type() else { + panic!("expected fixed size list field"); + }; + assert_eq!(*size, 0); + assert!(is_json_field(item)); + + let logical = convert_lance_json_to_arrow(&converted).unwrap(); + assert_eq!(logical.num_rows(), 3); + assert_eq!(logical.column(0).len(), 3); + + let logical_schema = logical.schema(); + let DataType::FixedSizeList(item, size) = logical_schema.field(0).data_type() else { + panic!("expected fixed size list field"); + }; + assert_eq!(*size, 0); + assert!(is_arrow_json_field(item)); + } + + #[test] + fn test_has_json_fields() { + // Test direct JSON field + let json_f = json_field("data", true); + assert!(has_json_fields(&json_f)); + + // Test non-JSON field + let non_json = ArrowField::new("data", DataType::Utf8, true); + assert!(!has_json_fields(&non_json)); + + // Test struct containing JSON field + let struct_field = ArrowField::new( + "struct", + DataType::Struct(vec![json_field("nested_json", true)].into()), + true, + ); + assert!(has_json_fields(&struct_field)); + + // Test struct without JSON field + let struct_no_json = ArrowField::new( + "struct", + DataType::Struct(vec![ArrowField::new("text", DataType::Utf8, true)].into()), + true, + ); + assert!(!has_json_fields(&struct_no_json)); + + // Test List containing JSON field + let list_field = ArrowField::new( + "list", + DataType::List(Arc::new(json_field("item", true))), + true, + ); + assert!(has_json_fields(&list_field)); + + // Test LargeList containing JSON field + let large_list_field = ArrowField::new( + "large_list", + DataType::LargeList(Arc::new(json_field("item", true))), + true, + ); + assert!(has_json_fields(&large_list_field)); + + // Test FixedSizeList containing JSON field + let fixed_list_field = ArrowField::new( + "fixed_list", + DataType::FixedSizeList(Arc::new(json_field("item", true)), 3), + true, + ); + assert!(has_json_fields(&fixed_list_field)); + + // Test Map containing JSON field + let map_field = ArrowField::new( + "map", + DataType::Map( + Arc::new(ArrowField::new( + "entries", + DataType::Struct( + vec![ + ArrowField::new("key", DataType::Utf8, false), + json_field("value", true), + ] + .into(), + ), + false, + )), + false, + ), + true, + ); + assert!(has_json_fields(&map_field)); + } + + #[test] + fn test_json_array_inner() { + let json_array = JsonArray::try_from_iter(vec![Some(r#"{"a": 1}"#)]).unwrap(); + let inner = json_array.inner(); + assert_eq!(inner.len(), 1); + } + + #[test] + fn test_json_array_value_null_error() { + let json_array = JsonArray::try_from_iter(vec![None::<&str>]).unwrap(); + let result = json_array.value(0); + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("null")); + } + + #[test] + fn test_json_array_value_bytes() { + let json_array = JsonArray::try_from_iter(vec![Some(r#"{"a": 1}"#)]).unwrap(); + let bytes = json_array.value_bytes(0); + assert!(!bytes.is_empty()); + } + + #[test] + fn test_json_path_with_null() { + let json_array = + JsonArray::try_from_iter(vec![Some(r#"{"user": {"name": "Alice"}}"#), None::<&str>]) + .unwrap(); + + let result = json_array.json_path(1, "$.user.name").unwrap(); + assert_eq!(result, None); + } + + #[test] + fn test_to_arrow_json() { + let json_array = JsonArray::try_from_iter(vec![ + Some(r#"{"name": "Alice"}"#), + None::<&str>, + Some(r#"{"name": "Bob"}"#), + ]) + .unwrap(); + + let arrow_json = json_array.to_arrow_json(); + assert_eq!(arrow_json.len(), 3); + assert!(!arrow_json.is_null(0)); + assert!(arrow_json.is_null(1)); + assert!(!arrow_json.is_null(2)); + + let string_array = arrow_json.as_any().downcast_ref::().unwrap(); + assert!(string_array.value(0).contains("Alice")); + assert!(string_array.value(2).contains("Bob")); + } + + #[test] + fn test_json_array_trait_methods() { + let json_array = + JsonArray::try_from_iter(vec![Some(r#"{"a": 1}"#), Some(r#"{"b": 2}"#)]).unwrap(); + + // Wrapper methods + assert_eq!(json_array.len(), 2); + assert!(!json_array.is_empty()); + assert!(!json_array.is_null(0)); + + // Underlying Arrow array + assert_eq!(json_array.inner().data_type(), &DataType::LargeBinary); + assert_eq!(json_array.inner().len(), 2); + } + + #[test] + fn test_json_array_empty() { + let json_array = JsonArray::try_from_iter(Vec::>::new()).unwrap(); + assert!(json_array.is_empty()); + assert_eq!(json_array.len(), 0); + } + + #[test] + fn test_try_from_large_string_array() { + let large_string_array = LargeStringArray::from(vec![ + Some(r#"{"name": "Alice"}"#), + Some(r#"{"name": "Bob"}"#), + None, + ]); + + // Test TryFrom<&LargeStringArray> + let json_array = JsonArray::try_from(&large_string_array).unwrap(); + assert_eq!(json_array.len(), 3); + assert!(!json_array.is_null(0)); + assert!(!json_array.is_null(1)); + assert!(json_array.is_null(2)); + + // Test TryFrom (owned) + let large_string_array2 = LargeStringArray::from(vec![Some(r#"{"x": 1}"#)]); + let json_array2 = JsonArray::try_from(large_string_array2).unwrap(); + assert_eq!(json_array2.len(), 1); + } + + #[test] + fn test_try_from_array_ref() { + // Test with Utf8 + let string_array: ArrayRef = Arc::new(StringArray::from(vec![ + Some(r#"{"a": 1}"#), + Some(r#"{"b": 2}"#), + ])); + let json_array = JsonArray::try_from(string_array).unwrap(); + assert_eq!(json_array.len(), 2); + + // Test with LargeUtf8 + let large_string_array: ArrayRef = Arc::new(LargeStringArray::from(vec![ + Some(r#"{"c": 3}"#), + Some(r#"{"d": 4}"#), + ])); + let json_array2 = JsonArray::try_from(large_string_array).unwrap(); + assert_eq!(json_array2.len(), 2); + + // Test with unsupported type + let int_array: ArrayRef = Arc::new(arrow_array::Int32Array::from(vec![1, 2, 3])); + let result = JsonArray::try_from(int_array); + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("Unsupported")); + } + + #[test] + fn test_arrow_json_to_lance_json_non_json_field() { + // Test that non-JSON fields are returned unchanged + let field = ArrowField::new("text", DataType::Utf8, true); + let converted = arrow_json_to_lance_json(&field); + assert_eq!(converted.data_type(), &DataType::Utf8); + assert_eq!(converted.name(), "text"); + } + + #[test] + fn test_convert_lance_json_to_arrow() { + // Create a batch with Lance JSON column (JSONB) + let json_array = JsonArray::try_from_iter(vec![ + Some(r#"{"name": "Alice"}"#), + None::<&str>, + Some(r#"{"name": "Bob"}"#), + ]) + .unwrap(); + + let lance_json_field = json_field("data", true); + let schema = Arc::new(Schema::new(vec![lance_json_field])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(json_array.into_inner()) as ArrayRef]) + .unwrap(); + + // Convert back to Arrow JSON + let converted = convert_lance_json_to_arrow(&batch).unwrap(); + + // Check schema + let converted_schema = converted.schema(); + let converted_field = converted_schema.field(0); + assert_eq!(converted_field.data_type(), &DataType::Utf8); + assert_eq!( + converted_field.metadata().get(ARROW_EXT_NAME_KEY), + Some(&ARROW_JSON_EXT_NAME.to_string()) + ); + + // Check data + let string_array = converted + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(!string_array.is_null(0)); + assert!(string_array.is_null(1)); + assert!(!string_array.is_null(2)); + assert!(string_array.value(0).contains("Alice")); + assert!(string_array.value(2).contains("Bob")); + } + + #[test] + fn test_convert_lance_json_to_arrow_empty_batch() { + // Create an empty batch with Lance JSON column + let lance_json_field = json_field("data", true); + let schema = Arc::new(Schema::new(vec![lance_json_field])); + let empty_binary = LargeBinaryBuilder::new().finish(); + let batch = RecordBatch::try_new(schema, vec![Arc::new(empty_binary) as ArrayRef]).unwrap(); + + // Convert back to Arrow JSON + let converted = convert_lance_json_to_arrow(&batch).unwrap(); + assert_eq!(converted.num_rows(), 0); + assert_eq!(converted.schema().field(0).data_type(), &DataType::Utf8); + } + + #[test] + fn test_convert_lance_json_to_arrow_no_json_columns() { + // Create a batch without JSON columns + let field = ArrowField::new("text", DataType::Utf8, true); + let schema = Arc::new(Schema::new(vec![field])); + let string_array = StringArray::from(vec![Some("hello"), Some("world")]); + let batch = RecordBatch::try_new(schema, vec![Arc::new(string_array) as ArrayRef]).unwrap(); + + // Convert - should return the same batch + let converted = convert_lance_json_to_arrow(&batch).unwrap(); + assert_eq!(converted.num_columns(), 1); + assert_eq!(converted.schema().field(0).data_type(), &DataType::Utf8); + } + + #[test] + fn test_convert_json_columns_empty_batch() { + // Create an empty batch with Arrow JSON column + let mut field = ArrowField::new("data", DataType::Utf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let empty_strings = arrow_array::builder::StringBuilder::new().finish(); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(empty_strings) as ArrayRef]).unwrap(); + + let converted = convert_json_columns(&batch).unwrap(); + assert_eq!(converted.num_rows(), 0); + assert_eq!( + converted.schema().field(0).data_type(), + &DataType::LargeBinary + ); + } + + #[test] + fn test_convert_json_columns_large_string() { + // Create a batch with Arrow JSON column using LargeUtf8 + let json_strings = LargeStringArray::from(vec![ + Some(r#"{"name": "Alice"}"#), + Some(r#"{"name": "Bob"}"#), + ]); + + let mut field = ArrowField::new("data", DataType::LargeUtf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(json_strings) as ArrayRef]).unwrap(); + + let converted = convert_json_columns(&batch).unwrap(); + assert_eq!(converted.num_columns(), 1); + assert_eq!( + converted.schema().field(0).data_type(), + &DataType::LargeBinary + ); + assert_eq!(converted.num_rows(), 2); + } + + #[test] + fn test_convert_json_columns_no_json_columns() { + // Create a batch without JSON columns + let field = ArrowField::new("text", DataType::Utf8, true); + let schema = Arc::new(Schema::new(vec![field])); + let string_array = StringArray::from(vec![Some("hello"), Some("world")]); + let batch = RecordBatch::try_new(schema, vec![Arc::new(string_array) as ArrayRef]).unwrap(); + + // Convert - should return the same batch + let converted = convert_json_columns(&batch).unwrap(); + assert_eq!(converted.num_columns(), 1); + assert_eq!(converted.schema().field(0).data_type(), &DataType::Utf8); + } + + #[test] + fn test_convert_json_columns_mixed_columns() { + // Create a batch with both JSON and non-JSON columns + let json_strings = StringArray::from(vec![ + Some(r#"{"name": "Alice"}"#), + Some(r#"{"name": "Bob"}"#), + ]); + let text_strings = StringArray::from(vec![Some("hello"), Some("world")]); + + let mut json_field = ArrowField::new("json_data", DataType::Utf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + json_field.set_metadata(metadata); + + let text_field = ArrowField::new("text_data", DataType::Utf8, true); + + let schema = Arc::new(Schema::new(vec![json_field, text_field])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(json_strings) as ArrayRef, + Arc::new(text_strings) as ArrayRef, + ], + ) + .unwrap(); + + let converted = convert_json_columns(&batch).unwrap(); + assert_eq!(converted.num_columns(), 2); + assert_eq!( + converted.schema().field(0).data_type(), + &DataType::LargeBinary + ); + assert_eq!(converted.schema().field(1).data_type(), &DataType::Utf8); + } + + #[test] + fn test_is_arrow_json_field_large_utf8() { + // Test with LargeUtf8 storage type + let mut field = ArrowField::new("data", DataType::LargeUtf8, true); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + assert!(is_arrow_json_field(&field)); + } + + #[test] + fn test_encode_json_invalid() { + // Test encoding invalid JSON + let result = encode_json("not valid json {"); + assert!(result.is_err()); + } + + #[test] + fn test_json_array_from_invalid_json() { + // Test creating JsonArray from invalid JSON strings + let result = JsonArray::try_from_iter(vec![Some("invalid json {")]); + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("Failed to encode")); + } + + #[test] + fn test_try_from_string_array_invalid_json() { + let string_array = StringArray::from(vec![Some("invalid json {")]); + let result = JsonArray::try_from(string_array); + assert!(result.is_err()); + } + + #[test] + fn test_try_from_large_string_array_invalid_json() { + let large_string_array = LargeStringArray::from(vec![Some("invalid json {")]); + let result = JsonArray::try_from(large_string_array); + assert!(result.is_err()); + } + + #[test] + fn test_convert_lance_json_to_arrow_mixed_columns() { + // Create a batch with both JSON and non-JSON columns + let json_array = JsonArray::try_from_iter(vec![ + Some(r#"{"name": "Alice"}"#), + Some(r#"{"name": "Bob"}"#), + ]) + .unwrap(); + let text_strings = StringArray::from(vec![Some("hello"), Some("world")]); + + let json_f = json_field("json_data", true); + let text_field = ArrowField::new("text_data", DataType::Utf8, true); + + let schema = Arc::new(Schema::new(vec![json_f, text_field])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(json_array.into_inner()) as ArrayRef, + Arc::new(text_strings) as ArrayRef, + ], + ) + .unwrap(); + + let converted = convert_lance_json_to_arrow(&batch).unwrap(); + assert_eq!(converted.num_columns(), 2); + assert_eq!(converted.schema().field(0).data_type(), &DataType::Utf8); + assert_eq!(converted.schema().field(1).data_type(), &DataType::Utf8); + } + + #[test] + fn test_json_path_invalid_path() { + let json_array = JsonArray::try_from_iter(vec![Some(r#"{"a": 1}"#)]).unwrap(); + // Invalid JSONPath syntax should return error + let result = json_array.json_path(0, "invalid path without $"); + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("Invalid JSONPath")); + } + + #[test] + fn test_convert_json_columns_invalid_storage_type() { + // Create a batch with Arrow JSON field but wrong storage type (Int32 instead of Utf8) + let int_array = arrow_array::Int32Array::from(vec![1, 2, 3]); + + let mut field = ArrowField::new("data", DataType::Int32, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(int_array) as ArrayRef]).unwrap(); + + // This should succeed since Int32 doesn't match is_arrow_json_field check + // (is_arrow_json_field requires Utf8 or LargeUtf8) + let result = convert_json_columns(&batch); + assert!(result.is_ok()); + } + + #[test] + fn test_is_json_field_wrong_extension() { + // LargeBinary field without the correct extension metadata + let field = ArrowField::new("data", DataType::LargeBinary, true); + assert!(!is_json_field(&field)); + + // LargeBinary field with wrong extension name + let mut field2 = ArrowField::new("data", DataType::LargeBinary, true); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + "other.extension".to_string(), + ); + field2.set_metadata(metadata); + assert!(!is_json_field(&field2)); + } + + #[test] + fn test_is_arrow_json_field_wrong_extension() { + // Utf8 field without extension metadata + let field = ArrowField::new("data", DataType::Utf8, true); + assert!(!is_arrow_json_field(&field)); + + // Utf8 field with wrong extension name + let mut field2 = ArrowField::new("data", DataType::Utf8, true); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + "other.extension".to_string(), + ); + field2.set_metadata(metadata); + assert!(!is_arrow_json_field(&field2)); + + // Wrong type entirely + let field3 = ArrowField::new("data", DataType::Int32, true); + assert!(!is_arrow_json_field(&field3)); + } + + #[test] + fn test_convert_json_columns_invalid_json_utf8() { + // Test error propagation when converting invalid JSON (Utf8) + let invalid_json = StringArray::from(vec![Some("invalid json {")]); + + let mut field = ArrowField::new("data", DataType::Utf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(invalid_json) as ArrayRef]).unwrap(); + + let result = convert_json_columns(&batch); + assert!(result.is_err()); + } + + #[test] + fn test_convert_json_columns_invalid_json_large_utf8() { + // Test error propagation when converting invalid JSON (LargeUtf8) + let invalid_json = LargeStringArray::from(vec![Some("invalid json {")]); + + let mut field = ArrowField::new("data", DataType::LargeUtf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(invalid_json) as ArrayRef]).unwrap(); + + let result = convert_json_columns(&batch); + assert!(result.is_err()); + } + + #[test] + fn test_json_path_on_corrupted_jsonb() { + // Create corrupted JSONB bytes directly + let corrupted_bytes: &[u8] = &[0xFF, 0xFE, 0x00, 0x01, 0x02]; + let corrupted_binary = LargeBinaryArray::from(vec![Some(corrupted_bytes)]); + + // Wrap in JsonArray + let corrupted_json = JsonArray { + inner: corrupted_binary, + }; + + // Try to use json_path on corrupted data - the selector might fail or return unexpected results + // This exercises the code path but may not produce an error depending on jsonb library behavior + let _result = corrupted_json.json_path(0, "$.a"); + // We don't assert on the result as the behavior depends on the jsonb library + } + + #[test] + fn test_decode_json_on_various_inputs() { + // Test decode_json with various inputs + let valid_jsonb = encode_json(r#"{"key": "value"}"#).unwrap(); + let decoded = decode_json(&valid_jsonb); + assert!(decoded.contains("key")); + + // Empty bytes - jsonb library handles this gracefully + let decoded_empty = decode_json(&[]); + // Just verify it doesn't panic + let _ = decoded_empty; + + // Random bytes - jsonb library handles this gracefully + let decoded_random = decode_json(&[0xFF, 0xFE, 0x00]); + // Just verify it doesn't panic + let _ = decoded_random; + } +} diff --git a/python/vendor/lance-arrow/src/lib.rs b/python/vendor/lance-arrow/src/lib.rs new file mode 100644 index 000000000..6c31cf0c5 --- /dev/null +++ b/python/vendor/lance-arrow/src/lib.rs @@ -0,0 +1,3707 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Extend Arrow Functionality +//! +//! To improve Arrow-RS ergonomic + +#![warn(clippy::undocumented_unsafe_blocks)] + +// lance-arrow reinterprets value bytes as native numeric types in +// `FloatArray::as_slice` for `bf16` (rust/lance-arrow/src/bfloat16.rs), which +// requires the host byte order to match the on-disk byte order Lance writes. +// Lance writes little-endian; building on a big-endian target would silently +// produce wrong numeric values. +#[cfg(not(target_endian = "little"))] +compile_error!("lance-arrow only supports little-endian targets"); + +use std::sync::Arc; +use std::{collections::HashMap, ptr::NonNull}; + +use arrow_array::{ + Array, ArrayRef, ArrowNumericType, FixedSizeBinaryArray, FixedSizeListArray, GenericListArray, + LargeListArray, ListArray, MapArray, OffsetSizeTrait, PrimitiveArray, RecordBatch, StructArray, + UInt8Array, UInt32Array, cast::AsArray, +}; +use arrow_array::{ + Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Int64Array, new_null_array, +}; +use arrow_buffer::{BooleanBufferBuilder, MutableBuffer, NullBuffer}; +use arrow_data::ArrayDataBuilder; +use arrow_schema::{ArrowError, DataType, Field, Fields, IntervalUnit, Schema, SortOptions}; +use arrow_select::{interleave::interleave, take::take}; +use rand::prelude::*; + +pub mod deepcopy; +pub mod schema; +pub use schema::*; +pub mod bfloat16; +pub mod floats; +use crate::list::ListArrayExt; +pub use floats::*; + +pub mod ipc; +pub mod json; +pub mod list; +pub mod memory; +pub mod scalar; +pub mod stream; +pub mod r#struct; + +/// Arrow extension metadata key for extension name +pub const ARROW_EXT_NAME_KEY: &str = "ARROW:extension:name"; + +/// Arrow extension metadata key for extension metadata +pub const ARROW_EXT_META_KEY: &str = "ARROW:extension:metadata"; + +/// Key used by lance to mark a field as a blob +/// TODO: Use Arrow extension mechanism instead? +pub const BLOB_META_KEY: &str = "lance-encoding:blob"; +/// Arrow extension type name for Lance blob v2 columns +pub const BLOB_V2_EXT_NAME: &str = "lance.blob.v2"; +/// Metadata key for overriding the dedicated blob size threshold (in bytes) +pub const BLOB_DEDICATED_SIZE_THRESHOLD_META_KEY: &str = + "lance-encoding:blob-dedicated-size-threshold"; +/// Metadata key for overriding the inline blob size threshold (in bytes) +pub const BLOB_INLINE_SIZE_THRESHOLD_META_KEY: &str = "lance-encoding:blob-inline-size-threshold"; +/// Metadata key for overriding the maximum size (in bytes) of a packed blob sidecar file +pub const BLOB_PACK_FILE_SIZE_THRESHOLD_META_KEY: &str = + "lance-encoding:blob-pack-file-size-threshold"; + +type Result = std::result::Result; + +pub trait DataTypeExt { + /// Returns true if the data type is binary-like, such as Utf8, Binary, or the large and/or view variants. + fn is_binary_like(&self) -> bool; + + /// Returns true if the data type is a struct. + fn is_struct(&self) -> bool; + + /// Check whether the given Arrow DataType is fixed stride. + /// + /// A fixed stride type has the same byte width for all array elements + /// This includes all PrimitiveType's Boolean, FixedSizeList, FixedSizeBinary, and Decimals + fn is_fixed_stride(&self) -> bool; + + /// Returns true if the [DataType] is a dictionary type. + fn is_dictionary(&self) -> bool; + + /// Returns the byte width of the data type + /// Panics if the data type is not fixed stride. + fn byte_width(&self) -> usize; + + /// Returns the byte width of the data type, if it is fixed stride. + /// Returns None if the data type is not fixed stride. + fn byte_width_opt(&self) -> Option; +} + +impl DataTypeExt for DataType { + fn is_binary_like(&self) -> bool { + use DataType::*; + matches!( + self, + Utf8 | Binary | LargeUtf8 | LargeBinary | Utf8View | BinaryView + ) + } + + fn is_struct(&self) -> bool { + matches!(self, Self::Struct(_)) + } + + fn is_fixed_stride(&self) -> bool { + use DataType::*; + matches!( + self, + Boolean + | UInt8 + | UInt16 + | UInt32 + | UInt64 + | Int8 + | Int16 + | Int32 + | Int64 + | Float16 + | Float32 + | Float64 + | Decimal128(_, _) + | Decimal256(_, _) + | FixedSizeList(_, _) + | FixedSizeBinary(_) + | Duration(_) + | Timestamp(_, _) + | Date32 + | Date64 + | Time32(_) + | Time64(_) + ) + } + + fn is_dictionary(&self) -> bool { + matches!(self, Self::Dictionary(_, _)) + } + + fn byte_width_opt(&self) -> Option { + match self { + Self::Int8 => Some(1), + Self::Int16 => Some(2), + Self::Int32 => Some(4), + Self::Int64 => Some(8), + Self::UInt8 => Some(1), + Self::UInt16 => Some(2), + Self::UInt32 => Some(4), + Self::UInt64 => Some(8), + Self::Float16 => Some(2), + Self::Float32 => Some(4), + Self::Float64 => Some(8), + Self::Date32 => Some(4), + Self::Date64 => Some(8), + Self::Time32(_) => Some(4), + Self::Time64(_) => Some(8), + Self::Timestamp(_, _) => Some(8), + Self::Duration(_) => Some(8), + Self::Decimal128(_, _) => Some(16), + Self::Decimal256(_, _) => Some(32), + Self::Interval(unit) => match unit { + IntervalUnit::YearMonth => Some(4), + IntervalUnit::DayTime => Some(8), + IntervalUnit::MonthDayNano => Some(16), + }, + Self::FixedSizeBinary(s) => Some(*s as usize), + Self::FixedSizeList(dt, s) => dt + .data_type() + .byte_width_opt() + .map(|width| width * *s as usize), + _ => None, + } + } + + fn byte_width(&self) -> usize { + self.byte_width_opt() + .unwrap_or_else(|| panic!("Expecting fixed stride data type, found {:?}", self)) + } +} + +/// Create an [`GenericListArray`] from values and offsets. +/// +/// ``` +/// use arrow_array::{Int32Array, Int64Array, ListArray}; +/// use arrow_array::types::Int64Type; +/// use lance_arrow::try_new_generic_list_array; +/// +/// let offsets = Int32Array::from_iter([0, 2, 7, 10]); +/// let int_values = Int64Array::from_iter(0..10); +/// let list_arr = try_new_generic_list_array(int_values, &offsets).unwrap(); +/// assert_eq!(list_arr, +/// ListArray::from_iter_primitive::(vec![ +/// Some(vec![Some(0), Some(1)]), +/// Some(vec![Some(2), Some(3), Some(4), Some(5), Some(6)]), +/// Some(vec![Some(7), Some(8), Some(9)]), +/// ])) +/// ``` +pub fn try_new_generic_list_array( + values: T, + offsets: &PrimitiveArray, +) -> Result> +where + Offset::Native: OffsetSizeTrait, +{ + let data_type = if Offset::Native::IS_LARGE { + DataType::LargeList(Arc::new(Field::new( + "item", + values.data_type().clone(), + true, + ))) + } else { + DataType::List(Arc::new(Field::new( + "item", + values.data_type().clone(), + true, + ))) + }; + let data = ArrayDataBuilder::new(data_type) + .len(offsets.len() - 1) + .add_buffer(offsets.into_data().buffers()[0].clone()) + .add_child_data(values.into_data()) + .build()?; + + Ok(GenericListArray::from(data)) +} + +pub fn fixed_size_list_type(list_width: i32, inner_type: DataType) -> DataType { + DataType::FixedSizeList(Arc::new(Field::new("item", inner_type, true)), list_width) +} + +pub trait FixedSizeListArrayExt { + /// Create an [`FixedSizeListArray`] from values and list size. + /// + /// ``` + /// use arrow_array::{Int64Array, FixedSizeListArray}; + /// use arrow_array::types::Int64Type; + /// use lance_arrow::FixedSizeListArrayExt; + /// + /// let int_values = Int64Array::from_iter(0..10); + /// let fixed_size_list_arr = FixedSizeListArray::try_new_from_values(int_values, 2).unwrap(); + /// assert_eq!(fixed_size_list_arr, + /// FixedSizeListArray::from_iter_primitive::(vec![ + /// Some(vec![Some(0), Some(1)]), + /// Some(vec![Some(2), Some(3)]), + /// Some(vec![Some(4), Some(5)]), + /// Some(vec![Some(6), Some(7)]), + /// Some(vec![Some(8), Some(9)]) + /// ], 2)) + /// ``` + fn try_new_from_values( + values: T, + list_size: i32, + ) -> Result; + + /// Sample `n` rows from the [FixedSizeListArray] + /// + /// ``` + /// use arrow_array::{Int64Array, FixedSizeListArray, Array}; + /// use lance_arrow::FixedSizeListArrayExt; + /// + /// let int_values = Int64Array::from_iter(0..256); + /// let fixed_size_list_arr = FixedSizeListArray::try_new_from_values(int_values, 16).unwrap(); + /// let sampled = fixed_size_list_arr.sample(10).unwrap(); + /// assert_eq!(sampled.len(), 10); + /// assert_eq!(sampled.value_length(), 16); + /// assert_eq!(sampled.values().len(), 160); + /// ``` + fn sample(&self, n: usize) -> Result; + + /// Ensure the [FixedSizeListArray] of Float16, Float32, Float64, + /// Int8, Int16, Int32, Int64, UInt8, UInt32 type to its closest floating point type. + fn convert_to_floating_point(&self) -> Result; +} + +impl FixedSizeListArrayExt for FixedSizeListArray { + fn try_new_from_values(values: T, list_size: i32) -> Result { + let field = Arc::new(Field::new("item", values.data_type().clone(), true)); + let values = Arc::new(values); + + Self::try_new(field, list_size, values, None) + } + + fn sample(&self, n: usize) -> Result { + if n >= self.len() { + return Ok(self.clone()); + } + let mut rng = SmallRng::from_os_rng(); + let chosen = (0..self.len() as u32).choose_multiple(&mut rng, n); + take(self, &UInt32Array::from(chosen), None).map(|arr| arr.as_fixed_size_list().clone()) + } + + fn convert_to_floating_point(&self) -> Result { + match self.data_type() { + DataType::FixedSizeList(field, size) => match field.data_type() { + DataType::Float16 | DataType::Float32 | DataType::Float64 => Ok(self.clone()), + DataType::Int8 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float32, + field.is_nullable(), + )), + *size, + Arc::new(Float32Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to Int8Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f32)), + )), + self.nulls().cloned(), + )), + DataType::Int16 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float32, + field.is_nullable(), + )), + *size, + Arc::new(Float32Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to Int16Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f32)), + )), + self.nulls().cloned(), + )), + DataType::Int32 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float32, + field.is_nullable(), + )), + *size, + Arc::new(Float32Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to Int32Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f32)), + )), + self.nulls().cloned(), + )), + DataType::Int64 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float64, + field.is_nullable(), + )), + *size, + Arc::new(Float64Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to Int64Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f64)), + )), + self.nulls().cloned(), + )), + DataType::UInt8 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float64, + field.is_nullable(), + )), + *size, + Arc::new(Float64Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to UInt8Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f64)), + )), + self.nulls().cloned(), + )), + DataType::UInt32 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float64, + field.is_nullable(), + )), + *size, + Arc::new(Float64Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to UInt32Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f64)), + )), + self.nulls().cloned(), + )), + data_type => Err(ArrowError::ParseError(format!( + "Expect either floating type or integer got {:?}", + data_type + ))), + }, + data_type => Err(ArrowError::ParseError(format!( + "Expect either FixedSizeList got {:?}", + data_type + ))), + } + } +} + +/// Force downcast of an [`Array`], such as an [`ArrayRef`], to +/// [`FixedSizeListArray`], panic'ing on failure. +pub fn as_fixed_size_list_array(arr: &dyn Array) -> &FixedSizeListArray { + arr.as_any().downcast_ref::().unwrap() +} + +pub trait FixedSizeBinaryArrayExt { + /// Create an [`FixedSizeBinaryArray`] from values and stride. + /// + /// ``` + /// use arrow_array::{UInt8Array, FixedSizeBinaryArray}; + /// use arrow_array::types::UInt8Type; + /// use lance_arrow::FixedSizeBinaryArrayExt; + /// + /// let int_values = UInt8Array::from_iter(0..10); + /// let fixed_size_list_arr = FixedSizeBinaryArray::try_new_from_values(&int_values, 2).unwrap(); + /// assert_eq!(fixed_size_list_arr, + /// FixedSizeBinaryArray::try_from_iter( + /// [[0u8, 1], [2, 3], [4, 5], [6, 7], [8, 9]].into_iter() + /// ).unwrap()) + /// ``` + fn try_new_from_values(values: &UInt8Array, stride: i32) -> Result; +} + +impl FixedSizeBinaryArrayExt for FixedSizeBinaryArray { + fn try_new_from_values(values: &UInt8Array, stride: i32) -> Result { + let data_type = DataType::FixedSizeBinary(stride); + let data = ArrayDataBuilder::new(data_type) + .len(values.len() / stride as usize) + .add_buffer(values.into_data().buffers()[0].clone()) + .build()?; + Ok(Self::from(data)) + } +} + +pub fn as_fixed_size_binary_array(arr: &dyn Array) -> &FixedSizeBinaryArray { + arr.as_any().downcast_ref::().unwrap() +} + +pub fn iter_str_array(arr: &dyn Array) -> Box> + Send + '_> { + match arr.data_type() { + DataType::Utf8 => Box::new(arr.as_string::().iter()), + DataType::LargeUtf8 => Box::new(arr.as_string::().iter()), + DataType::Utf8View => Box::new(arr.as_string_view().iter()), + _ => panic!( + "Expecting Utf8, LargeUtf8 or Utf8View, found {:?}", + arr.data_type() + ), + } +} + +pub fn iter_binary_array( + arr: &dyn Array, +) -> Result> + Send + '_>> { + match arr.data_type() { + DataType::Binary => Ok(Box::new(arr.as_binary::().iter())), + DataType::LargeBinary => Ok(Box::new(arr.as_binary::().iter())), + DataType::BinaryView => Ok(Box::new(arr.as_binary_view().iter())), + DataType::FixedSizeBinary(_) => Ok(Box::new(arr.as_fixed_size_binary().iter())), + data_type => Err(ArrowError::InvalidArgumentError(format!( + "Expecting a binary type, found {data_type}" + ))), + } +} + +/// Extends Arrow's [RecordBatch]. +pub trait RecordBatchExt { + /// Append a new column to this [`RecordBatch`] and returns a new RecordBatch. + /// + /// ``` + /// use std::sync::Arc; + /// use arrow_array::{RecordBatch, Int32Array, StringArray}; + /// use arrow_schema::{Schema, Field, DataType}; + /// use lance_arrow::*; + /// + /// let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)])); + /// let int_arr = Arc::new(Int32Array::from(vec![1, 2, 3, 4])); + /// let record_batch = RecordBatch::try_new(schema, vec![int_arr.clone()]).unwrap(); + /// + /// let new_field = Field::new("s", DataType::Utf8, true); + /// let str_arr = Arc::new(StringArray::from(vec!["a", "b", "c", "d"])); + /// let new_record_batch = record_batch.try_with_column(new_field, str_arr.clone()).unwrap(); + /// + /// assert_eq!( + /// new_record_batch, + /// RecordBatch::try_new( + /// Arc::new(Schema::new( + /// vec![ + /// Field::new("a", DataType::Int32, true), + /// Field::new("s", DataType::Utf8, true) + /// ]) + /// ), + /// vec![int_arr, str_arr], + /// ).unwrap() + /// ) + /// ``` + fn try_with_column(&self, field: Field, arr: ArrayRef) -> Result; + + /// Created a new RecordBatch with column at index. + fn try_with_column_at(&self, index: usize, field: Field, arr: ArrayRef) -> Result; + + /// Creates a new [`RecordBatch`] from the provided [`StructArray`]. + /// + /// The fields on the [`StructArray`] need to match this [`RecordBatch`] schema + fn try_new_from_struct_array(&self, arr: StructArray) -> Result; + + /// Merge with another [`RecordBatch`] and returns a new one. + /// + /// Fields are merged based on name. First we iterate the left columns. If a matching + /// name is found in the right then we merge the two columns. If there is no match then + /// we add the left column to the output. + /// + /// To merge two columns we consider the type. If both arrays are struct arrays we recurse. + /// Otherwise we use the left array. + /// + /// Afterwards we add all non-matching right columns to the output. + /// + /// Note: This method likely does not handle nested fields correctly and you may want to consider + /// using [`Self::merge_with_schema`] instead. + /// ``` + /// use std::sync::Arc; + /// use arrow_array::*; + /// use arrow_schema::{Schema, Field, DataType}; + /// use lance_arrow::*; + /// + /// let left_schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)])); + /// let int_arr = Arc::new(Int32Array::from(vec![1, 2, 3, 4])); + /// let left = RecordBatch::try_new(left_schema, vec![int_arr.clone()]).unwrap(); + /// + /// let right_schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, true)])); + /// let str_arr = Arc::new(StringArray::from(vec!["a", "b", "c", "d"])); + /// let right = RecordBatch::try_new(right_schema, vec![str_arr.clone()]).unwrap(); + /// + /// let new_record_batch = left.merge(&right).unwrap(); + /// + /// assert_eq!( + /// new_record_batch, + /// RecordBatch::try_new( + /// Arc::new(Schema::new( + /// vec![ + /// Field::new("a", DataType::Int32, true), + /// Field::new("s", DataType::Utf8, true) + /// ]) + /// ), + /// vec![int_arr, str_arr], + /// ).unwrap() + /// ) + /// ``` + /// + /// TODO: add merge nested fields support. + fn merge(&self, other: &RecordBatch) -> Result; + + /// Create a batch by merging columns between two batches with a given schema. + /// + /// A reference schema is used to determine the proper ordering of nested fields. + /// + /// For each field in the reference schema we look for corresponding fields in + /// the left and right batches. If a field is found in both batches we recursively merge + /// it. + /// + /// If a field is only in the left or right batch we take it as it is. + fn merge_with_schema(&self, other: &RecordBatch, schema: &Schema) -> Result; + + /// Drop one column specified with the name and return the new [`RecordBatch`]. + /// + /// If the named column does not exist, it returns a copy of this [`RecordBatch`]. + fn drop_column(&self, name: &str) -> Result; + + /// Replace a column (specified by name) and return the new [`RecordBatch`]. + fn replace_column_by_name(&self, name: &str, column: Arc) -> Result; + + /// Replace a column schema (specified by name) and return the new [`RecordBatch`]. + fn replace_column_schema_by_name( + &self, + name: &str, + new_data_type: DataType, + column: Arc, + ) -> Result; + + /// Rename a column at a given index. + fn rename_column(&self, index: usize, new_name: &str) -> Result; + + /// Get (potentially nested) column by qualified name. + fn column_by_qualified_name(&self, name: &str) -> Option<&ArrayRef>; + + /// Project the schema over the [RecordBatch]. + fn project_by_schema(&self, schema: &Schema) -> Result; + + /// metadata of the schema. + fn metadata(&self) -> &HashMap; + + /// Add metadata to the schema. + fn add_metadata(&self, key: String, value: String) -> Result { + let mut metadata = self.metadata().clone(); + metadata.insert(key, value); + self.with_metadata(metadata) + } + + /// Replace the schema metadata with the provided one. + fn with_metadata(&self, metadata: HashMap) -> Result; + + /// Take selected rows from the [RecordBatch]. + fn take(&self, indices: &UInt32Array) -> Result; + + /// Create a new RecordBatch with compacted memory after slicing. + fn shrink_to_fit(&self) -> Result; + + /// Helper method to sort the RecordBatch by a column + fn sort_by_column(&self, column: usize, options: Option) -> Result; +} + +impl RecordBatchExt for RecordBatch { + fn try_with_column(&self, field: Field, arr: ArrayRef) -> Result { + let new_schema = Arc::new(self.schema().as_ref().try_with_column(field)?); + let mut new_columns = self.columns().to_vec(); + new_columns.push(arr); + Self::try_new(new_schema, new_columns) + } + + fn try_with_column_at(&self, index: usize, field: Field, arr: ArrayRef) -> Result { + let new_schema = Arc::new(self.schema().as_ref().try_with_column_at(index, field)?); + let mut new_columns = self.columns().to_vec(); + new_columns.insert(index, arr); + Self::try_new(new_schema, new_columns) + } + + fn try_new_from_struct_array(&self, arr: StructArray) -> Result { + let schema = Arc::new(Schema::new_with_metadata( + arr.fields().to_vec(), + self.schema().metadata.clone(), + )); + let batch = Self::from(arr); + batch.with_schema(schema) + } + + fn merge(&self, other: &Self) -> Result { + if self.num_rows() != other.num_rows() { + return Err(ArrowError::InvalidArgumentError(format!( + "Attempt to merge two RecordBatch with different sizes: {} != {}", + self.num_rows(), + other.num_rows() + ))); + } + let left_struct_array: StructArray = self.clone().into(); + let right_struct_array: StructArray = other.clone().into(); + self.try_new_from_struct_array(merge(&left_struct_array, &right_struct_array)?) + } + + fn merge_with_schema(&self, other: &RecordBatch, schema: &Schema) -> Result { + if self.num_rows() != other.num_rows() { + return Err(ArrowError::InvalidArgumentError(format!( + "Attempt to merge two RecordBatch with different sizes: {} != {}", + self.num_rows(), + other.num_rows() + ))); + } + let left_struct_array: StructArray = self.clone().into(); + let right_struct_array: StructArray = other.clone().into(); + self.try_new_from_struct_array(merge_with_schema( + &left_struct_array, + &right_struct_array, + schema.fields(), + )) + } + + fn drop_column(&self, name: &str) -> Result { + let mut fields = vec![]; + let mut columns = vec![]; + for i in 0..self.schema().fields.len() { + if self.schema().field(i).name() != name { + fields.push(self.schema().field(i).clone()); + columns.push(self.column(i).clone()); + } + } + Self::try_new( + Arc::new(Schema::new_with_metadata( + fields, + self.schema().metadata().clone(), + )), + columns, + ) + } + + fn rename_column(&self, index: usize, new_name: &str) -> Result { + let mut fields = self.schema().fields().to_vec(); + if index >= fields.len() { + return Err(ArrowError::InvalidArgumentError(format!( + "Index out of bounds: {}", + index + ))); + } + fields[index] = Arc::new(Field::new( + new_name, + fields[index].data_type().clone(), + fields[index].is_nullable(), + )); + Self::try_new( + Arc::new(Schema::new_with_metadata( + fields, + self.schema().metadata().clone(), + )), + self.columns().to_vec(), + ) + } + + fn replace_column_by_name(&self, name: &str, column: Arc) -> Result { + let mut columns = self.columns().to_vec(); + let field_i = self + .schema() + .fields() + .iter() + .position(|f| f.name() == name) + .ok_or_else(|| ArrowError::SchemaError(format!("Field {} does not exist", name)))?; + columns[field_i] = column; + Self::try_new(self.schema(), columns) + } + + fn replace_column_schema_by_name( + &self, + name: &str, + new_data_type: DataType, + column: Arc, + ) -> Result { + let fields = self + .schema() + .fields() + .iter() + .map(|x| { + if x.name() != name { + x.clone() + } else { + let new_field = Field::new(name, new_data_type.clone(), x.is_nullable()); + Arc::new(new_field) + } + }) + .collect::>(); + let schema = Schema::new_with_metadata(fields, self.schema().metadata.clone()); + let mut columns = self.columns().to_vec(); + let field_i = self + .schema() + .fields() + .iter() + .position(|f| f.name() == name) + .ok_or_else(|| ArrowError::SchemaError(format!("Field {} does not exist", name)))?; + columns[field_i] = column; + Self::try_new(Arc::new(schema), columns) + } + + fn column_by_qualified_name(&self, name: &str) -> Option<&ArrayRef> { + let split = name.split('.').collect::>(); + if split.is_empty() { + return None; + } + + self.column_by_name(split[0]) + .and_then(|arr| get_sub_array(arr, &split[1..])) + } + + fn project_by_schema(&self, schema: &Schema) -> Result { + let struct_array: StructArray = self.clone().into(); + self.try_new_from_struct_array(project(&struct_array, schema.fields())?) + } + + fn metadata(&self) -> &HashMap { + self.schema_ref().metadata() + } + + fn with_metadata(&self, metadata: HashMap) -> Result { + let mut schema = self.schema_ref().as_ref().clone(); + schema.metadata = metadata; + Self::try_new(schema.into(), self.columns().into()) + } + + fn take(&self, indices: &UInt32Array) -> Result { + let struct_array: StructArray = self.clone().into(); + let taken = take(&struct_array, indices, None)?; + self.try_new_from_struct_array(taken.as_struct().clone()) + } + + fn shrink_to_fit(&self) -> Result { + // Deep copy the sliced record batch, instead of whole batch + crate::deepcopy::deep_copy_batch_sliced(self) + } + + fn sort_by_column(&self, column: usize, options: Option) -> Result { + if column >= self.num_columns() { + return Err(ArrowError::InvalidArgumentError(format!( + "Column index out of bounds: {}", + column + ))); + } + let column = self.column(column); + let sorted = arrow_ord::sort::sort_to_indices(column, options, None)?; + self.take(&sorted) + } +} + +/// Recursively projects an array to match the target field's structure. +/// This handles reordering fields inside nested List types. +fn project_array(array: &ArrayRef, target_field: &Field) -> Result { + match target_field.data_type() { + DataType::Struct(subfields) => { + let struct_arr = array.as_struct(); + let projected = project(struct_arr, subfields)?; + Ok(Arc::new(projected)) + } + DataType::List(inner_field) => { + let list_arr: &ListArray = array.as_list(); + let projected_values = project_array(list_arr.values(), inner_field.as_ref())?; + Ok(Arc::new(ListArray::new( + inner_field.clone(), + list_arr.offsets().clone(), + projected_values, + list_arr.nulls().cloned(), + ))) + } + DataType::LargeList(inner_field) => { + let list_arr: &LargeListArray = array.as_list(); + let projected_values = project_array(list_arr.values(), inner_field.as_ref())?; + Ok(Arc::new(LargeListArray::new( + inner_field.clone(), + list_arr.offsets().clone(), + projected_values, + list_arr.nulls().cloned(), + ))) + } + DataType::FixedSizeList(inner_field, size) => { + let list_arr = array.as_fixed_size_list(); + let projected_values = project_array(list_arr.values(), inner_field.as_ref())?; + Ok(Arc::new(FixedSizeListArray::new( + inner_field.clone(), + *size, + projected_values, + list_arr.nulls().cloned(), + ))) + } + // A nullable entries field fails MapArray::try_new unconditionally, + // so a (schema-invalid) map declared that way keeps the clone + // fallthrough it always had rather than gaining a new error. + DataType::Map(entries_field, sorted) if !entries_field.is_nullable() => { + let map_arr = array.as_map(); + let DataType::Struct(entry_fields) = entries_field.data_type() else { + return Err(ArrowError::SchemaError(format!( + "Map entries field must be a struct, got {}", + entries_field.data_type() + ))); + }; + let projected_entries = project(map_arr.entries(), entry_fields)?; + // try_new re-checks the entries invariants (a non-null entries + // struct, two entry columns, offset bounds); null keys are ruled + // out one level down, by the struct rebuild against the + // non-nullable key field. + Ok(Arc::new(MapArray::try_new( + entries_field.clone(), + map_arr.offsets().clone(), + projected_entries, + map_arr.nulls().cloned(), + *sorted, + )?)) + } + _ => Ok(array.clone()), + } +} + +fn project(struct_array: &StructArray, fields: &Fields) -> Result { + if fields.is_empty() { + return Ok(StructArray::new_empty_fields( + struct_array.len(), + struct_array.nulls().cloned(), + )); + } + let mut columns: Vec = vec![]; + for field in fields.iter() { + if let Some(col) = struct_array.column_by_name(field.name()) { + let projected = project_array(col, field.as_ref())?; + columns.push(projected); + } else { + return Err(ArrowError::SchemaError(format!( + "field {} does not exist in the RecordBatch", + field.name() + ))); + } + } + // Preserve the struct's validity when projecting + StructArray::try_new(fields.clone(), columns, struct_array.nulls().cloned()) +} + +/// Whether `data_type` has a struct somewhere below it, through lists. +fn holds_struct(data_type: &DataType) -> bool { + match data_type { + DataType::Struct(_) => true, + DataType::List(item) | DataType::LargeList(item) => holds_struct(item.data_type()), + _ => false, + } +} + +/// The values of `list`, with the items of every entry that is null in `list` +/// but valid in `other` made null. Those entries become valid when the two +/// lists are merged, and their items here were never meant to be read. Merging +/// the items then pushes these nulls into their children. +fn hide_items_revealed_by( + list: &GenericListArray, + other: Option<&NullBuffer>, +) -> ArrayRef { + let Some(nulls) = list.nulls() else { + return list.values().clone(); + }; + let revealed = match other { + Some(other) => other.inner() & &!nulls.inner(), + None => !nulls.inner(), + }; + if revealed.count_set_bits() == 0 { + return list.values().clone(); + } + let offsets = list.value_offsets(); + let mut items_validity = BooleanBufferBuilder::new(list.values().len()); + items_validity.append_n(list.values().len(), true); + for row in revealed.set_indices() { + for item in offsets[row].as_usize()..offsets[row + 1].as_usize() { + items_validity.set_bit(item, false); + } + } + adjust_child_validity( + list.values(), + Some(&NullBuffer::new(items_validity.finish())), + ) +} + +/// Merge the values of two lists: structs field by field, nested lists +/// recursively, anything else keeps the left side. +fn merge_list_values(left: &ArrayRef, right: &ArrayRef) -> Result { + Ok(match (left.data_type(), right.data_type()) { + (DataType::Struct(_), DataType::Struct(_)) => { + Arc::new(merge(left.as_struct(), right.as_struct())?) + } + (DataType::List(_), DataType::List(_)) + | (DataType::LargeList(_), DataType::LargeList(_)) + if left.data_type() != right.data_type() + && holds_struct(left.data_type()) + && holds_struct(right.data_type()) => + { + merge_list_struct(left, right, None, None)? + } + _ => left.clone(), + }) +} + +fn merge_list_struct_helper( + left: &dyn Array, + right: &dyn Array, + null_left: bool, + null_right: bool, +) -> Result { + let left_list: &GenericListArray = left.as_list(); + let right_list: &GenericListArray = right.as_list(); + let ((DataType::List(left_item), DataType::List(right_item)) + | (DataType::LargeList(left_item), DataType::LargeList(right_item))) = + (left.data_type(), right.data_type()) + else { + unreachable!() + }; + let (merged_items, list, nulls, items_nullable) = if null_left || null_right { + // One side all-null (a placeholder for columns this fragment lacks) has + // no values, so stand in nulls shaped like the other side's. + let not_null = if null_left { right_list } else { left_list }; + let values_len = not_null.values().len(); + let values = |list: &GenericListArray, is_null: bool| { + if is_null { + new_null_array(list.values().data_type(), values_len) + } else { + list.values().clone() + } + }; + let merged = merge_list_values( + &values(left_list, null_left), + &values(right_list, null_right), + )?; + ( + merged, + not_null, + not_null.nulls().cloned(), + left_item.is_nullable() || right_item.is_nullable(), + ) + } else { + if left_list.offsets().inner() != right_list.offsets().inner() { + panic!("Attempt to merge list struct arrays which do not have same offsets"); + } + // The lists share offsets, and an entry is valid if either side has it, + // as for struct rows. Each side's items under its own null entries are + // hidden first, so the other side's validity cannot expose them. + let left_items = hide_items_revealed_by(left_list, right_list.nulls()); + let right_items = hide_items_revealed_by(right_list, left_list.nulls()); + let merged = merge_list_values(&left_items, &right_items)?; + ( + merged, + left_list, + merge_struct_validity(left_list.nulls(), right_list.nulls()), + left_item.is_nullable() || right_item.is_nullable(), + ) + }; + let items_field = Arc::new(Field::new( + left_item.name(), + merged_items.data_type().clone(), + items_nullable, + )); + Ok(Arc::new(GenericListArray::::new( + items_field, + list.offsets().clone(), + merged_items, + nulls, + ))) +} + +/// Merge two lists whose items hold structs. Only succeeds if both lists have +/// the same offsets or one of them is all-null; panics otherwise. +/// +/// `left_parent` and `right_parent`, when given, null each side's entries under +/// its null parent rows before the merge. +fn merge_list_struct( + left: &ArrayRef, + right: &ArrayRef, + left_parent: Option<&NullBuffer>, + right_parent: Option<&NullBuffer>, +) -> Result { + // The parents are applied before the all-null side is picked, so a side + // whose rows all sit under null parents counts as the placeholder and the + // other side's offsets are kept. + let left = adjust_child_validity(left, left_parent); + let right = adjust_child_validity(right, right_parent); + let null_left = left.null_count() == left.len(); + let null_right = !null_left && right.null_count() == right.len(); + let (left, right) = (left.as_ref(), right.as_ref()); + match (left.data_type(), right.data_type()) { + (DataType::List(_), DataType::List(_)) => { + merge_list_struct_helper::(left, right, null_left, null_right) + } + (DataType::LargeList(_), DataType::LargeList(_)) => { + merge_list_struct_helper::(left, right, null_left, null_right) + } + _ => unreachable!(), + } +} + +/// Helper function to merge validity buffers from two struct arrays. +/// +/// A row is valid if it is valid in either input. +/// An absent validity buffer means all rows are valid, an all-null buffer acts as the identity for this merge. +fn merge_struct_validity( + left_validity: Option<&arrow_buffer::NullBuffer>, + right_validity: Option<&arrow_buffer::NullBuffer>, +) -> Option { + match (left_validity, right_validity) { + // Fast paths: no computation needed + (None, _) | (_, None) => None, + (Some(left), Some(right)) => { + if left.null_count() == 0 || right.null_count() == 0 { + return None; + } + if left.null_count() == left.len() { + return Some(right.clone()); + } + if right.null_count() == right.len() { + return Some(left.clone()); + } + + let left_buffer = left.inner(); + let right_buffer = right.inner(); + + // Perform bitwise OR directly on BooleanBuffers + // This preserves the correct semantics: 1 = valid, 0 = null + let merged_buffer = left_buffer | right_buffer; + + Some(arrow_buffer::NullBuffer::from(merged_buffer)) + } + } +} + +fn merge_list_child_values( + child_field: &Field, + left_values: ArrayRef, + right_values: ArrayRef, +) -> ArrayRef { + match child_field.data_type() { + DataType::Struct(child_fields) => Arc::new(merge_with_schema( + left_values.as_struct(), + right_values.as_struct(), + child_fields, + )) as ArrayRef, + DataType::List(grandchild) => { + let left_list = left_values + .as_any() + .downcast_ref::() + .expect("left list values should be ListArray"); + let right_list = right_values + .as_any() + .downcast_ref::() + .expect("right list values should be ListArray"); + let merged_values = merge_list_child_values( + grandchild.as_ref(), + left_list.values().clone(), + right_list.values().clone(), + ); + let merged_validity = merge_struct_validity(left_list.nulls(), right_list.nulls()); + Arc::new(ListArray::new( + grandchild.clone(), + left_list.offsets().clone(), + merged_values, + merged_validity, + )) as ArrayRef + } + DataType::LargeList(grandchild) => { + let left_list = left_values + .as_any() + .downcast_ref::() + .expect("left list values should be LargeListArray"); + let right_list = right_values + .as_any() + .downcast_ref::() + .expect("right list values should be LargeListArray"); + let merged_values = merge_list_child_values( + grandchild.as_ref(), + left_list.values().clone(), + right_list.values().clone(), + ); + let merged_validity = merge_struct_validity(left_list.nulls(), right_list.nulls()); + Arc::new(LargeListArray::new( + grandchild.clone(), + left_list.offsets().clone(), + merged_values, + merged_validity, + )) as ArrayRef + } + DataType::FixedSizeList(grandchild, list_size) => { + let left_list = left_values + .as_any() + .downcast_ref::() + .expect("left list values should be FixedSizeListArray"); + let right_list = right_values + .as_any() + .downcast_ref::() + .expect("right list values should be FixedSizeListArray"); + let merged_values = merge_list_child_values( + grandchild.as_ref(), + left_list.values().clone(), + right_list.values().clone(), + ); + let merged_validity = merge_struct_validity(left_list.nulls(), right_list.nulls()); + Arc::new(FixedSizeListArray::new( + grandchild.clone(), + *list_size, + merged_values, + merged_validity, + )) as ArrayRef + } + _ => left_values.clone(), + } +} + +// Helper function to adjust child array validity based on parent struct validity +// When parent struct is null, propagates null to child array +// Optimized with fast paths and SIMD operations +fn adjust_child_validity( + child: &ArrayRef, + parent_validity: Option<&arrow_buffer::NullBuffer>, +) -> ArrayRef { + // Fast path: no parent validity means no adjustment needed + let parent_validity = match parent_validity { + None => return child.clone(), + Some(p) if p.null_count() == 0 => return child.clone(), // No nulls to propagate + Some(p) => p, + }; + + // Fast path: DataType::Null arrays are always entirely null by definition and cannot + // carry an explicit null bitmap (Arrow rejects it). No adjustment is needed. + if child.data_type() == &DataType::Null { + return child.clone(); + } + + let child_validity = child.nulls(); + + // Compute the new validity: child_validity AND parent_validity + let new_validity = match child_validity { + None => { + // Fast path: child has no existing validity, just use parent's + parent_validity.clone() + } + Some(child_nulls) => { + let child_buffer = child_nulls.inner(); + let parent_buffer = parent_validity.inner(); + + // Perform bitwise AND directly on BooleanBuffers + // This preserves the correct semantics: 1 = valid, 0 = null + let merged_buffer = child_buffer & parent_buffer; + + arrow_buffer::NullBuffer::from(merged_buffer) + } + }; + + // ArrayData keeps the child's offset for its value buffers. Its null bitmap + // must cover that offset too, even though the merged validity describes only + // the visible rows. Copy logical bits into an offset-aligned bitmap when needed. + let null_bit_buffer = if child.offset() == 0 && new_validity.inner().offset() == 0 { + new_validity.into_inner().into_inner() + } else { + let mut builder = + arrow_buffer::builder::BooleanBufferBuilder::new(child.offset() + child.len()); + builder.append_n(child.offset(), true); + builder.append_buffer(new_validity.inner()); + builder.build().into_inner() + }; + + // Create new array with adjusted validity + arrow_array::make_array( + arrow_data::ArrayData::try_new( + child.data_type().clone(), + child.len(), + Some(null_bit_buffer), + child.offset(), + child.to_data().buffers().to_vec(), + child.to_data().child_data().to_vec(), + ) + .unwrap(), + ) +} + +/// Fails if `field`, a non-nullable child of one side's struct, sits under a +/// row that is null on that side but valid in `merged`. The merged row is valid +/// because the other side has it, and this side has no value to show there. +fn check_hideable( + field: &Field, + parent: Option<&NullBuffer>, + merged: Option<&NullBuffer>, +) -> Result<()> { + let Some(parent) = parent.filter(|_| !field.is_nullable()) else { + return Ok(()); + }; + let revealed = match merged { + Some(merged) => merged.inner() & &!parent.inner(), + None => !parent.inner(), + }; + match revealed.set_indices().next() { + None => Ok(()), + Some(row) => Err(ArrowError::InvalidArgumentError(format!( + "Cannot merge non-nullable field '{}': its parent is null on one side but valid \ + on the other at row {row}, where the field has no value", + field.name() + ))), + } +} + +/// `column`, a child of one side's struct, with that struct's null rows pushed +/// into it. The merged struct is valid where either side is, so the column +/// would otherwise show, at a row only the other side has, what its own null +/// parent hides. +fn hide_under_parent( + field: &Field, + column: &ArrayRef, + parent: Option<&NullBuffer>, + merged: Option<&NullBuffer>, +) -> Result { + check_hideable(field, parent, merged)?; + Ok(adjust_child_validity(column, parent)) +} + +fn merge(left_struct_array: &StructArray, right_struct_array: &StructArray) -> Result { + let mut fields: Vec = vec![]; + let mut columns: Vec = vec![]; + let right_fields = right_struct_array.fields(); + let right_columns = right_struct_array.columns(); + + // Get the validity buffers from both structs + let left_validity = left_struct_array.nulls(); + let right_validity = right_struct_array.nulls(); + + // Compute merged validity + let merged_validity = merge_struct_validity(left_validity, right_validity); + let merged = merged_validity.as_ref(); + + // iterate through the fields on the left hand side + for (left_field, left_column) in left_struct_array + .fields() + .iter() + .zip(left_struct_array.columns().iter()) + { + match right_fields + .iter() + .position(|f| f.name() == left_field.name()) + { + // if the field exists on the right hand side, merge them recursively if appropriate + Some(right_index) => { + let right_field = right_fields.get(right_index).unwrap(); + let right_column = right_columns.get(right_index).unwrap(); + // if both fields are struct, merge them recursively + match (left_field.data_type(), right_field.data_type()) { + (DataType::Struct(_), DataType::Struct(_)) => { + // Both sides feed this column, so a row one side's parent + // hides can still take its value from the other side, and + // the field's nullability is checked on the merged result. + let left_sub_array = adjust_child_validity(left_column, left_validity); + let right_sub_array = adjust_child_validity(right_column, right_validity); + let merged_sub_array = + merge(left_sub_array.as_struct(), right_sub_array.as_struct())?; + fields.push(Field::new( + left_field.name(), + merged_sub_array.data_type().clone(), + left_field.is_nullable(), + )); + columns.push(Arc::new(merged_sub_array) as ArrayRef); + } + (DataType::List(left_list), DataType::List(right_list)) + | (DataType::LargeList(left_list), DataType::LargeList(right_list)) + if holds_struct(left_list.data_type()) + && holds_struct(right_list.data_type()) => + { + // Identical inner types: nothing to merge, keep the left column. + if left_list.data_type() == right_list.data_type() { + fields.push(left_field.as_ref().clone()); + columns.push(hide_under_parent( + left_field, + left_column, + left_validity, + merged, + )?); + } else { + // The struct fields differ, so merge them structurally. merge_list_struct + // only succeeds when both lists share offsets or one side is all-null; + // it panics otherwise. + let merged_sub_array = merge_list_struct( + left_column, + right_column, + left_validity, + right_validity, + )?; + + fields.push(Field::new( + left_field.name(), + merged_sub_array.data_type().clone(), + left_field.is_nullable(), + )); + columns.push(merged_sub_array); + } + } + // otherwise, just use the field on the left hand side + _ => { + // TODO handle list-of-struct and other types + fields.push(left_field.as_ref().clone()); + columns.push(hide_under_parent( + left_field, + left_column, + left_validity, + merged, + )?); + } + } + } + None => { + fields.push(left_field.as_ref().clone()); + columns.push(hide_under_parent( + left_field, + left_column, + left_validity, + merged, + )?); + } + } + } + + // now iterate through the fields on the right hand side + for (field, column) in right_fields.iter().zip(right_columns.iter()) { + // add new columns on the right + if !left_struct_array + .fields() + .iter() + .any(|f| f.name() == field.name()) + { + fields.push(field.as_ref().clone()); + columns.push(hide_under_parent(field, column, right_validity, merged)?); + } + } + + StructArray::try_new(Fields::from(fields), columns, merged_validity) +} + +fn merge_with_schema( + left_struct_array: &StructArray, + right_struct_array: &StructArray, + fields: &Fields, +) -> StructArray { + // Helper function that returns true if both types are struct or both are non-struct + fn same_type_kind(left: &DataType, right: &DataType) -> bool { + match (left, right) { + (DataType::Struct(_), DataType::Struct(_)) => true, + (DataType::Struct(_), _) => false, + (_, DataType::Struct(_)) => false, + _ => true, + } + } + + let mut output_fields: Vec = Vec::with_capacity(fields.len()); + let mut columns: Vec = Vec::with_capacity(fields.len()); + + let left_fields = left_struct_array.fields(); + let left_columns = left_struct_array.columns(); + let right_fields = right_struct_array.fields(); + let right_columns = right_struct_array.columns(); + + // Get the validity buffers from both structs + let left_validity = left_struct_array.nulls(); + let right_validity = right_struct_array.nulls(); + + // Compute merged validity + let merged_validity = merge_struct_validity(left_validity, right_validity); + + for field in fields { + let left_match_idx = left_fields.iter().position(|f| { + f.name() == field.name() && same_type_kind(f.data_type(), field.data_type()) + }); + let right_match_idx = right_fields.iter().position(|f| { + f.name() == field.name() && same_type_kind(f.data_type(), field.data_type()) + }); + + match (left_match_idx, right_match_idx) { + (None, Some(right_idx)) => { + output_fields.push(right_fields[right_idx].as_ref().clone()); + // Adjust validity if the right struct was null + let adjusted_column = + adjust_child_validity(&right_columns[right_idx], right_validity); + columns.push(adjusted_column); + } + (Some(left_idx), None) => { + output_fields.push(left_fields[left_idx].as_ref().clone()); + // Adjust validity if the left struct was null + let adjusted_column = adjust_child_validity(&left_columns[left_idx], left_validity); + columns.push(adjusted_column); + } + (Some(left_idx), Some(right_idx)) => { + match field.data_type() { + DataType::Struct(child_fields) => { + let left_sub_array = left_columns[left_idx].as_struct(); + let right_sub_array = right_columns[right_idx].as_struct(); + let merged_sub_array = + merge_with_schema(left_sub_array, right_sub_array, child_fields); + output_fields.push(Field::new( + field.name(), + merged_sub_array.data_type().clone(), + field.is_nullable(), + )); + columns.push(Arc::new(merged_sub_array) as ArrayRef); + } + DataType::List(child_field) => { + let left_list = left_columns[left_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let right_list = right_columns[right_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let merged_values = merge_list_child_values( + child_field.as_ref(), + left_list.trimmed_values(), + right_list.trimmed_values(), + ); + let merged_validity = + merge_struct_validity(left_list.nulls(), right_list.nulls()); + // `trimmed_values` starts at the first used value, so offsets + // must be shifted to match or `ListArray::new` panics when the + // input list was sliced (e.g. from a filtered batch). + let merged_list = ListArray::new( + child_field.clone(), + left_list.trimmed_offsets(), + merged_values, + merged_validity, + ); + output_fields.push(field.as_ref().clone()); + columns.push(Arc::new(merged_list) as ArrayRef); + } + DataType::LargeList(child_field) => { + let left_list = left_columns[left_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let right_list = right_columns[right_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let merged_values = merge_list_child_values( + child_field.as_ref(), + left_list.trimmed_values(), + right_list.trimmed_values(), + ); + let merged_validity = + merge_struct_validity(left_list.nulls(), right_list.nulls()); + let merged_list = LargeListArray::new( + child_field.clone(), + left_list.trimmed_offsets(), + merged_values, + merged_validity, + ); + output_fields.push(field.as_ref().clone()); + columns.push(Arc::new(merged_list) as ArrayRef); + } + DataType::FixedSizeList(child_field, list_size) => { + let left_list = left_columns[left_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let right_list = right_columns[right_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let merged_values = merge_list_child_values( + child_field.as_ref(), + left_list.values().clone(), + right_list.values().clone(), + ); + let merged_validity = + merge_struct_validity(left_list.nulls(), right_list.nulls()); + let merged_list = FixedSizeListArray::new( + child_field.clone(), + *list_size, + merged_values, + merged_validity, + ); + output_fields.push(field.as_ref().clone()); + columns.push(Arc::new(merged_list) as ArrayRef); + } + _ => { + output_fields.push(left_fields[left_idx].as_ref().clone()); + // For fields that exist in both, use left but adjust validity + let adjusted_column = + adjust_child_validity(&left_columns[left_idx], left_validity); + columns.push(adjusted_column); + } + } + } + (None, None) => { + // The field will not be included in the output + } + } + } + + StructArray::try_new(Fields::from(output_fields), columns, merged_validity).unwrap() +} + +fn get_sub_array<'a>(array: &'a ArrayRef, components: &[&str]) -> Option<&'a ArrayRef> { + if components.is_empty() { + return Some(array); + } + if !matches!(array.data_type(), DataType::Struct(_)) { + return None; + } + let struct_arr = array.as_struct(); + struct_arr + .column_by_name(components[0]) + .and_then(|arr| get_sub_array(arr, &components[1..])) +} + +/// Interleave multiple RecordBatches into a single RecordBatch. +/// +/// Behaves like [`arrow_select::interleave::interleave`], but for RecordBatches. +pub fn interleave_batches( + batches: &[RecordBatch], + indices: &[(usize, usize)], +) -> Result { + let first_batch = batches.first().ok_or_else(|| { + ArrowError::InvalidArgumentError("Cannot interleave zero RecordBatches".to_string()) + })?; + let schema = first_batch.schema(); + let num_columns = first_batch.num_columns(); + let mut columns = Vec::with_capacity(num_columns); + let mut chunks = Vec::with_capacity(batches.len()); + + for i in 0..num_columns { + for batch in batches { + chunks.push(batch.column(i).as_ref()); + } + let new_column = interleave(&chunks, indices)?; + columns.push(new_column); + chunks.clear(); + } + + RecordBatch::try_new(schema, columns) +} + +pub trait BufferExt { + /// Create an `arrow_buffer::Buffer`` from a `bytes::Bytes` object + /// + /// The alignment must be specified (as `bytes_per_value`) since we want to make + /// sure we can safely reinterpret the buffer. + /// + /// If the buffer is properly aligned this will be zero-copy. If not, a copy + /// will be made and an owned buffer returned. + /// + /// If `bytes_per_value` is not a power of two, then we assume the buffer is + /// never going to be reinterpreted into another type and we can safely + /// ignore the alignment. + /// + /// Yes, the method name is odd. It's because there is already a `from_bytes` + /// which converts from `arrow_buffer::bytes::Bytes` (not `bytes::Bytes`) + fn from_bytes_bytes(bytes: bytes::Bytes, bytes_per_value: u64) -> Self; + + /// Allocates a new properly aligned arrow buffer and copies `bytes` into it + /// + /// `size_bytes` can be larger than `bytes` and, if so, the trailing bytes will + /// be zeroed out. + /// + /// # Panics + /// + /// Panics if `size_bytes` is less than `bytes.len()` + fn copy_bytes_bytes(bytes: bytes::Bytes, size_bytes: usize) -> Self; +} + +fn is_pwr_two(n: u64) -> bool { + n & (n - 1) == 0 +} + +impl BufferExt for arrow_buffer::Buffer { + fn from_bytes_bytes(bytes: bytes::Bytes, bytes_per_value: u64) -> Self { + if is_pwr_two(bytes_per_value) && bytes.as_ptr().align_offset(bytes_per_value as usize) != 0 + { + // The original buffer is not aligned, cannot zero-copy + let size_bytes = bytes.len(); + Self::copy_bytes_bytes(bytes, size_bytes) + } else { + // The original buffer is aligned, can zero-copy + // SAFETY: the alignment is correct we can make this conversion + unsafe { + Self::from_custom_allocation( + NonNull::new(bytes.as_ptr() as _).expect("should be a valid pointer"), + bytes.len(), + Arc::new(bytes), + ) + } + } + } + + fn copy_bytes_bytes(bytes: bytes::Bytes, size_bytes: usize) -> Self { + assert!(size_bytes >= bytes.len()); + let mut buf = MutableBuffer::with_capacity(size_bytes); + let to_fill = size_bytes - bytes.len(); + buf.extend(bytes); + buf.extend(std::iter::repeat_n(0_u8, to_fill)); + + // FIX for issue #4512: Shrink buffer to actual size before converting to immutable + // This reduces memory overhead from capacity over-allocation + buf.shrink_to_fit(); + + Self::from(buf) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::types::Int32Type; + use arrow_array::{ + BinaryArray, BinaryViewArray, BooleanArray, FixedSizeBinaryArray, Float32Array, Int32Array, + LargeBinaryArray, ListArray, NullArray, StringArray, StructArray, new_empty_array, + new_null_array, + }; + use arrow_buffer::OffsetBuffer; + + #[test] + fn test_adjust_child_validity_with_sliced_child() { + let child: ArrayRef = Arc::new(BooleanArray::from_iter((0..1030).map(|index| { + if index == 1027 { + None + } else { + Some(index % 2 == 1) + } + }))); + let child = child.slice(1025, 4); + assert_eq!(child.offset(), 1025); + + let parent_validity = arrow_buffer::NullBuffer::from(vec![true, false, true, true]); + let adjusted = adjust_child_validity(&child, Some(&parent_validity)); + assert_eq!(adjusted.offset(), child.offset()); + let adjusted = adjusted.as_any().downcast_ref::().unwrap(); + assert_eq!( + adjusted.iter().collect::>(), + vec![Some(true), None, None, Some(false)] + ); + } + + #[test] + fn test_adjust_child_validity_with_sliced_parent_bitmap() { + let child: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4])); + let parent_validity: arrow_buffer::NullBuffer = + (0..1030).map(|index| index != 1026).collect(); + let parent_validity = parent_validity.slice(1025, 4); + assert_eq!(parent_validity.inner().offset(), 1025); + + let adjusted = adjust_child_validity(&child, Some(&parent_validity)); + let adjusted = adjusted.as_any().downcast_ref::().unwrap(); + assert_eq!( + adjusted.iter().collect::>(), + vec![Some(1), None, Some(3), Some(4)] + ); + } + + #[test] + fn test_convert_to_floating_point_preserves_inner_nulls() { + // A FixedSizeList with a null inner element must convert to a + // FixedSizeList with the null kept in place. Dropping it would + // shorten the values array and shift every later element (and, when the + // remaining count is not a multiple of the list size, panic). + let values = Int8Array::from(vec![Some(1), None, Some(3), Some(4)]); + let fsl = FixedSizeListArray::new( + Arc::new(Field::new("item", DataType::Int8, true)), + 2, + Arc::new(values), + None, + ); + + let converted = fsl.convert_to_floating_point().unwrap(); + + assert_eq!(converted.len(), 2); + let conv_values = converted + .values() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(conv_values.len(), 4); + assert_eq!(conv_values.value(0), 1.0); + assert!(conv_values.is_null(1)); + assert_eq!(conv_values.value(2), 3.0); + assert_eq!(conv_values.value(3), 4.0); + } + + #[test] + fn test_convert_to_floating_point_preserves_inner_nulls_f64_arm() { + // The Float64-producing arms (Int64/UInt8/UInt32) share the same fix as the + // Float32 arms; cover one representative (UInt8 -> Float64) so both branch + // families are exercised. + let values = UInt8Array::from(vec![Some(10u8), None, Some(30), Some(40)]); + let fsl = FixedSizeListArray::new( + Arc::new(Field::new("item", DataType::UInt8, true)), + 2, + Arc::new(values), + None, + ); + + let converted = fsl.convert_to_floating_point().unwrap(); + + assert_eq!(converted.len(), 2); + let conv_values = converted + .values() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(conv_values.len(), 4); + assert_eq!(conv_values.value(0), 10.0); + assert!(conv_values.is_null(1)); + assert_eq!(conv_values.value(2), 30.0); + assert_eq!(conv_values.value(3), 40.0); + } + + #[test] + fn test_merge_recursive() { + let a_array = Int32Array::from(vec![Some(1), Some(2), Some(3)]); + let e_array = Int32Array::from(vec![Some(4), Some(5), Some(6)]); + let c_array = Int32Array::from(vec![Some(7), Some(8), Some(9)]); + let d_array = StringArray::from(vec![Some("a"), Some("b"), Some("c")]); + + let left_schema = Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new( + "b", + DataType::Struct(vec![Field::new("c", DataType::Int32, true)].into()), + true, + ), + ]); + let left_batch = RecordBatch::try_new( + Arc::new(left_schema), + vec![ + Arc::new(a_array.clone()), + Arc::new(StructArray::from(vec![( + Arc::new(Field::new("c", DataType::Int32, true)), + Arc::new(c_array.clone()) as ArrayRef, + )])), + ], + ) + .unwrap(); + + let right_schema = Schema::new(vec![ + Field::new("e", DataType::Int32, true), + Field::new( + "b", + DataType::Struct(vec![Field::new("d", DataType::Utf8, true)].into()), + true, + ), + ]); + let right_batch = RecordBatch::try_new( + Arc::new(right_schema), + vec![ + Arc::new(e_array.clone()), + Arc::new(StructArray::from(vec![( + Arc::new(Field::new("d", DataType::Utf8, true)), + Arc::new(d_array.clone()) as ArrayRef, + )])) as ArrayRef, + ], + ) + .unwrap(); + + let merged_schema = Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new( + "b", + DataType::Struct( + vec![ + Field::new("c", DataType::Int32, true), + Field::new("d", DataType::Utf8, true), + ] + .into(), + ), + true, + ), + Field::new("e", DataType::Int32, true), + ]); + let merged_batch = RecordBatch::try_new( + Arc::new(merged_schema), + vec![ + Arc::new(a_array) as ArrayRef, + Arc::new(StructArray::from(vec![ + ( + Arc::new(Field::new("c", DataType::Int32, true)), + Arc::new(c_array) as ArrayRef, + ), + ( + Arc::new(Field::new("d", DataType::Utf8, true)), + Arc::new(d_array) as ArrayRef, + ), + ])) as ArrayRef, + Arc::new(e_array) as ArrayRef, + ], + ) + .unwrap(); + + let result = left_batch.merge(&right_batch).unwrap(); + assert_eq!(result, merged_batch); + } + + #[test] + fn test_merge_with_schema() { + fn test_batch(names: &[&str], types: &[DataType]) -> (Schema, RecordBatch) { + let fields: Fields = names + .iter() + .zip(types) + .map(|(name, ty)| Field::new(name.to_string(), ty.clone(), false)) + .collect(); + let schema = Schema::new(vec![Field::new( + "struct", + DataType::Struct(fields.clone()), + false, + )]); + let children = types.iter().map(new_empty_array).collect::>(); + let batch = RecordBatch::try_new( + Arc::new(schema.clone()), + vec![Arc::new(StructArray::new(fields, children, None)) as ArrayRef], + ); + (schema, batch.unwrap()) + } + + let (_, left_batch) = test_batch(&["a", "b"], &[DataType::Int32, DataType::Int64]); + let (_, right_batch) = test_batch(&["c", "b"], &[DataType::Int32, DataType::Int64]); + let (output_schema, _) = test_batch( + &["b", "a", "c"], + &[DataType::Int64, DataType::Int32, DataType::Int32], + ); + + // If we use merge_with_schema the schema is respected + let merged = left_batch + .merge_with_schema(&right_batch, &output_schema) + .unwrap(); + assert_eq!(merged.schema().as_ref(), &output_schema); + + // If we use merge we get first-come first-serve based on the left batch + let (naive_schema, _) = test_batch( + &["a", "b", "c"], + &[DataType::Int32, DataType::Int64, DataType::Int32], + ); + let merged = left_batch.merge(&right_batch).unwrap(); + assert_eq!(merged.schema().as_ref(), &naive_schema); + } + + #[test] + fn test_merge_list_struct() { + let x_field = Arc::new(Field::new("x", DataType::Int32, true)); + let y_field = Arc::new(Field::new("y", DataType::Int32, true)); + let x_struct_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![x_field.clone()])), + true, + )); + let y_struct_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![y_field.clone()])), + true, + )); + let both_struct_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![x_field.clone(), y_field.clone()])), + true, + )); + let left_schema = Schema::new(vec![Field::new( + "list_struct", + DataType::List(x_struct_field.clone()), + true, + )]); + let right_schema = Schema::new(vec![Field::new( + "list_struct", + DataType::List(y_struct_field.clone()), + true, + )]); + let both_schema = Schema::new(vec![Field::new( + "list_struct", + DataType::List(both_struct_field.clone()), + true, + )]); + + let x = Arc::new(Int32Array::from(vec![1])); + let y = Arc::new(Int32Array::from(vec![2])); + let x_struct = Arc::new(StructArray::new( + Fields::from(vec![x_field.clone()]), + vec![x.clone()], + None, + )); + let y_struct = Arc::new(StructArray::new( + Fields::from(vec![y_field.clone()]), + vec![y.clone()], + None, + )); + let both_struct = Arc::new(StructArray::new( + Fields::from(vec![x_field.clone(), y_field.clone()]), + vec![x.clone(), y], + None, + )); + let both_null_struct = Arc::new(StructArray::new( + Fields::from(vec![x_field, y_field]), + vec![x, Arc::new(new_null_array(&DataType::Int32, 1))], + None, + )); + let offsets = OffsetBuffer::from_lengths([1]); + let x_s_list = ListArray::new(x_struct_field, offsets.clone(), x_struct, None); + let y_s_list = ListArray::new(y_struct_field, offsets.clone(), y_struct, None); + let both_list = ListArray::new( + both_struct_field.clone(), + offsets.clone(), + both_struct, + None, + ); + let both_null_list = ListArray::new(both_struct_field, offsets, both_null_struct, None); + let x_batch = + RecordBatch::try_new(Arc::new(left_schema), vec![Arc::new(x_s_list)]).unwrap(); + let y_batch = RecordBatch::try_new( + Arc::new(right_schema.clone()), + vec![Arc::new(y_s_list.clone())], + ) + .unwrap(); + let merged = x_batch.merge(&y_batch).unwrap(); + let expected = + RecordBatch::try_new(Arc::new(both_schema.clone()), vec![Arc::new(both_list)]).unwrap(); + assert_eq!(merged, expected); + + let y_null_list = new_null_array(y_s_list.data_type(), 1); + let y_null_batch = + RecordBatch::try_new(Arc::new(right_schema), vec![Arc::new(y_null_list.clone())]) + .unwrap(); + let expected = + RecordBatch::try_new(Arc::new(both_schema), vec![Arc::new(both_null_list)]).unwrap(); + let merged = x_batch.merge(&y_null_batch).unwrap(); + assert_eq!(merged, expected); + } + + #[test] + fn test_merge_all_null_list_adds_nested_child() { + // An all-null placeholder (what a fragment reader merges in for children + // missing from its files) adds `b` to a struct below one or two lists. + let strukt = |cols: Vec<(&str, ArrayRef)>| -> ArrayRef { + let fields = cols + .iter() + .map(|(name, col)| Field::new(*name, col.data_type().clone(), true)) + .collect::>(); + Arc::new(StructArray::new( + fields.into(), + cols.into_iter().map(|(_, col)| col).collect(), + None, + )) + }; + // Two rows: `[values]` and null. + let list = |values: ArrayRef, large: bool| -> ArrayRef { + let field = Arc::new(Field::new("item", values.data_type().clone(), true)); + let lengths = [values.len(), 0]; + let nulls = Some(arrow_buffer::NullBuffer::from(vec![true, false])); + if large { + Arc::new(LargeListArray::new( + field, + OffsetBuffer::from_lengths(lengths), + values, + nulls, + )) + } else { + Arc::new(ListArray::new( + field, + OffsetBuffer::from_lengths(lengths), + values, + nulls, + )) + } + }; + let a = || Arc::new(Int32Array::from(vec![7])) as ArrayRef; + let b = || new_null_array(&DataType::Utf8, 1); + for large in [false, true] { + // list>>, built with or without `t`. + let under_list = |inner: ArrayRef, with_t: bool| { + let mut cols = vec![("in", inner)]; + if with_t { + cols.insert(0, ("t", Arc::new(Int32Array::from(vec![1])) as ArrayRef)); + } + list(strukt(cols), large) + }; + // list>> + let under_two_lists = |inner: ArrayRef, _: bool| { + let inner_list: ArrayRef = if large { + let field = Arc::new(Field::new("item", inner.data_type().clone(), true)); + Arc::new(LargeListArray::new( + field, + OffsetBuffer::from_lengths([1]), + inner, + None, + )) + } else { + let field = Arc::new(Field::new("item", inner.data_type().clone(), true)); + Arc::new(ListArray::new( + field, + OffsetBuffer::from_lengths([1]), + inner, + None, + )) + }; + list(inner_list, large) + }; + let shapes: [&dyn Fn(ArrayRef, bool) -> ArrayRef; 2] = [&under_list, &under_two_lists]; + for shape in shapes { + let data = shape(strukt(vec![("a", a())]), true); + let expected = shape(strukt(vec![("a", a()), ("b", b())]), true); + let placeholder = + new_null_array(shape(strukt(vec![("b", b())]), false).data_type(), 2); + let batch = |col: ArrayRef| { + RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "c", + col.data_type().clone(), + true, + )])), + vec![col], + ) + .unwrap() + }; + let expected = batch(expected); + // Either side may be the placeholder; field order follows the left. + for merged in [ + batch(data.clone()) + .merge(&batch(placeholder.clone())) + .unwrap(), + batch(placeholder.clone()) + .merge(&batch(data.clone())) + .unwrap(), + ] { + let merged = merged.project_by_schema(expected.schema_ref()).unwrap(); + assert_eq!(merged, expected, "large={large}"); + } + } + } + } + + #[test] + fn test_merge_list_struct_identical_schema() { + // Merging two batches whose `List` columns have identical types + // should yield a single column equal to the input (there is nothing to + // merge), not a struct with the field pushed twice. + let x_field = Arc::new(Field::new("x", DataType::Int32, true)); + let item_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![x_field.clone()])), + true, + )); + let schema = Arc::new(Schema::new(vec![Field::new( + "list_struct", + DataType::List(item_field.clone()), + true, + )])); + + let build_list = |values: Vec| { + let len = values.len(); + let item_struct = Arc::new(StructArray::new( + Fields::from(vec![x_field.clone()]), + vec![Arc::new(Int32Array::from(values))], + None, + )); + ListArray::new( + item_field.clone(), + OffsetBuffer::from_lengths([len]), + item_struct, + None, + ) + }; + + // Distinct values so the equality assertion proves the left column is kept, + // not that some column with the same values happens to be present. + let left = + RecordBatch::try_new(schema.clone(), vec![Arc::new(build_list(vec![1, 2]))]).unwrap(); + let right = RecordBatch::try_new(schema, vec![Arc::new(build_list(vec![3, 4]))]).unwrap(); + + let merged = left.merge(&right).unwrap(); + + // Exactly one column, equal to the left input: the field must not be duplicated. + assert_eq!(merged.num_columns(), 1); + assert_eq!(merged, left); + } + + #[test] + fn test_merge_nested_list_struct_identical_schema() { + // A `List` nested inside a struct reaches the identical-type + // short-circuit through the recursive `merge` call. The recursion must + // keep the field exactly once, equal to the left input. + let x_field = Arc::new(Field::new("x", DataType::Int32, true)); + let item_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![x_field.clone()])), + true, + )); + let companies_field = Arc::new(Field::new( + "companies", + DataType::List(item_field.clone()), + true, + )); + let schema = Arc::new(Schema::new(vec![Field::new( + "outer", + DataType::Struct(Fields::from(vec![companies_field.clone()])), + true, + )])); + + let build_outer = |x: i32| { + // One list row: [{x}]. + let item_struct = Arc::new(StructArray::new( + Fields::from(vec![x_field.clone()]), + vec![Arc::new(Int32Array::from(vec![x]))], + None, + )); + let companies = Arc::new(ListArray::new( + item_field.clone(), + OffsetBuffer::from_lengths([1]), + item_struct, + None, + )); + StructArray::new( + Fields::from(vec![companies_field.clone()]), + vec![companies], + None, + ) + }; + + // Distinct values so equality proves the left column is kept. + let left = RecordBatch::try_new(schema.clone(), vec![Arc::new(build_outer(10))]).unwrap(); + let right = RecordBatch::try_new(schema, vec![Arc::new(build_outer(20))]).unwrap(); + + let merged = left.merge(&right).unwrap(); + + // The recursive identical-type merge keeps exactly one `companies` field, + // with no double-push inside the nested struct. + assert_eq!(merged.column(0).as_struct().num_columns(), 1); + assert_eq!(merged, left); + } + + /// A list of `items`, one item per entry. + fn one_item_per_entry(large: bool, items: ArrayRef) -> ArrayRef { + let item_field = Arc::new(Field::new("item", items.data_type().clone(), true)); + let lengths = vec![1; items.len()]; + if large { + Arc::new(LargeListArray::new( + item_field, + OffsetBuffer::::from_lengths(lengths), + items, + None, + )) + } else { + Arc::new(ListArray::new( + item_field, + OffsetBuffer::::from_lengths(lengths), + items, + None, + )) + } + } + + /// A batch with the single column `s`, valid per `parent_validity`. + fn batch_of_parent(parent: StructArray) -> RecordBatch { + RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "s", + parent.data_type().clone(), + true, + )])), + vec![Arc::new(parent)], + ) + .unwrap() + } + + /// `{s: struct>>}`, one row per value, each + /// list holding one item, and `s` valid per `parent_validity`. + fn list_struct_under_parent( + large: bool, + child: &str, + parent_validity: &[bool], + values: &[i32], + ) -> RecordBatch { + let items = Arc::new(StructArray::new( + vec![Field::new(child, DataType::Int32, true)].into(), + vec![Arc::new(Int32Array::from(values.to_vec()))], + None, + )); + let list = one_item_per_entry(large, items); + batch_of_parent(StructArray::new( + vec![Field::new("l", list.data_type().clone(), true)].into(), + vec![list], + Some(parent_validity.to_vec().into()), + )) + } + + /// The child `name` of the single item in row `row` of the merged `s.l`. + fn merged_item_child(merged: &RecordBatch, large: bool, row: usize, name: &str) -> ArrayRef { + let list = merged.column(0).as_struct().column(0); + let item = if large { + list.as_list::().value(row) + } else { + list.as_list::().value(row) + }; + item.as_struct().column_by_name(name).unwrap().clone() + } + + #[test] + fn test_merge_list_struct_identical_schema_hides_a_null_parent_row() { + for large in [false, true] { + let left = list_struct_under_parent(large, "x", &[false, true], &[11, 12]); + let right = list_struct_under_parent(large, "x", &[true, true], &[21, 22]); + let merged = left.merge(&right).unwrap(); + let parent = merged.column(0).as_struct(); + assert!(parent.is_valid(0), "large={large}"); + assert!( + parent.column(0).is_null(0), + "large={large}: the list under the null left parent became visible" + ); + assert!(parent.column(0).is_valid(1), "large={large}"); + } + } + + #[test] + fn test_merge_list_struct_hides_the_items_of_a_null_parent_row() { + for large in [false, true] { + // Null parent on the left: row 0 keeps the right item, not x = 11. + let left = list_struct_under_parent(large, "x", &[false, true], &[11, 12]); + let right = list_struct_under_parent(large, "y", &[true, true], &[21, 22]); + let merged = left.merge(&right).unwrap(); + assert!(merged.column(0).as_struct().column(0).is_valid(0)); + assert!( + merged_item_child(&merged, large, 0, "x").is_null(0), + "large={large}: x under the null left parent became visible" + ); + let y = merged_item_child(&merged, large, 0, "y"); + assert_eq!(y.as_primitive::().value(0), 21, "large={large}"); + + // Null parent on the right: row 0 keeps x = 11, not y = 21. + let left = list_struct_under_parent(large, "x", &[true, true], &[11, 12]); + let right = list_struct_under_parent(large, "y", &[false, true], &[21, 22]); + let merged = left.merge(&right).unwrap(); + let x = merged_item_child(&merged, large, 0, "x"); + assert_eq!(x.as_primitive::().value(0), 11, "large={large}"); + assert!( + merged_item_child(&merged, large, 0, "y").is_null(0), + "large={large}: y under the null right parent became visible" + ); + + // Row 1 is valid on both sides and keeps both items. + let x = merged_item_child(&merged, large, 1, "x"); + let y = merged_item_child(&merged, large, 1, "y"); + assert_eq!(x.as_primitive::().value(0), 12, "large={large}"); + assert_eq!(y.as_primitive::().value(0), 22, "large={large}"); + } + } + + #[test] + fn test_merge_list_struct_follows_a_sliced_parent() { + for large in [false, true] { + // After slicing, row 0 is the null parent row and row 1 is valid. + let left = list_struct_under_parent(large, "x", &[true, false, true], &[10, 11, 12]); + let left = left.slice(1, 2); + + let same = list_struct_under_parent(large, "x", &[true, true, true], &[20, 21, 22]); + let merged = left.merge(&same.slice(1, 2)).unwrap(); + let list = merged.column(0).as_struct().column(0); + assert!(list.is_null(0), "large={large}"); + assert!(list.is_valid(1), "large={large}"); + + let other = list_struct_under_parent(large, "y", &[true, true, true], &[20, 21, 22]); + let merged = left.merge(&other.slice(1, 2)).unwrap(); + assert!( + merged_item_child(&merged, large, 0, "x").is_null(0), + "large={large}" + ); + let x = merged_item_child(&merged, large, 1, "x"); + assert_eq!(x.as_primitive::().value(0), 12, "large={large}"); + } + } + + /// A non-nullable `l` or item child cannot be nulled under a parent row that + /// only the other side has, so the merge fails there rather than show the + /// hidden value. Where both sides agree on the parent, nothing is revealed + /// and the same fields merge. + #[test] + fn test_merge_list_struct_with_non_nullable_fields_under_a_null_parent() { + #[derive(Clone, Copy)] + struct Shape { + child: &'static str, + l_nullable: bool, + item_nullable: bool, + child_nullable: bool, + null_first_entry: bool, + null_first_item: bool, + } + let shape = |child| Shape { + child, + l_nullable: true, + item_nullable: true, + child_nullable: true, + null_first_entry: false, + null_first_item: false, + }; + let batch = |shape: Shape, parent_validity: [bool; 2]| { + let items = Arc::new(StructArray::new( + vec![Field::new( + shape.child, + DataType::Int32, + shape.child_nullable, + )] + .into(), + vec![Arc::new(Int32Array::from(vec![1, 2]))], + shape.null_first_item.then(|| vec![false, true].into()), + )); + let list: ArrayRef = Arc::new(ListArray::new( + Arc::new(Field::new( + "item", + items.data_type().clone(), + shape.item_nullable, + )), + OffsetBuffer::::from_lengths([1, 1]), + items, + shape.null_first_entry.then(|| vec![false, true].into()), + )); + batch_of_parent(StructArray::new( + vec![Field::new("l", list.data_type().clone(), shape.l_nullable)].into(), + vec![list], + Some(parent_validity.to_vec().into()), + )) + }; + let null_first = [false, true]; + let all_valid = [true, true]; + let cases = [ + // Non-nullable `l`, identical item types. + ( + Shape { + l_nullable: false, + ..shape("x") + }, + Shape { + l_nullable: false, + ..shape("x") + }, + Some("Cannot merge non-nullable field 'l'"), + ), + // Non-nullable `l` on the left, a null entry on the right: neither + // side has an entry at the merged row. + ( + Shape { + l_nullable: false, + ..shape("x") + }, + Shape { + null_first_entry: true, + ..shape("y") + }, + Some("non-nullable StructArray field \"l\""), + ), + // A non-nullable child of the item struct. + ( + Shape { + child_nullable: false, + ..shape("x") + }, + shape("y"), + Some("Cannot merge non-nullable field 'x'"), + ), + // A non-nullable item can be hidden where the right item is null. + ( + Shape { + item_nullable: false, + ..shape("x") + }, + Shape { + null_first_item: true, + ..shape("y") + }, + None, + ), + ]; + for (case, (left, right, rejected)) in cases.into_iter().enumerate() { + let merged = batch(left, null_first).merge(&batch(right, all_valid)); + match rejected { + Some(expected) => { + let message = merged.unwrap_err().to_string(); + assert!(message.contains(expected), "case {case}: {message}"); + } + None => assert!(merged.is_ok(), "case {case}: {merged:?}"), + } + let agreed = batch(left, null_first).merge(&batch(right, null_first)); + assert!( + agreed.is_ok(), + "case {case} with agreeing parents: {agreed:?}" + ); + } + } + + /// The fragment reader merges a data batch with an all-null placeholder for + /// a nested child the file lacks. Only the placeholder's top-level field is + /// nullable, so a non-nullable field below it must still merge, in either + /// order, keeping the data and filling the new child with nulls. + #[test] + fn test_merge_with_a_placeholder_under_a_non_nullable_field() { + let inner = + |child: &str| -> Fields { vec![Field::new(child, DataType::Int32, true)].into() }; + for wrap in ["struct", "list", "large_list"] { + let wrapped = |fields: Fields| match wrap { + "struct" => DataType::Struct(fields), + "list" => { + DataType::List(Arc::new(Field::new("item", DataType::Struct(fields), true))) + } + _ => DataType::LargeList(Arc::new(Field::new( + "item", + DataType::Struct(fields), + true, + ))), + }; + let outer = |child: &str| { + DataType::Struct(vec![Field::new("inner", wrapped(inner(child)), false)].into()) + }; + let items: ArrayRef = Arc::new(StructArray::new( + inner("a"), + vec![Arc::new(Int32Array::from(vec![1, 2]))], + None, + )); + let data_inner = match wrap { + "struct" => items, + "list" => one_item_per_entry(false, items), + _ => one_item_per_entry(true, items), + }; + let data = batch_of_parent(StructArray::new( + vec![Field::new("inner", data_inner.data_type().clone(), false)].into(), + vec![data_inner], + None, + )); + let placeholder = batch_of_parent(new_null_array(&outer("b"), 2).as_struct().clone()); + + for (left, right) in [(&data, &placeholder), (&placeholder, &data)] { + let merged = left.merge(right).unwrap(); + let inner = merged + .column(0) + .as_struct() + .column_by_name("inner") + .unwrap(); + let items = match wrap { + "struct" => inner.clone(), + "list" => inner.as_list::().values().clone(), + _ => inner.as_list::().values().clone(), + }; + let items = items.as_struct(); + let a = items.column_by_name("a").unwrap(); + assert_eq!(a.as_primitive::().values(), &[1, 2], "{wrap}"); + assert_eq!(a.null_count(), 0, "{wrap}"); + assert_eq!(items.column_by_name("b").unwrap().null_count(), 2, "{wrap}"); + } + } + } + + /// The null parent row's values stay hidden below a struct nested in the + /// list item, and below a plain struct field. + #[test] + fn test_merge_hides_nested_structs_of_a_null_parent_row() { + let nested = |child: &str, values: Vec| { + let leaf = StructArray::new( + vec![Field::new(child, DataType::Int32, true)].into(), + vec![Arc::new(Int32Array::from(values))], + None, + ); + StructArray::new( + vec![Field::new("payload", leaf.data_type().clone(), true)].into(), + vec![Arc::new(leaf)], + None, + ) + }; + let x_of = |payload: &dyn Array, row: usize| { + let x = payload.as_struct().column_by_name("x").unwrap().clone(); + x.is_null(row) + }; + + for large in [false, true] { + let in_list = |child: &str, parent: [bool; 2]| { + let list = one_item_per_entry(large, Arc::new(nested(child, vec![11, 12]))); + batch_of_parent(StructArray::new( + vec![Field::new("l", list.data_type().clone(), true)].into(), + vec![list], + Some(parent.to_vec().into()), + )) + }; + let merged = in_list("x", [false, true]) + .merge(&in_list("y", [true, true])) + .unwrap(); + let list = merged.column(0).as_struct().column(0); + let item = if large { + list.as_list::().value(0) + } else { + list.as_list::().value(0) + }; + let payload = item.as_struct().column_by_name("payload").unwrap(); + assert!(x_of(payload.as_ref(), 0), "large={large}"); + } + + let in_struct = |child: &str, parent: [bool; 2]| { + let inner = nested(child, vec![11, 12]); + batch_of_parent(StructArray::new( + vec![Field::new("c", inner.data_type().clone(), true)].into(), + vec![Arc::new(inner)], + Some(parent.to_vec().into()), + )) + }; + let merged = in_struct("x", [false, true]) + .merge(&in_struct("y", [true, true])) + .unwrap(); + let c = merged.column(0).as_struct().column(0); + let payload = c.as_struct().column_by_name("payload").unwrap(); + assert!(x_of(payload.as_ref(), 0)); + assert!(!x_of(payload.as_ref(), 1)); + } + + /// A batch whose parent rows are all null merges with an all-null + /// placeholder whose item struct holds more fields. + #[test] + fn test_merge_list_struct_under_null_parents_with_a_placeholder() { + for large in [false, true] { + let a = Field::new("a", DataType::Int32, true); + let inner = StructArray::new( + vec![a.clone()].into(), + vec![Arc::new(Int32Array::from(vec![1, 2]))], + None, + ); + let items = Arc::new(StructArray::new( + vec![Field::new("x", inner.data_type().clone(), true)].into(), + vec![Arc::new(inner)], + None, + )); + let list = one_item_per_entry(large, items); + let left = batch_of_parent(StructArray::new( + vec![Field::new("l", list.data_type().clone(), true)].into(), + vec![list], + Some(vec![false, false].into()), + )); + + let wider_x = + DataType::Struct(vec![a.clone(), Field::new("b", DataType::Int32, true)].into()); + let wider_items = new_null_array( + &DataType::Struct(vec![Field::new("x", wider_x, true)].into()), + 2, + ); + let wider_list = one_item_per_entry(large, wider_items); + let placeholder = new_null_array( + &DataType::Struct( + vec![Field::new("l", wider_list.data_type().clone(), true)].into(), + ), + 2, + ); + let right = batch_of_parent(placeholder.as_struct().clone()); + + let merged = left.merge(&right).unwrap(); + assert_eq!(merged.column(0).null_count(), 2, "large={large}"); + } + } + + /// A side whose list entries are all hidden by null parents merges like a + /// placeholder, so the other side's lists survive even with other offsets. + #[test] + fn test_merge_list_struct_hidden_side_keeps_the_other_offsets() { + for large in [false, true] { + let list_of = |child: &str, lengths: Vec, values: Vec| -> ArrayRef { + let items: ArrayRef = Arc::new(StructArray::new( + vec![Field::new(child, DataType::Int32, true)].into(), + vec![Arc::new(Int32Array::from(values))], + None, + )); + let field = Arc::new(Field::new("item", items.data_type().clone(), true)); + if large { + Arc::new(LargeListArray::new( + field, + OffsetBuffer::::from_lengths(lengths), + items, + None, + )) + } else { + Arc::new(ListArray::new( + field, + OffsetBuffer::::from_lengths(lengths), + items, + None, + )) + } + }; + let parent = |list: ArrayRef, validity: Vec| { + batch_of_parent(StructArray::new( + vec![Field::new("l", list.data_type().clone(), true)].into(), + vec![list], + Some(validity.into()), + )) + }; + let left = parent(list_of("x", vec![1, 1], vec![1, 2]), vec![false, false]); + let right = parent(list_of("y", vec![2, 0], vec![7, 8]), vec![true, true]); + + let merged = left.merge(&right).unwrap(); + let list = merged.column(0).as_struct().column(0); + let (first, second) = if large { + let list = list.as_list::(); + (list.value(0), list.value(1)) + } else { + let list = list.as_list::(); + (list.value(0), list.value(1)) + }; + let first = first.as_struct(); + assert_eq!( + first + .column_by_name("y") + .unwrap() + .as_primitive::() + .values(), + &[7, 8], + "large={large}" + ); + assert_eq!( + first.column_by_name("x").unwrap().null_count(), + 2, + "large={large}" + ); + assert_eq!(second.len(), 0, "large={large}"); + } + } + + #[test] + fn test_byte_width_opt() { + assert_eq!(DataType::Int32.byte_width_opt(), Some(4)); + assert_eq!(DataType::Int64.byte_width_opt(), Some(8)); + assert_eq!(DataType::Float32.byte_width_opt(), Some(4)); + assert_eq!(DataType::Float64.byte_width_opt(), Some(8)); + assert_eq!(DataType::Utf8.byte_width_opt(), None); + assert_eq!(DataType::Binary.byte_width_opt(), None); + assert_eq!( + DataType::List(Arc::new(Field::new("item", DataType::Int32, true))).byte_width_opt(), + None + ); + assert_eq!( + DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int32, true)), 3) + .byte_width_opt(), + Some(12) + ); + assert_eq!( + DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int32, true)), 4) + .byte_width_opt(), + Some(16) + ); + assert_eq!( + DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Utf8, true)), 5) + .byte_width_opt(), + None + ); + } + + #[test] + fn test_take_record_batch() { + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Utf8, true), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from_iter_values(0..20)), + Arc::new(StringArray::from_iter_values( + (0..20).map(|i| format!("str-{}", i)), + )), + ], + ) + .unwrap(); + let taken = batch.take(&(vec![1_u32, 5_u32, 10_u32].into())).unwrap(); + assert_eq!( + taken, + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from(vec![1, 5, 10])), + Arc::new(StringArray::from(vec!["str-1", "str-5", "str-10"])), + ], + ) + .unwrap() + ) + } + + #[test] + fn test_schema_project_by_schema() { + let metadata = [("key".to_string(), "value".to_string())]; + let schema = Arc::new( + Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Utf8, true), + ]) + .with_metadata(metadata.clone().into()), + ); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from_iter_values(0..20)), + Arc::new(StringArray::from_iter_values( + (0..20).map(|i| format!("str-{}", i)), + )), + ], + ) + .unwrap(); + + // Empty schema + let empty_schema = Schema::empty(); + let empty_projected = batch.project_by_schema(&empty_schema).unwrap(); + let expected_schema = empty_schema.with_metadata(metadata.clone().into()); + assert_eq!( + empty_projected, + RecordBatch::from(StructArray::new_empty_fields(batch.num_rows(), None)) + .with_schema(Arc::new(expected_schema)) + .unwrap() + ); + + // Re-ordered schema + let reordered_schema = Schema::new(vec![ + Field::new("b", DataType::Utf8, true), + Field::new("a", DataType::Int32, true), + ]); + let reordered_projected = batch.project_by_schema(&reordered_schema).unwrap(); + let expected_schema = Arc::new(reordered_schema.with_metadata(metadata.clone().into())); + assert_eq!( + reordered_projected, + RecordBatch::try_new( + expected_schema, + vec![ + Arc::new(StringArray::from_iter_values( + (0..20).map(|i| format!("str-{}", i)), + )), + Arc::new(Int32Array::from_iter_values(0..20)), + ], + ) + .unwrap() + ); + + // Sub schema + let sub_schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]); + let sub_projected = batch.project_by_schema(&sub_schema).unwrap(); + let expected_schema = Arc::new(sub_schema.with_metadata(metadata.into())); + assert_eq!( + sub_projected, + RecordBatch::try_new( + expected_schema, + vec![Arc::new(Int32Array::from_iter_values(0..20))], + ) + .unwrap() + ); + } + + #[test] + fn test_project_rebuilds_sliced_map() { + // A sliced MapArray keeps its full entries array behind sliced + // offsets and validity; the Map projection arm must rebuild it + // without renormalizing either. + let entry_fields = Fields::from(vec![ + Field::new("key", DataType::Utf8, false), + Field::new("value", DataType::Int32, true), + ]); + let entries_field = Arc::new(Field::new( + "entries", + DataType::Struct(entry_fields.clone()), + false, + )); + let entries = StructArray::new( + entry_fields, + vec![ + Arc::new(StringArray::from(vec!["k0", "k1", "k2"])) as ArrayRef, + Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef, + ], + None, + ); + let map = MapArray::new( + entries_field.clone(), + OffsetBuffer::new(vec![0, 1, 1, 3].into()), + entries, + Some(arrow_buffer::NullBuffer::from(vec![true, false, true])), + false, + ); + let schema = Arc::new(Schema::new(vec![Field::new( + "m", + DataType::Map(entries_field, false), + true, + )])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(map) as ArrayRef]).unwrap(); + + // Rows 1..3: a null slot and a two-entry slot, offsets not zero-based. + let projected = batch + .slice(1, 2) + .project_by_schema(schema.as_ref()) + .unwrap(); + let map = projected.column(0).as_map(); + assert!(map.is_null(0)); + assert!(map.is_valid(1)); + assert_eq!(map.value_length(1), 2); + assert_eq!( + map.value(1) + .column(1) + .as_primitive::() + .values(), + &[2, 3] + ); + } + + #[test] + fn test_project_preserves_struct_validity() { + // Test that projecting a struct array preserves its validity (fix for issue #4385) + let fields = Fields::from(vec![ + Field::new("id", DataType::Int32, false), + Field::new("value", DataType::Float32, true), + ]); + + // Create a struct array with validity + let id_array = Int32Array::from(vec![1, 2, 3]); + let value_array = Float32Array::from(vec![Some(1.0), Some(2.0), Some(3.0)]); + let struct_array = StructArray::new( + fields.clone(), + vec![ + Arc::new(id_array) as ArrayRef, + Arc::new(value_array) as ArrayRef, + ], + Some(vec![true, false, true].into()), // Second struct is null + ); + + // Project the struct array + let projected = project(&struct_array, &fields).unwrap(); + + // Verify the validity is preserved + assert_eq!(projected.null_count(), 1); + assert!(!projected.is_null(0)); + assert!(projected.is_null(1)); + assert!(!projected.is_null(2)); + } + + #[test] + fn test_merge_struct_with_different_validity() { + // Test case from Weston's review comment + // File 1 has height field with some nulls + let height_array = Int32Array::from(vec![Some(500), None, Some(600), None]); + let left_fields = Fields::from(vec![Field::new("height", DataType::Int32, true)]); + let left_struct = StructArray::new( + left_fields, + vec![Arc::new(height_array) as ArrayRef], + Some(vec![true, false, true, false].into()), // Rows 2 and 4 are null structs + ); + + // File 2 has width field with some nulls + let width_array = Int32Array::from(vec![Some(300), Some(200), None, None]); + let right_fields = Fields::from(vec![Field::new("width", DataType::Int32, true)]); + let right_struct = StructArray::new( + right_fields, + vec![Arc::new(width_array) as ArrayRef], + Some(vec![true, true, false, false].into()), // Rows 3 and 4 are null structs + ); + + // Merge the two structs + let merged = merge(&left_struct, &right_struct).unwrap(); + + // Expected: + // Row 1: both non-null -> {width: 300, height: 500} + // Row 2: left null, right non-null -> {width: 200, height: null} + // Row 3: left non-null, right null -> {width: null, height: 600} + // Row 4: both null -> null struct + + assert_eq!(merged.null_count(), 1); // Only row 4 is null + assert!(!merged.is_null(0)); + assert!(!merged.is_null(1)); + assert!(!merged.is_null(2)); + assert!(merged.is_null(3)); + + // Check field values + let height_col = merged.column_by_name("height").unwrap(); + let height_values = height_col.as_any().downcast_ref::().unwrap(); + assert_eq!(height_values.value(0), 500); + assert!(height_values.is_null(1)); // height is null when left struct was null + assert_eq!(height_values.value(2), 600); + + let width_col = merged.column_by_name("width").unwrap(); + let width_values = width_col.as_any().downcast_ref::().unwrap(); + assert_eq!(width_values.value(0), 300); + assert_eq!(width_values.value(1), 200); + assert!(width_values.is_null(2)); // width is null when right struct was null + + // An all-null validity buffer is data, not a placeholder meaning "this side has no + // validity": merging two of them keeps the rows null. + let all_null_left = StructArray::new( + Fields::from(vec![Field::new("height", DataType::Int32, true)]), + vec![Arc::new(Int32Array::from(vec![None, None])) as ArrayRef], + Some(vec![false, false].into()), + ); + let all_null_right = StructArray::new( + Fields::from(vec![Field::new("width", DataType::Int32, true)]), + vec![Arc::new(Int32Array::from(vec![None, None])) as ArrayRef], + Some(vec![false, false].into()), + ); + + let merged = merge(&all_null_left, &all_null_right).unwrap(); + assert_eq!(merged.null_count(), 2); + + // An all-null side is the identity of the merge, so the other side decides each row. + let partial_left = StructArray::new( + Fields::from(vec![Field::new("height", DataType::Int32, true)]), + vec![Arc::new(Int32Array::from(vec![Some(1), None])) as ArrayRef], + Some(vec![true, false].into()), + ); + let merged = merge(&partial_left, &all_null_right).unwrap(); + assert!(!merged.is_null(0)); + assert!(merged.is_null(1)); + + // A missing validity buffer means all rows are valid, which absorbs an all-null side. + let all_valid_left = StructArray::new( + Fields::from(vec![Field::new("height", DataType::Int32, true)]), + vec![Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef], + None, + ); + let merged = merge(&all_valid_left, &all_null_right).unwrap(); + assert_eq!(merged.null_count(), 0); + + // An explicit all-valid buffer has the same semantics as a missing buffer. + let all_valid: arrow_buffer::NullBuffer = vec![true, true].into(); + let partial: arrow_buffer::NullBuffer = vec![true, false].into(); + assert!(merge_struct_validity(Some(&all_valid), Some(&partial)).is_none()); + assert!(merge_struct_validity(Some(&partial), Some(&all_valid)).is_none()); + } + + #[test] + fn test_merge_null_typed_column_with_parent_validity() { + // Reproduces ENT-990: panic in adjust_child_validity when a Null-typed column + // exists on one side and the parent struct has null rows. + // Arrow's Null type has no null bitmap, so passing one to ArrayData::try_new panics. + let left_struct = StructArray::new( + Fields::from(vec![Field::new("a", DataType::Int32, true)]), + vec![Arc::new(Int32Array::from(vec![Some(1), None])) as ArrayRef], + Some(vec![true, false].into()), + ); + let right_struct = StructArray::new( + Fields::from(vec![Field::new("b", DataType::Null, true)]), + vec![Arc::new(NullArray::new(2)) as ArrayRef], + Some(vec![true, false].into()), + ); + + // Previously panicked: "Arrays of type Null cannot contain a null bitmask" + let merged = merge(&left_struct, &right_struct).unwrap(); + assert_eq!(merged.len(), 2); + let b_col = merged.column_by_name("b").unwrap(); + // DataType::Null implies all-null by definition; no null bitmap is stored. + assert_eq!(b_col.data_type(), &DataType::Null); + assert_eq!(b_col.len(), 2); + } + + #[test] + fn test_merge_with_schema_with_nullable_struct_list_schema_mismatch() { + // left_list setup + let left_company_id = Arc::new(Int32Array::from(vec![None, None])); + let left_count = Arc::new(Int32Array::from(vec![None, None])); + let left_struct = Arc::new(StructArray::new( + Fields::from(vec![ + Field::new("company_id", DataType::Int32, true), + Field::new("count", DataType::Int32, true), + ]), + vec![left_company_id, left_count], + None, + )); + let left_list = Arc::new(ListArray::new( + Arc::new(Field::new( + "item", + DataType::Struct(left_struct.fields().clone()), + true, + )), + OffsetBuffer::from_lengths([2]), + left_struct, + None, + )); + + // Right List Setup + let right_company_name = Arc::new(StringArray::from(vec!["Google", "Microsoft"])); + let right_struct = Arc::new(StructArray::new( + Fields::from(vec![Field::new("company_name", DataType::Utf8, true)]), + vec![right_company_name], + None, + )); + let right_list = Arc::new(ListArray::new( + Arc::new(Field::new( + "item", + DataType::Struct(right_struct.fields().clone()), + true, + )), + OffsetBuffer::from_lengths([2]), + right_struct, + None, + )); + + let target_fields = Fields::from(vec![Field::new( + "companies", + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("company_id", DataType::Int32, true), + Field::new("company_name", DataType::Utf8, true), + Field::new("count", DataType::Int32, true), + ])), + true, + ))), + true, + )]); + + let left_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "companies", + left_list.data_type().clone(), + true, + )])), + vec![left_list as ArrayRef], + ) + .unwrap(); + + let right_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "companies", + right_list.data_type().clone(), + true, + )])), + vec![right_list as ArrayRef], + ) + .unwrap(); + + let merged = left_batch + .merge_with_schema(&right_batch, &Schema::new(target_fields.to_vec())) + .unwrap(); + + // Verify the merged structure + let merged_list = merged + .column_by_name("companies") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let merged_struct = merged_list.values().as_struct(); + + // Should have all 3 fields + assert_eq!(merged_struct.num_columns(), 3); + assert!(merged_struct.column_by_name("company_id").is_some()); + assert!(merged_struct.column_by_name("company_name").is_some()); + assert!(merged_struct.column_by_name("count").is_some()); + + // Verify values + let company_id = merged_struct + .column_by_name("company_id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert!(company_id.is_null(0)); + assert!(company_id.is_null(1)); + + let company_name = merged_struct + .column_by_name("company_name") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(company_name.value(0), "Google"); + assert_eq!(company_name.value(1), "Microsoft"); + + let count = merged_struct + .column_by_name("count") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert!(count.is_null(0)); + assert!(count.is_null(1)); + } + + #[test] + fn test_merge_struct_lists() { + test_merge_struct_lists_generic::(); + } + + #[test] + fn test_merge_struct_large_lists() { + test_merge_struct_lists_generic::(); + } + + fn test_merge_struct_lists_generic() { + // left_list setup + let left_company_id = Arc::new(Int32Array::from(vec![ + Some(1), + Some(2), + Some(3), + Some(4), + Some(5), + Some(6), + Some(7), + Some(8), + Some(9), + Some(10), + Some(11), + Some(12), + Some(13), + Some(14), + Some(15), + Some(16), + Some(17), + Some(18), + Some(19), + Some(20), + ])); + let left_count = Arc::new(Int32Array::from(vec![ + Some(10), + Some(20), + Some(30), + Some(40), + Some(50), + Some(60), + Some(70), + Some(80), + Some(90), + Some(100), + Some(110), + Some(120), + Some(130), + Some(140), + Some(150), + Some(160), + Some(170), + Some(180), + Some(190), + Some(200), + ])); + let left_struct = Arc::new(StructArray::new( + Fields::from(vec![ + Field::new("company_id", DataType::Int32, true), + Field::new("count", DataType::Int32, true), + ]), + vec![left_company_id, left_count], + None, + )); + + let left_list = Arc::new(GenericListArray::::new( + Arc::new(Field::new( + "item", + DataType::Struct(left_struct.fields().clone()), + true, + )), + OffsetBuffer::from_lengths([3, 1]), + left_struct.clone(), + None, + )); + + let left_list_struct = Arc::new(StructArray::new( + Fields::from(vec![Field::new( + "companies", + if O::IS_LARGE { + DataType::LargeList(Arc::new(Field::new( + "item", + DataType::Struct(left_struct.fields().clone()), + true, + ))) + } else { + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(left_struct.fields().clone()), + true, + ))) + }, + true, + )]), + vec![left_list as ArrayRef], + None, + )); + + // right_list setup + let right_company_name = Arc::new(StringArray::from(vec![ + "Google", + "Microsoft", + "Apple", + "Facebook", + ])); + let right_struct = Arc::new(StructArray::new( + Fields::from(vec![Field::new("company_name", DataType::Utf8, true)]), + vec![right_company_name], + None, + )); + let right_list = Arc::new(GenericListArray::::new( + Arc::new(Field::new( + "item", + DataType::Struct(right_struct.fields().clone()), + true, + )), + OffsetBuffer::from_lengths([3, 1]), + right_struct.clone(), + None, + )); + + let right_list_struct = Arc::new(StructArray::new( + Fields::from(vec![Field::new( + "companies", + if O::IS_LARGE { + DataType::LargeList(Arc::new(Field::new( + "item", + DataType::Struct(right_struct.fields().clone()), + true, + ))) + } else { + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(right_struct.fields().clone()), + true, + ))) + }, + true, + )]), + vec![right_list as ArrayRef], + None, + )); + + // prepare schema + let target_fields = Fields::from(vec![Field::new( + "companies", + if O::IS_LARGE { + DataType::LargeList(Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("company_id", DataType::Int32, true), + Field::new("company_name", DataType::Utf8, true), + Field::new("count", DataType::Int32, true), + ])), + true, + ))) + } else { + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("company_id", DataType::Int32, true), + Field::new("company_name", DataType::Utf8, true), + Field::new("count", DataType::Int32, true), + ])), + true, + ))) + }, + true, + )]); + + // merge left_list and right_list + let merged_array = merge_with_schema(&left_list_struct, &right_list_struct, &target_fields); + assert_eq!(merged_array.len(), 2); + } + + #[test] + fn test_merge_with_schema_sliced_list_struct() { + test_merge_with_schema_sliced_list_struct_generic::(); + } + + #[test] + fn test_merge_with_schema_sliced_large_list_struct() { + test_merge_with_schema_sliced_list_struct_generic::(); + } + + // Regression for #6580: merge_with_schema panicked when the left list was a + // sliced view whose offsets did not start at zero (common after a filtered + // scan). Cloning those offsets alongside `trimmed_values` produced offsets + // larger than the trimmed child, panicking in `(Large)ListArray::new`. + fn test_merge_with_schema_sliced_list_struct_generic() { + let make_list_dtype = |item_field: Arc| { + if O::IS_LARGE { + DataType::LargeList(item_field) + } else { + DataType::List(item_field) + } + }; + + // Build a List with two rows of 5 items each, then slice away + // the first row so the remaining list's offsets start at 5, not 0. + let struct_fields_a = Fields::from(vec![Field::new("a", DataType::Int32, true)]); + let left_values = Arc::new(StructArray::new( + struct_fields_a.clone(), + vec![Arc::new(Int32Array::from_iter_values(0..10)) as ArrayRef], + None, + )); + let full_list = GenericListArray::::new( + Arc::new(Field::new("item", DataType::Struct(struct_fields_a), true)), + OffsetBuffer::::from_lengths([5, 5]), + left_values, + None, + ); + let sliced_left = full_list.slice(1, 1); + assert_eq!(sliced_left.offsets()[0].as_usize(), 5); + assert_eq!(sliced_left.offsets()[1].as_usize(), 10); + + let struct_fields_b = Fields::from(vec![Field::new("b", DataType::Int32, true)]); + let right_values = Arc::new(StructArray::new( + struct_fields_b.clone(), + vec![Arc::new(Int32Array::from_iter_values(100..105)) as ArrayRef], + None, + )); + let right_list = GenericListArray::::new( + Arc::new(Field::new("item", DataType::Struct(struct_fields_b), true)), + OffsetBuffer::::from_lengths([5]), + right_values, + None, + ); + + let target_item_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Int32, true), + ])), + true, + )); + let target_fields = Fields::from(vec![Field::new( + "items", + make_list_dtype(target_item_field), + true, + )]); + + let left_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "items", + sliced_left.data_type().clone(), + true, + )])), + vec![Arc::new(sliced_left) as ArrayRef], + ) + .unwrap(); + let right_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "items", + right_list.data_type().clone(), + true, + )])), + vec![Arc::new(right_list) as ArrayRef], + ) + .unwrap(); + + let merged = left_batch + .merge_with_schema(&right_batch, &Schema::new(target_fields.to_vec())) + .unwrap(); + + let merged_list = merged + .column_by_name("items") + .unwrap() + .as_any() + .downcast_ref::>() + .unwrap(); + assert_eq!(merged_list.len(), 1); + assert_eq!(merged_list.value_length(0).as_usize(), 5); + let merged_struct = merged_list.values().as_struct(); + assert_eq!(merged_struct.num_columns(), 2); + let a = merged_struct + .column_by_name("a") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + // After shifting offsets to zero, values 5..10 should be first. + let a_vals: Vec = a.iter().map(|v| v.unwrap()).collect(); + assert_eq!(a_vals, vec![5, 6, 7, 8, 9]); + } + + #[test] + fn test_project_by_schema_list_struct_reorder() { + // Test that project_by_schema correctly reorders fields inside List + // This is a regression test for issue #5702 + + // Source schema with inner struct fields in order: c, b, a + let source_inner_struct = DataType::Struct(Fields::from(vec![ + Field::new("c", DataType::Utf8, true), + Field::new("b", DataType::Utf8, true), + Field::new("a", DataType::Utf8, true), + ])); + let source_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "data", + DataType::List(Arc::new(Field::new( + "item", + source_inner_struct.clone(), + true, + ))), + true, + ), + ])); + + // Create source data with c, b, a order + let c_array = StringArray::from(vec!["c1", "c2"]); + let b_array = StringArray::from(vec!["b1", "b2"]); + let a_array = StringArray::from(vec!["a1", "a2"]); + let inner_struct = StructArray::from(vec![ + ( + Arc::new(Field::new("c", DataType::Utf8, true)), + Arc::new(c_array) as ArrayRef, + ), + ( + Arc::new(Field::new("b", DataType::Utf8, true)), + Arc::new(b_array) as ArrayRef, + ), + ( + Arc::new(Field::new("a", DataType::Utf8, true)), + Arc::new(a_array) as ArrayRef, + ), + ]); + + let list_array = ListArray::new( + Arc::new(Field::new("item", source_inner_struct, true)), + OffsetBuffer::from_lengths([1, 1]), + Arc::new(inner_struct), + None, + ); + + let batch = RecordBatch::try_new( + source_schema, + vec![Arc::new(Int32Array::from(vec![1, 2])), Arc::new(list_array)], + ) + .unwrap(); + + // Target schema with inner struct fields in order: a, b, c + let target_inner_struct = DataType::Struct(Fields::from(vec![ + Field::new("a", DataType::Utf8, true), + Field::new("b", DataType::Utf8, true), + Field::new("c", DataType::Utf8, true), + ])); + let target_schema = Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "data", + DataType::List(Arc::new(Field::new("item", target_inner_struct, true))), + true, + ), + ]); + + // Project should reorder the inner struct fields + let projected = batch.project_by_schema(&target_schema).unwrap(); + + // Verify the schema is correct + assert_eq!(projected.schema().as_ref(), &target_schema); + + // Verify the data is correct by checking inner struct field order + let projected_list = projected.column(1).as_list::(); + let projected_struct = projected_list.values().as_struct(); + + // Fields should now be in order: a, b, c + assert_eq!( + projected_struct.column_by_name("a").unwrap().as_ref(), + &StringArray::from(vec!["a1", "a2"]) as &dyn Array + ); + assert_eq!( + projected_struct.column_by_name("b").unwrap().as_ref(), + &StringArray::from(vec!["b1", "b2"]) as &dyn Array + ); + assert_eq!( + projected_struct.column_by_name("c").unwrap().as_ref(), + &StringArray::from(vec!["c1", "c2"]) as &dyn Array + ); + + // Also verify positional access matches expected order (a=0, b=1, c=2) + assert_eq!( + projected_struct.column(0).as_ref(), + &StringArray::from(vec!["a1", "a2"]) as &dyn Array + ); + assert_eq!( + projected_struct.column(1).as_ref(), + &StringArray::from(vec!["b1", "b2"]) as &dyn Array + ); + assert_eq!( + projected_struct.column(2).as_ref(), + &StringArray::from(vec!["c1", "c2"]) as &dyn Array + ); + } + + #[test] + fn test_project_by_schema_nested_list_struct() { + // Test deeply nested List>> projection + let inner_struct = DataType::Struct(Fields::from(vec![ + Field::new("y", DataType::Int32, true), + Field::new("x", DataType::Int32, true), + ])); + let source_schema = Arc::new(Schema::new(vec![Field::new( + "outer", + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("b", DataType::Utf8, true), + Field::new( + "inner_list", + DataType::List(Arc::new(Field::new("item", inner_struct.clone(), true))), + true, + ), + Field::new("a", DataType::Utf8, true), + ])), + true, + ))), + true, + )])); + + // Create deeply nested data + let y_array = Int32Array::from(vec![1, 2]); + let x_array = Int32Array::from(vec![3, 4]); + let innermost_struct = StructArray::from(vec![ + ( + Arc::new(Field::new("y", DataType::Int32, true)), + Arc::new(y_array) as ArrayRef, + ), + ( + Arc::new(Field::new("x", DataType::Int32, true)), + Arc::new(x_array) as ArrayRef, + ), + ]); + let inner_list = ListArray::new( + Arc::new(Field::new("item", inner_struct.clone(), true)), + OffsetBuffer::from_lengths([2]), + Arc::new(innermost_struct), + None, + ); + + let b_array = StringArray::from(vec!["b1"]); + let a_array = StringArray::from(vec!["a1"]); + let middle_struct = StructArray::from(vec![ + ( + Arc::new(Field::new("b", DataType::Utf8, true)), + Arc::new(b_array) as ArrayRef, + ), + ( + Arc::new(Field::new( + "inner_list", + DataType::List(Arc::new(Field::new("item", inner_struct, true))), + true, + )), + Arc::new(inner_list) as ArrayRef, + ), + ( + Arc::new(Field::new("a", DataType::Utf8, true)), + Arc::new(a_array) as ArrayRef, + ), + ]); + + let outer_list = ListArray::new( + Arc::new(Field::new("item", middle_struct.data_type().clone(), true)), + OffsetBuffer::from_lengths([1]), + Arc::new(middle_struct), + None, + ); + + let batch = + RecordBatch::try_new(source_schema, vec![Arc::new(outer_list) as ArrayRef]).unwrap(); + + // Target schema with reordered fields at all levels + let target_inner_struct = DataType::Struct(Fields::from(vec![ + Field::new("x", DataType::Int32, true), // x before y now + Field::new("y", DataType::Int32, true), + ])); + let target_schema = Schema::new(vec![Field::new( + "outer", + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("a", DataType::Utf8, true), // a before b now + Field::new( + "inner_list", + DataType::List(Arc::new(Field::new("item", target_inner_struct, true))), + true, + ), + Field::new("b", DataType::Utf8, true), + ])), + true, + ))), + true, + )]); + + let projected = batch.project_by_schema(&target_schema).unwrap(); + + // Verify schema + assert_eq!(projected.schema().as_ref(), &target_schema); + + // Verify deeply nested data is reordered correctly + let outer_list = projected.column(0).as_list::(); + let middle_struct = outer_list.values().as_struct(); + + // Middle struct should have a first, then inner_list, then b + assert_eq!( + middle_struct.column(0).as_ref(), + &StringArray::from(vec!["a1"]) as &dyn Array + ); + assert_eq!( + middle_struct.column(2).as_ref(), + &StringArray::from(vec!["b1"]) as &dyn Array + ); + + // Inner list's struct should have x first, then y + let inner_list = middle_struct.column(1).as_list::(); + let innermost_struct = inner_list.values().as_struct(); + assert_eq!( + innermost_struct.column(0).as_ref(), + &Int32Array::from(vec![3, 4]) as &dyn Array + ); + assert_eq!( + innermost_struct.column(1).as_ref(), + &Int32Array::from(vec![1, 2]) as &dyn Array + ); + } + + #[test] + fn test_iter_binary_array_accepts_binary_variants() { + let binary = BinaryArray::from(vec![b"a".as_slice(), b"bc"]); + assert_eq!( + iter_binary_array(&binary).unwrap().collect::>(), + vec![Some(b"a".as_slice()), Some(b"bc".as_slice())] + ); + + let large_binary = LargeBinaryArray::from(vec![b"x".as_slice(), b"yz"]); + assert_eq!( + iter_binary_array(&large_binary) + .unwrap() + .collect::>(), + vec![Some(b"x".as_slice()), Some(b"yz".as_slice())] + ); + + let binary_view = BinaryViewArray::from(vec![b"1".as_slice(), b"23"]); + assert_eq!( + iter_binary_array(&binary_view).unwrap().collect::>(), + vec![Some(b"1".as_slice()), Some(b"23".as_slice())] + ); + + let fixed_size = + FixedSizeBinaryArray::try_from_iter([b"abcd", b"efgh"].into_iter()).unwrap(); + assert_eq!( + iter_binary_array(&fixed_size).unwrap().collect::>(), + vec![Some(b"abcd".as_slice()), Some(b"efgh".as_slice())] + ); + } + + #[test] + fn test_iter_binary_array_rejects_non_binary() { + let int_array = Int32Array::from(vec![1, 2, 3]); + let Err(error) = iter_binary_array(&int_array) else { + panic!("expected an error for non-binary array"); + }; + assert!(error.to_string().contains("Expecting a binary type")); + } +} diff --git a/python/vendor/lance-arrow/src/list.rs b/python/vendor/lance-arrow/src/list.rs new file mode 100644 index 000000000..750b54c93 --- /dev/null +++ b/python/vendor/lance-arrow/src/list.rs @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::sync::Arc; + +use arrow_array::{Array, BooleanArray, GenericListArray, OffsetSizeTrait}; +use arrow_buffer::{BooleanBufferBuilder, OffsetBuffer, ScalarBuffer}; +use arrow_schema::Field; + +pub trait ListArrayExt { + /// Filters out masked null items from the list array + /// + /// It is legal for a list array to have a null entry with a non-zero length. The + /// values inside the entry are "garbage" and should be ignored. This function + /// filters the values array to remove the garbage values. + /// + /// The output list will always have zero-length nulls. + fn filter_garbage_nulls(&self) -> Self; + /// Returns a copy of the list's values array that has been sliced to size + /// + /// It is legal for a list array's offsets to not start with zero. It's also legal + /// for a list array's offsets to not extend to the entire values array. This function + /// behaves similarly to `values()` except it slices the array so that it starts at + /// the first list offset and ends at the last list offset. + fn trimmed_values(&self) -> Arc; + /// The offset type of the underlying list array. + type Offset: OffsetSizeTrait; + /// Returns offsets shifted so the first offset is zero, matching + /// [`Self::trimmed_values`]. + /// + /// Sliced list arrays (e.g. a filtered batch) keep offsets that reference the + /// original values buffer, so combining them with trimmed values produces + /// offsets that exceed the values length. Use this together with + /// `trimmed_values` when constructing a new list array. + fn trimmed_offsets(&self) -> OffsetBuffer; +} + +impl ListArrayExt for GenericListArray { + fn filter_garbage_nulls(&self) -> Self { + if self.is_empty() { + return self.clone(); + } + let Some(validity) = self.nulls().cloned() else { + return self.clone(); + }; + + let mut should_keep = BooleanBufferBuilder::new(self.values().len()); + + // Handle case where offsets do not start at 0 + let preamble_len = self.offsets().first().unwrap().to_usize().unwrap(); + should_keep.append_n(preamble_len, false); + + let mut new_offsets: Vec = Vec::with_capacity(self.len() + 1); + new_offsets.push(OffsetSize::zero()); + let mut cur_len = OffsetSize::zero(); + for (offset, is_valid) in self.offsets().windows(2).zip(validity.iter()) { + let len = offset[1] - offset[0]; + if is_valid { + cur_len += len; + should_keep.append_n(len.to_usize().unwrap(), true); + new_offsets.push(cur_len); + } else { + should_keep.append_n(len.to_usize().unwrap(), false); + new_offsets.push(cur_len); + } + } + + // Offsets may not reference entire values buffer + let trailer = self.values().len() - should_keep.len(); + should_keep.append_n(trailer, false); + + let should_keep = should_keep.finish(); + let should_keep = BooleanArray::new(should_keep, None); + let new_values = arrow_select::filter::filter(self.values(), &should_keep).unwrap(); + let new_offsets = ScalarBuffer::from(new_offsets); + let new_offsets = OffsetBuffer::new(new_offsets); + + Self::new( + Arc::new(Field::new( + "item", + self.value_type(), + self.values().is_nullable(), + )), + new_offsets, + new_values, + Some(validity), + ) + } + + fn trimmed_values(&self) -> Arc { + let first_value = self + .offsets() + .first() + .map(|v| v.to_usize().unwrap()) + .unwrap_or(0); + let last_value = self + .offsets() + .last() + .map(|v| v.to_usize().unwrap()) + .unwrap_or(0); + self.values().slice(first_value, last_value - first_value) + } + + type Offset = OffsetSize; + + fn trimmed_offsets(&self) -> OffsetBuffer { + let offsets = self.offsets(); + let Some(&first) = offsets.first() else { + return offsets.clone(); + }; + if first == OffsetSize::zero() { + return offsets.clone(); + } + let shifted: Vec = offsets.iter().map(|&o| o - first).collect(); + OffsetBuffer::new(ScalarBuffer::from(shifted)) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::{ListArray, UInt64Array}; + use arrow_buffer::{BooleanBuffer, NullBuffer, OffsetBuffer, ScalarBuffer}; + use arrow_schema::{DataType, Field}; + + use super::ListArrayExt; + + #[test] + fn test_filter_garbage_nulls() { + let items = UInt64Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + let offsets = ScalarBuffer::::from(vec![2, 5, 8, 9]); + let offsets = OffsetBuffer::new(offsets); + let list_validity = NullBuffer::new(BooleanBuffer::from(vec![true, false, true])); + let list_arr = ListArray::new( + Arc::new(Field::new("item", DataType::UInt64, true)), + offsets, + Arc::new(items), + Some(list_validity.clone()), + ); + + let filtered = list_arr.filter_garbage_nulls(); + + let expected_items = UInt64Array::from(vec![2, 3, 4, 8]); + let offsets = ScalarBuffer::::from(vec![0, 3, 3, 4]); + let expected = ListArray::new( + Arc::new(Field::new("item", DataType::UInt64, false)), + OffsetBuffer::new(offsets), + Arc::new(expected_items), + Some(list_validity), + ); + + assert_eq!(filtered, expected); + } + + #[test] + fn test_trim_values() { + let items = UInt64Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + let offsets = ScalarBuffer::::from(vec![2, 5, 6, 8, 9]); + let offsets = OffsetBuffer::new(offsets); + let list_arr = ListArray::new( + Arc::new(Field::new("item", DataType::UInt64, true)), + offsets, + Arc::new(items), + None, + ); + let list_arr = list_arr.slice(1, 2); + + let trimmed = list_arr.trimmed_values(); + + let expected_items = UInt64Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + let expected_items = expected_items.slice(5, 3); + + assert_eq!(trimmed.as_ref(), &expected_items); + } +} diff --git a/python/vendor/lance-arrow/src/memory.rs b/python/vendor/lance-arrow/src/memory.rs new file mode 100644 index 000000000..1038a3f91 --- /dev/null +++ b/python/vendor/lance-arrow/src/memory.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::collections::HashSet; + +use arrow_array::{Array, RecordBatch}; +use arrow_data::ArrayData; + +/// Counts memory used by buffers of Arrow arrays and RecordBatches. +/// +/// This is meant to capture how much memory is being used by the Arrow data +/// structures as they are. It does not represent the memory used if the data +/// were to be serialized and then deserialized. In particular: +/// +/// * This does not double count memory used by buffers shared by multiple +/// arrays or batches. Round-tripped data may use more memory because of this. +/// * This counts the **total** size of the buffers, even if the array is a slice. +/// Round-tripped data may use less memory because of this. +#[derive(Default)] +pub struct MemoryAccumulator { + seen: HashSet, + total: usize, +} + +impl MemoryAccumulator { + pub fn record_array(&mut self, array: &dyn Array) { + let data = array.to_data(); + self.record_array_data(&data); + } + + fn record_array_data(&mut self, data: &ArrayData) { + for buffer in data.buffers() { + let ptr = buffer.as_ptr(); + if self.seen.insert(ptr as usize) { + self.total += buffer.capacity(); + } + } + + if let Some(nulls) = data.nulls() { + let null_buf = nulls.inner().inner(); + let ptr = null_buf.as_ptr(); + if self.seen.insert(ptr as usize) { + self.total += null_buf.capacity(); + } + } + + for child in data.child_data() { + self.record_array_data(child); + } + } + + pub fn record_batch(&mut self, batch: &RecordBatch) { + for array in batch.columns() { + self.record_array(array); + } + } + + pub fn total(&self) -> usize { + self.total + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::Int32Array; + use arrow_schema::{DataType, Field, Schema}; + + use super::*; + + #[test] + fn test_memory_accumulator() { + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], + ) + .unwrap(); + let slice = batch.slice(1, 2); + + let mut acc = MemoryAccumulator::default(); + + // Should record whole buffer, not just slice + acc.record_batch(&slice); + assert_eq!(acc.total(), 3 * std::mem::size_of::()); + + // Should not double count + acc.record_batch(&slice); + assert_eq!(acc.total(), 3 * std::mem::size_of::()); + } +} diff --git a/python/vendor/lance-arrow/src/scalar.rs b/python/vendor/lance-arrow/src/scalar.rs new file mode 100644 index 000000000..412253d12 --- /dev/null +++ b/python/vendor/lance-arrow/src/scalar.rs @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use arrow_array::{ArrayRef, UInt64Array, make_array}; +use arrow_buffer::Buffer; +use arrow_data::ArrayDataBuilder; +use arrow_schema::{ArrowError, DataType}; +use arrow_select::take::take; + +use crate::DataTypeExt; + +type Result = std::result::Result; + +pub const INLINE_VALUE_MAX_BYTES: usize = 32; + +pub fn extract_scalar_value(array: &ArrayRef, idx: usize) -> Result { + if idx >= array.len() { + return Err(ArrowError::InvalidArgumentError( + "Scalar index out of bounds".to_string(), + )); + } + + take(array.as_ref(), &UInt64Array::from(vec![idx as u64]), None) +} + +fn read_u32(buf: &[u8], offset: &mut usize) -> Result { + if *offset + 4 > buf.len() { + return Err(ArrowError::InvalidArgumentError( + "Invalid scalar value buffer: unexpected EOF".to_string(), + )); + } + let bytes = [ + buf[*offset], + buf[*offset + 1], + buf[*offset + 2], + buf[*offset + 3], + ]; + *offset += 4; + Ok(u32::from_le_bytes(bytes)) +} + +fn read_bytes<'a>(buf: &'a [u8], offset: &mut usize, len: usize) -> Result<&'a [u8]> { + if *offset + len > buf.len() { + return Err(ArrowError::InvalidArgumentError( + "Invalid scalar value buffer: unexpected EOF".to_string(), + )); + } + let slice = &buf[*offset..*offset + len]; + *offset += len; + Ok(slice) +} + +fn write_u32(out: &mut Vec, v: u32) { + out.extend_from_slice(&v.to_le_bytes()); +} + +fn write_bytes(out: &mut Vec, bytes: &[u8]) { + out.extend_from_slice(bytes); +} + +pub fn encode_scalar_value_buffer(scalar: &ArrayRef) -> Result> { + if scalar.len() != 1 || scalar.null_count() != 0 { + return Err(ArrowError::InvalidArgumentError( + "Scalar value buffer must be a single non-null value".to_string(), + )); + } + let data = scalar.to_data(); + if data.offset() != 0 { + return Err(ArrowError::InvalidArgumentError( + "Scalar value buffer must have offset=0".to_string(), + )); + } + if !data.child_data().is_empty() { + return Err(ArrowError::InvalidArgumentError( + "Scalar value buffer does not support nested types".to_string(), + )); + } + + // Minimal format (RFC): store the Arrow value buffers for a length-1 array. + // Null bitmap and child data are intentionally not supported here. + // + // | u32 num_buffers | + // | u32 buffer_0_len | ... | u32 buffer_{n-1}_len | + // | buffer_0 bytes | ... | buffer_{n-1} bytes | + let mut out = Vec::with_capacity(128); + let buffers = data.buffers(); + write_u32(&mut out, buffers.len() as u32); + for b in buffers { + write_u32(&mut out, b.len() as u32); + } + for b in buffers { + write_bytes(&mut out, b.as_slice()); + } + Ok(out) +} + +pub fn decode_scalar_from_value_buffer( + data_type: &DataType, + value_buffer: &[u8], +) -> Result { + if matches!( + data_type, + DataType::Struct(_) | DataType::FixedSizeList(_, _) + ) { + return Err(ArrowError::InvalidArgumentError(format!( + "Scalar value buffer does not support nested data type {:?}", + data_type + ))); + } + + let mut offset = 0; + let num_buffers = read_u32(value_buffer, &mut offset)? as usize; + let buffer_lens = (0..num_buffers) + .map(|_| read_u32(value_buffer, &mut offset).map(|l| l as usize)) + .collect::>>()?; + + let mut buffers = Vec::with_capacity(num_buffers); + for len in buffer_lens { + let bytes = read_bytes(value_buffer, &mut offset, len)?; + buffers.push(Buffer::from_vec(bytes.to_vec())); + } + + if offset != value_buffer.len() { + return Err(ArrowError::InvalidArgumentError( + "Invalid scalar value buffer: trailing bytes".to_string(), + )); + } + + let mut builder = ArrayDataBuilder::new(data_type.clone()) + .len(1) + .null_count(0); + for b in buffers { + builder = builder.add_buffer(b); + } + Ok(make_array(builder.build()?)) +} + +pub fn decode_scalar_from_inline_value( + data_type: &DataType, + inline_value: &[u8], +) -> Result { + // I expect our input to be safe here, but I added some debug_assert_eq statements just in case. + // If they are triggered, we may need to change them to return actual errors. + // + // Boolean values are bit-packed in Arrow and therefore are not "fixed-stride" in bytes. + // As a result, `byte_width_opt()` returns `None` for `DataType::Boolean`, even though a + // length-1 scalar can be represented inline using a single byte (matching `try_inline_value`). + if matches!(data_type, DataType::Boolean) { + debug_assert_eq!( + inline_value.len(), + 1, + "Invalid boolean inline scalar length (expected 1 byte, got {})", + inline_value.len() + ); + } else if let Some(byte_width) = data_type.byte_width_opt() { + debug_assert_eq!( + inline_value.len(), + byte_width, + "Inline constant length mismatch for {:?}: expected {} bytes but got {}", + data_type, + byte_width, + inline_value.len() + ); + } + + let data = ArrayDataBuilder::new(data_type.clone()) + .len(1) + .null_count(0) + .add_buffer(Buffer::from_vec(inline_value.to_vec())) + .build()?; + Ok(make_array(data)) +} + +pub fn try_inline_value(scalar: &ArrayRef) -> Option> { + if scalar.null_count() != 0 || scalar.len() != 1 { + return None; + } + let data = scalar.to_data(); + if !data.child_data().is_empty() { + return None; + } + if data.buffers().len() != 1 { + return None; + } + let bytes = data.buffers()[0].as_slice(); + if bytes.len() > INLINE_VALUE_MAX_BYTES { + return None; + } + Some(bytes.to_vec()) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::{ + BooleanArray, DictionaryArray, FixedSizeBinaryArray, Int8Array, Int32Array, StringArray, + cast::AsArray, types::Int8Type, + }; + + use super::*; + + #[test] + fn test_extract_scalar_value() { + let array: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), None, Some(3)])); + let scalar = extract_scalar_value(&array, 2).unwrap(); + assert_eq!(scalar.len(), 1); + assert_eq!( + scalar + .as_primitive::() + .value(0), + 3 + ); + } + + #[test] + fn test_extract_scalar_value_from_full_dictionary() { + let values = Arc::new(StringArray::from( + (0..=i8::MAX) + .map(|value| format!("value-{value}")) + .collect::>(), + )); + let keys = Int8Array::from((0..=i8::MAX).collect::>()); + let array: ArrayRef = Arc::new(DictionaryArray::::new(keys, values)); + + let scalar = extract_scalar_value(&array, i8::MAX as usize).unwrap(); + + let scalar = scalar.as_dictionary::(); + assert_eq!(scalar.len(), 1); + assert_eq!(scalar.key(0), Some(i8::MAX as usize)); + assert_eq!(scalar.values().len(), i8::MAX as usize + 1); + } + + #[test] + fn test_scalar_value_buffer_utf8_round_trip() { + let scalar: ArrayRef = Arc::new(StringArray::from(vec!["hello"])); + let buf = encode_scalar_value_buffer(&scalar).unwrap(); + let decoded = decode_scalar_from_value_buffer(&DataType::Utf8, &buf).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded.null_count(), 0); + assert_eq!(decoded.as_string::().value(0), "hello"); + } + + #[test] + fn test_scalar_value_buffer_fixed_size_binary_round_trip() { + let val = vec![0xABu8; 33]; + let scalar: ArrayRef = Arc::new( + FixedSizeBinaryArray::try_from_sparse_iter_with_size( + std::iter::once(Some(val.as_slice())), + 33, + ) + .unwrap(), + ); + let buf = encode_scalar_value_buffer(&scalar).unwrap(); + let decoded = + decode_scalar_from_value_buffer(&DataType::FixedSizeBinary(33), &buf).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded.as_fixed_size_binary().value(0), val.as_slice()); + } + + #[test] + fn test_inline_value_boolean_round_trip() { + let scalar: ArrayRef = Arc::new(BooleanArray::from_iter([Some(true)])); + let inline = try_inline_value(&scalar).unwrap(); + let decoded = decode_scalar_from_inline_value(&DataType::Boolean, &inline).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded.null_count(), 0); + assert!(decoded.as_boolean().value(0)); + } + + #[test] + fn test_scalar_value_buffer_rejects_nested_type() { + let field = Arc::new(arrow_schema::Field::new("item", DataType::Int32, false)); + let list: ArrayRef = Arc::new(arrow_array::FixedSizeListArray::new( + field, + 2, + Arc::new(Int32Array::from(vec![1, 2])), + None, + )); + let scalar = list.slice(0, 1); + assert!(encode_scalar_value_buffer(&scalar).is_err()); + } + + #[test] + fn test_decode_scalar_from_value_buffer_rejects_nested_type() { + let buf = Vec::::new(); + let res = + decode_scalar_from_value_buffer(&DataType::Struct(arrow_schema::Fields::empty()), &buf); + assert!(res.is_err()); + } + + #[test] + fn test_decode_scalar_from_value_buffer_trailing_bytes() { + // num_buffers = 0, plus an extra byte + let mut bytes = Vec::new(); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.push(1); + let res = decode_scalar_from_value_buffer(&DataType::Int32, &bytes); + assert!(res.is_err()); + } +} diff --git a/python/vendor/lance-arrow/src/schema.rs b/python/vendor/lance-arrow/src/schema.rs new file mode 100644 index 000000000..0489dd584 --- /dev/null +++ b/python/vendor/lance-arrow/src/schema.rs @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Extension to arrow schema + +use arrow_schema::{ArrowError, DataType, Field, FieldRef, Schema}; + +use crate::{ARROW_EXT_NAME_KEY, BLOB_META_KEY, BLOB_V2_EXT_NAME}; + +pub enum Indentation { + OneLine, + MultiLine(u8), +} + +impl Indentation { + fn value(&self) -> String { + match self { + Self::OneLine => "".to_string(), + Self::MultiLine(spaces) => " ".repeat(*spaces as usize), + } + } + + fn deepen(&self) -> Self { + match self { + Self::OneLine => Self::OneLine, + Self::MultiLine(spaces) => Self::MultiLine(spaces + 2), + } + } +} + +/// Extends the functionality of [arrow_schema::Field]. +pub trait FieldExt { + /// Create a compact string representation of the field + /// + /// This is intended for display purposes and not for serialization + fn to_compact_string(&self, indent: Indentation) -> String; + + /// Check if the field is marked as a packed struct + fn is_packed_struct(&self) -> bool; + + /// Check if the field is marked as a blob + fn is_blob(&self) -> bool; + + /// Check if the field is marked as a blob + fn is_blob_v2(&self) -> bool; +} + +impl FieldExt for Field { + fn to_compact_string(&self, indent: Indentation) -> String { + let mut result = format!("{}: ", self.name().clone()); + match self.data_type() { + DataType::Struct(fields) => { + result += "{"; + result += &indent.value(); + for (field_idx, field) in fields.iter().enumerate() { + result += field.to_compact_string(indent.deepen()).as_str(); + if field_idx < fields.len() - 1 { + result += ","; + } + result += indent.value().as_str(); + } + result += "}"; + } + DataType::List(field) + | DataType::LargeList(field) + | DataType::ListView(field) + | DataType::LargeListView(field) => { + result += "["; + result += field.to_compact_string(indent.deepen()).as_str(); + result += "]"; + } + DataType::FixedSizeList(child, dimension) => { + result += &format!( + "[{}; {}]", + child.to_compact_string(indent.deepen()), + dimension + ); + } + DataType::Dictionary(key_type, value_type) => { + result += &value_type.to_string(); + result += "@"; + result += &key_type.to_string(); + } + _ => { + result += &self.data_type().to_string(); + } + } + if self.is_nullable() { + result += "?"; + } + result + } + + // Check if field has metadata `packed` set to true, this check is case insensitive. + fn is_packed_struct(&self) -> bool { + let field_metadata = self.metadata(); + const PACKED_KEYS: [&str; 2] = ["packed", "lance-encoding:packed"]; + PACKED_KEYS.iter().any(|key| { + field_metadata + .get(*key) + .map(|value| value.eq_ignore_ascii_case("true")) + .unwrap_or(false) + }) + } + + fn is_blob(&self) -> bool { + let field_metadata = self.metadata(); + field_metadata.get(BLOB_META_KEY).is_some() + || field_metadata + .get(ARROW_EXT_NAME_KEY) + .map(|value| value == BLOB_V2_EXT_NAME) + .unwrap_or(false) + } + + fn is_blob_v2(&self) -> bool { + let field_metadata = self.metadata(); + field_metadata + .get(ARROW_EXT_NAME_KEY) + .map(|value| value == BLOB_V2_EXT_NAME) + .unwrap_or(false) + } +} + +/// Extends the functionality of [arrow_schema::Schema]. +pub trait SchemaExt { + /// Create a new [`Schema`] with one extra field. + fn try_with_column(&self, field: Field) -> std::result::Result; + + fn try_with_column_at( + &self, + index: usize, + field: Field, + ) -> std::result::Result; + + fn field_names(&self) -> Vec<&String>; + + fn without_column(&self, column_name: &str) -> Schema; + + /// Create a compact string representation of the schema + /// + /// This is intended for display purposes and not for serialization + fn to_compact_string(&self, indent: Indentation) -> String; +} + +impl SchemaExt for Schema { + fn try_with_column(&self, field: Field) -> std::result::Result { + if self.column_with_name(field.name()).is_some() { + return Err(ArrowError::SchemaError(format!( + "Can not append column {} on schema: {:?}", + field.name(), + self + ))); + }; + let mut fields: Vec = self.fields().iter().cloned().collect(); + fields.push(FieldRef::new(field)); + Ok(Self::new_with_metadata(fields, self.metadata.clone())) + } + + fn try_with_column_at( + &self, + index: usize, + field: Field, + ) -> std::result::Result { + if self.column_with_name(field.name()).is_some() { + return Err(ArrowError::SchemaError(format!( + "Failed to modify schema: Inserting column {} would create a duplicate column in schema: {:?}", + field.name(), + self + ))); + }; + let mut fields: Vec = self.fields().iter().cloned().collect(); + fields.insert(index, FieldRef::new(field)); + Ok(Self::new_with_metadata(fields, self.metadata.clone())) + } + + /// Project the schema to remove the given column. + /// + /// This only works on top-level fields right now. If a field does not exist, + /// the schema will be returned as is. + fn without_column(&self, column_name: &str) -> Schema { + let fields: Vec = self + .fields() + .iter() + .filter(|f| f.name() != column_name) + .cloned() + .collect(); + Self::new_with_metadata(fields, self.metadata.clone()) + } + + fn field_names(&self) -> Vec<&String> { + self.fields().iter().map(|f| f.name()).collect() + } + + fn to_compact_string(&self, indent: Indentation) -> String { + let mut result = "{".to_string(); + result += &indent.value(); + for (field_idx, field) in self.fields.iter().enumerate() { + result += field.to_compact_string(indent.deepen()).as_str(); + if field_idx < self.fields.len() - 1 { + result += ","; + } + result += indent.value().as_str(); + } + result += "}"; + result + } +} diff --git a/python/vendor/lance-arrow/src/stream.rs b/python/vendor/lance-arrow/src/stream.rs new file mode 100644 index 000000000..5aee834fd --- /dev/null +++ b/python/vendor/lance-arrow/src/stream.rs @@ -0,0 +1,569 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Utilities for working with streams of [`RecordBatch`]. + +use arrow_array::RecordBatch; +use arrow_schema::{ArrowError, SchemaRef}; +use futures::stream::{self, Stream, StreamExt}; +use std::pin::Pin; +use std::vec::IntoIter; + +use crate::deepcopy::deep_copy_batch_sliced; + +/// Rechunks a stream of [`RecordBatch`] so that each output batch has +/// approximately `max_bytes` of array data. +/// +/// Small input batches are accumulated (by concatenation) until at least +/// `min_bytes` of data has been collected. If the resulting batch exceeds +/// `max_bytes`, it is sliced into roughly equal pieces of ~`max_bytes` +/// (assuming uniform row sizes). +/// +/// Slices share the input's buffers, so their array memory sizes may still +/// report the full parent allocation. Once split, all slices are delivered +/// directly, including a final slice smaller than `min_bytes`. +pub fn rechunk_stream_by_size( + input: S, + input_schema: SchemaRef, + min_bytes: usize, + max_bytes: usize, +) -> impl Stream> +where + S: Stream>, + E: From, +{ + rechunk_stream_by_size_inner(input, input_schema, min_bytes, max_bytes, false) +} + +/// Like [`rechunk_stream_by_size`] but deep-copies slices so that +/// `get_array_memory_size` reflects the true size of each output batch. +/// +/// After a normal `RecordBatch::slice`, the backing buffers are shared with +/// the original batch, so `get_array_memory_size` still reports the full +/// parent size. This variant deep-copies every slice produced during the +/// splitting phase, which allows the stream to detect and re-split slices +/// that still exceed `max_bytes` (e.g. because a single row is much larger +/// than average). +/// +/// The deep copy is a last resort and potentially expensive for large +/// batches. However, it is only performed when a batch actually needs to be +/// sliced — batches that are already within the target range pass through at +/// zero cost. Use this only when the hard cap on `max_bytes` is a +/// correctness requirement, not merely a performance hint. +pub fn rechunk_stream_by_size_deep_copy( + input: S, + input_schema: SchemaRef, + min_bytes: usize, + max_bytes: usize, +) -> impl Stream> +where + S: Stream>, + E: From, +{ + rechunk_stream_by_size_inner(input, input_schema, min_bytes, max_bytes, true) +} + +fn rechunk_stream_by_size_inner( + input: S, + input_schema: SchemaRef, + min_bytes: usize, + max_bytes: usize, + deep_copy: bool, +) -> impl Stream> +where + S: Stream>, + E: From, +{ + stream::try_unfold( + RechunkState { + input: Box::pin(input), + accumulated: Vec::new(), + slices: Vec::new().into_iter(), + acc_bytes: 0, + done: false, + input_schema, + min_bytes, + max_bytes, + deep_copy, + }, + |mut state| async move { + // These slices are already sized. Measuring their shared buffers + // again would repeatedly split the tail using the parent size. + if let Some(batch) = state.slices.next() { + return Ok(Some((batch, state))); + } + + if state.done && state.accumulated.is_empty() { + return Ok(None); + } + + // Pull batches until we reach the byte target or exhaust input. + // Always pull at least one batch so that min_bytes=0 works. + while !state.done && (state.accumulated.is_empty() || state.acc_bytes < state.min_bytes) + { + match state.input.next().await { + Some(Ok(batch)) => { + state.acc_bytes += batch.get_array_memory_size(); + state.accumulated.push(batch); + } + Some(Err(e)) => return Err(e), + None => { + state.done = true; + } + } + } + + if state.accumulated.is_empty() { + return Ok(None); + } + + let batch = if state.accumulated.len() == 1 { + state.accumulated.pop().unwrap() + } else { + let b = + arrow_select::concat::concat_batches(&state.input_schema, &state.accumulated) + .map_err(E::from)?; + state.accumulated.clear(); + b + }; + state.acc_bytes = 0; + + // Slice the batch into ~max_bytes pieces assuming uniform row sizes. + let mut slices = + slice_batch(batch, state.max_bytes, state.deep_copy).map_err(E::from)?; + + let first = slices.remove(0); + state.slices = slices.into_iter(); + Ok(Some((first, state))) + }, + ) +} + +/// Slice a batch into pieces of at most `max_bytes`. +/// +/// When `deep_copy` is false, slices share buffers with the original batch +/// and `get_array_memory_size` will still report the parent buffer size. +/// This is fine when the caller only needs approximate sizing. +/// +/// When `deep_copy` is true, each slice is deep-copied so that +/// `get_array_memory_size` reflects the true size. If a deep-copied slice +/// still exceeds `max_bytes` (due to non-uniform row sizes), it is +/// recursively split until every piece is within budget or contains only a +/// single row. +fn slice_batch( + batch: RecordBatch, + max_bytes: usize, + deep_copy: bool, +) -> Result, ArrowError> { + let batch_bytes = batch.get_array_memory_size(); + let num_rows = batch.num_rows(); + + if batch_bytes <= max_bytes { + return Ok(vec![batch]); + } + + if num_rows <= 1 { + // A single row cannot be split further, but the size just measured may + // belong to its source buffer rather than to the row: + // `get_array_memory_size` reports whole buffers, and a slice shares + // them. Returning it uncopied hands the caller that inflated figure -- + // a 100 KB row inside a 200 MB buffer measures as 200 MB, and a caller + // budgeting on it concludes the row cannot fit anywhere. + if deep_copy { + return Ok(vec![deep_copy_batch_sliced(&batch)?]); + } + return Ok(vec![batch]); + } + + let rows_per_chunk = (max_bytes as u64 * num_rows as u64 / batch_bytes as u64).max(1) as usize; + + let mut result = Vec::new(); + let mut offset = 0; + while offset < num_rows { + let len = rows_per_chunk.min(num_rows - offset); + let slice = batch.slice(offset, len); + if deep_copy { + let copied = deep_copy_batch_sliced(&slice)?; + // Recurse: the deep-copied slice has accurate sizes, so if it + // still exceeds max_bytes we can split further. + result.extend(slice_batch(copied, max_bytes, true)?); + } else { + result.push(slice); + } + offset += len; + } + + Ok(result) +} + +/// Internal state for [`rechunk_stream_by_size`]. +/// +/// Kept as a named struct so the `try_unfold` closure stays readable. +struct RechunkState { + input: Pin>, + accumulated: Vec, + slices: IntoIter, + acc_bytes: usize, + done: bool, + input_schema: SchemaRef, + min_bytes: usize, + max_bytes: usize, + deep_copy: bool, +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::sync::Arc; + + use arrow_array::Int32Array; + use arrow_schema::{DataType, Field, Schema}; + use futures::executor::block_on; + + /// A single row that shares a large source buffer must report its own + /// size, not the buffer's. Callers budget on this figure, and an inflated + /// one makes a small row look impossible to place. + #[test] + fn a_single_row_slice_reports_its_own_size() { + use arrow_array::LargeStringArray; + + let row = "x".repeat(100 * 1024); + let values: Vec<&str> = (0..2000).map(|_| row.as_str()).collect(); + let schema = Arc::new(Schema::new(vec![Field::new( + "text", + DataType::LargeUtf8, + false, + )])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(LargeStringArray::from(values))]).unwrap(); + let whole = batch.get_array_memory_size(); + + let one_row = batch.slice(7, 1); + assert_eq!( + one_row.get_array_memory_size(), + whole, + "a slice shares its source buffer, which is the reason this test exists" + ); + + // Budget far below the row so the split recurses to the single-row floor. + let chunks = slice_batch(one_row, 1024, true).unwrap(); + assert_eq!(chunks.len(), 1); + let measured = chunks[0].get_array_memory_size(); + assert_eq!(chunks[0].num_rows(), 1); + assert!( + measured < whole / 100, + "single row still measured as {measured} bytes against a {whole} byte source" + ); + } + + fn make_batch(num_rows: usize) -> RecordBatch { + let schema = test_schema(); + let values: Vec = (0..num_rows as i32).collect(); + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(values))]).unwrap() + } + + fn test_schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])) + } + + fn collect_rechunked( + batches: Vec, + min_bytes: usize, + max_bytes: usize, + ) -> Vec { + let input = stream::iter(batches.into_iter().map(Ok::<_, ArrowError>)); + let rechunked = rechunk_stream_by_size(input, test_schema(), min_bytes, max_bytes); + block_on(rechunked.collect::>()) + .into_iter() + .map(|r| r.unwrap()) + .collect() + } + + fn total_rows(batches: &[RecordBatch]) -> usize { + batches.iter().map(|b| b.num_rows()).sum() + } + + #[test] + fn test_empty_stream() { + let result = collect_rechunked(vec![], 100, 200); + assert!(result.is_empty()); + } + + #[test] + fn test_single_batch_passthrough() { + let batch = make_batch(100); + let bytes = batch.get_array_memory_size(); + // Batch is between min and max — should pass through as-is. + let result = collect_rechunked(vec![batch], bytes / 2, bytes * 2); + assert_eq!(result.len(), 1); + assert_eq!(result[0].num_rows(), 100); + } + + #[test] + fn test_small_batches_concatenated() { + let one_batch_bytes = make_batch(10).get_array_memory_size(); + let batches: Vec<_> = (0..8).map(|_| make_batch(10)).collect(); + // min = 5 batches worth, max = 10 batches worth. + let result = collect_rechunked(batches, one_batch_bytes * 5, one_batch_bytes * 10); + assert_eq!(total_rows(&result), 80); + // Should have been concatenated into fewer batches than the 8 inputs. + assert!( + result.len() < 8, + "expected fewer output batches, got {}", + result.len() + ); + } + + #[test] + fn test_large_batch_sliced() { + let batch = make_batch(1000); + let bytes = batch.get_array_memory_size(); + let result = collect_rechunked(vec![batch], bytes / 8, bytes / 4); + assert_eq!(total_rows(&result), 1000); + assert!( + result.len() >= 4, + "expected at least 4 slices, got {}", + result.len() + ); + } + + #[test] + fn test_sliced_leftovers_are_not_recombined() { + // When a large batch is sliced, leftover slices should be delivered + // one at a time without being split again or concatenated back + // together. We verify zero-copy behavior by checking that + // every output buffer pointer falls inside the original batch's + // allocation (i.e. they are all zero-copy slices, not fresh copies). + let batch = make_batch(1000); + let bytes = batch.get_array_memory_size(); + let orig_data = batch.column(0).to_data(); + let orig_buf = &orig_data.buffers()[0]; + let orig_start = orig_buf.as_ptr() as usize; + let orig_end = orig_start + orig_buf.len(); + + let result = collect_rechunked(vec![batch], bytes / 8, bytes / 4); + + assert_eq!(total_rows(&result), 1000); + assert_eq!( + result.iter().map(RecordBatch::num_rows).collect::>(), + vec![250, 250, 250, 250], + "leftover slices must not be split again using the parent buffer size" + ); + + for (i, b) in result.iter().enumerate() { + let ptr = b.column(0).to_data().buffers()[0].as_ptr() as usize; + assert!( + ptr >= orig_start && ptr < orig_end, + "slice {i} buffer at {ptr:#x} is outside the original allocation \ + [{orig_start:#x}, {orig_end:#x}) — it was re-concatenated" + ); + } + } + + #[test] + fn test_flush_remainder_on_stream_end() { + // Data below min_bytes should still be flushed when the stream ends. + let batch = make_batch(10); + let bytes = batch.get_array_memory_size(); + let result = collect_rechunked(vec![batch], bytes * 100, bytes * 200); + assert_eq!(result.len(), 1); + assert_eq!(result[0].num_rows(), 10); + } + + #[test] + fn test_large_then_small_batches() { + // After a large batch is fully drained, subsequent small batches + // should be accumulated normally. + let large = make_batch(1000); + let large_bytes = large.get_array_memory_size(); + let small_bytes = make_batch(10).get_array_memory_size(); + let batches = vec![ + large, + make_batch(10), + make_batch(10), + make_batch(10), + make_batch(10), + make_batch(10), + ]; + let result = collect_rechunked(batches, small_bytes * 3, large_bytes / 4); + assert_eq!(total_rows(&result), 1050); + assert_eq!( + result.iter().map(RecordBatch::num_rows).collect::>(), + vec![250, 250, 250, 250, 30, 20] + ); + } + + #[test] + fn test_row_preservation_across_slicing() { + // Verify that every input row appears exactly once in the output + // and in the correct order after slicing. + let batch = make_batch(237); // odd count to exercise remainder slice + let bytes = batch.get_array_memory_size(); + let result = collect_rechunked(vec![batch], bytes / 8, bytes / 5); + + assert_eq!(total_rows(&result), 237); + + let values: Vec = result + .iter() + .flat_map(|b| { + b.column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + let expected: Vec = (0..237).collect(); + assert_eq!(values, expected); + } + + #[test] + fn test_min_bytes_zero_still_yields_all_rows() { + // When min_bytes=0, the stream should still yield every batch. + // This is the "chop only, don't coalesce" use case. + let batches: Vec<_> = (0..5).map(|_| make_batch(100)).collect(); + let batch_bytes = batches[0].get_array_memory_size(); + let result = collect_rechunked(batches, 0, batch_bytes * 2); + assert_eq!(total_rows(&result), 500); + } + + #[test] + fn test_min_bytes_zero_slices_oversized() { + // min_bytes=0 with a small max_bytes should still slice large batches. + let batch = make_batch(1000); + let bytes = batch.get_array_memory_size(); + let result = collect_rechunked(vec![batch], 0, bytes / 4); + assert_eq!(total_rows(&result), 1000); + assert_eq!( + result.iter().map(RecordBatch::num_rows).collect::>(), + vec![250, 250, 250, 250] + ); + } + + /// Build a batch with one variable-length string column. + /// Every row is `small_size` bytes except the row at index `big_row_idx` + /// which is `big_size` bytes. + fn make_variable_batch( + num_rows: usize, + small_size: usize, + big_row_idx: usize, + big_size: usize, + ) -> RecordBatch { + let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)])); + let values: Vec = (0..num_rows) + .map(|i| { + if i == big_row_idx { + "X".repeat(big_size) + } else { + "x".repeat(small_size) + } + }) + .collect(); + let array = arrow_array::StringArray::from(values); + RecordBatch::try_new(schema, vec![Arc::new(array)]).unwrap() + } + + fn variable_schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)])) + } + + #[test] + fn test_variable_length_tail_is_not_resliced() { + let batch = make_variable_batch(100, 256, usize::MAX, 256); + let bytes = batch.get_array_memory_size(); + let max_bytes = bytes - bytes / 4; + let input = stream::iter(vec![Ok::<_, ArrowError>(batch)]); + let rechunked = rechunk_stream_by_size(input, variable_schema(), max_bytes, max_bytes); + let result: Vec<_> = block_on(rechunked.collect::>()) + .into_iter() + .map(Result::unwrap) + .collect(); + + assert_eq!( + result.iter().map(RecordBatch::num_rows).collect::>(), + vec![75, 25] + ); + assert_eq!(total_rows(&result), 100); + } + + fn collect_rechunked_variable( + batches: Vec, + min_bytes: usize, + max_bytes: usize, + ) -> Vec { + let input = stream::iter(batches.into_iter().map(Ok::<_, ArrowError>)); + let rechunked = + rechunk_stream_by_size_deep_copy(input, variable_schema(), min_bytes, max_bytes); + block_on(rechunked.collect::>()) + .into_iter() + .map(|r| r.unwrap()) + .collect() + } + + #[test] + fn test_oversized_row_at_end() { + // 100 rows: 99 small (64 bytes each) + 1 large (100KiB) at the end. + let batch = make_variable_batch(100, 64, 99, 100 * 1024); + let max_bytes = 64 * 1024; + let result = collect_rechunked_variable(vec![batch], 0, max_bytes); + assert_eq!(total_rows(&result), 100); + for (i, b) in result.iter().enumerate() { + let size = b.get_array_memory_size(); + assert!( + size <= max_bytes || b.num_rows() == 1, + "batch {i} has {size} bytes (max {max_bytes}) and {} rows", + b.num_rows() + ); + } + } + + #[test] + fn test_oversized_row_at_start() { + // 100 rows: 1 large (100KiB) at the start + 99 small (64 bytes each). + let batch = make_variable_batch(100, 64, 0, 100 * 1024); + let max_bytes = 64 * 1024; + let result = collect_rechunked_variable(vec![batch], 0, max_bytes); + assert_eq!(total_rows(&result), 100); + for (i, b) in result.iter().enumerate() { + let size = b.get_array_memory_size(); + assert!( + size <= max_bytes || b.num_rows() == 1, + "batch {i} has {size} bytes (max {max_bytes}) and {} rows", + b.num_rows() + ); + } + } + + #[test] + fn test_oversized_row_in_middle() { + // 100 rows: 1 large (100KiB) in the middle + 99 small (64 bytes each). + let batch = make_variable_batch(100, 64, 50, 100 * 1024); + let max_bytes = 64 * 1024; + let result = collect_rechunked_variable(vec![batch], 0, max_bytes); + assert_eq!(total_rows(&result), 100); + for (i, b) in result.iter().enumerate() { + let size = b.get_array_memory_size(); + assert!( + size <= max_bytes || b.num_rows() == 1, + "batch {i} has {size} bytes (max {max_bytes}) and {} rows", + b.num_rows() + ); + } + } + + #[test] + fn test_error_propagation() { + let input = stream::iter(vec![ + Ok(make_batch(10)), + Err(ArrowError::ComputeError("boom".into())), + Ok(make_batch(10)), + ]); + let rechunked = rechunk_stream_by_size(input, test_schema(), 1, usize::MAX); + let results: Vec> = block_on(rechunked.collect()); + assert!(results.iter().any(|r| r.is_err())); + } +} diff --git a/python/vendor/lance-arrow/src/struct.rs b/python/vendor/lance-arrow/src/struct.rs new file mode 100644 index 000000000..ed4b6288e --- /dev/null +++ b/python/vendor/lance-arrow/src/struct.rs @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Extension to arrow struct arrays + +use arrow_array::{Array, StructArray, cast::AsArray, make_array}; +use arrow_buffer::NullBuffer; +use arrow_data::{ArrayData, ArrayDataBuilder}; +use arrow_schema::{ArrowError, DataType}; + +pub trait StructArrayExt { + /// Removes the offset / length of the struct array by pushing it into the children + /// + /// In arrow-rs when slice is called it recursively slices the children. + /// In arrow-cpp when slice is called it just sets the offset/length of + /// the struct array and leaves the children as-is + /// + /// Both are legal approaches (╥﹏╥) + /// + /// This method helps reduce complexity by folding into the arrow-rs approach + fn normalize_slicing(&self) -> Result + where + Self: Sized; + + /// Structs are allowed to mask valid items. For example, a struct array might be: + /// + /// [ {"items": [1, 2, 3]}, NULL, {"items": NULL}] + /// + /// However, the underlying items array might be: [[1, 2, 3], [4, 5], NULL] + /// + /// The [4, 5] list is masked out because the struct array is null. + /// + /// The struct validity would be [true, false, true] and the list validity would be [true, true, false] + /// + /// This method pushes nulls down into all children. In the above example the list validity would become + /// [true, false, false]. + /// + /// This method is not recursive. If a child is a struct array it will not push that child's nulls down. + /// + /// This method does not remove garbage lists. It only updates the validity so a future call to + /// [crate::list::ListArrayExt::filter_garbage_nulls] will remove the garbage lists (without + /// this pushdown it would not) + fn pushdown_nulls(&self) -> Result + where + Self: Sized; +} + +fn normalized_struct_array_data(data: ArrayData) -> Result { + let parent_offset = data.offset(); + let parent_len = data.len(); + let modified_children = data + .child_data() + .iter() + .map(|d| { + let d = normalized_struct_array_data(d.clone())?; + let offset = d.offset(); + let len = d.len(); + if len < parent_len + parent_offset { + return Err(ArrowError::InvalidArgumentError(format!( + "Child array {} has length {} which is less than the parent length {} plus the parent offset {}", + d.data_type(), + len, + parent_len, + parent_offset + ))); + } + let new_offset = offset + parent_offset; + d.into_builder().offset(new_offset) + .len(parent_len) + .build() + }) + .collect::, _>>()?; + ArrayDataBuilder::new(data.data_type().clone()) + .len(parent_len) + .offset(0) + .buffers(data.buffers().to_vec()) + .child_data(modified_children) + .build() +} + +impl StructArrayExt for StructArray { + fn normalize_slicing(&self) -> Result + where + Self: Sized, + { + if self.offset() == 0 && self.columns().iter().all(|c| c.len() == self.len()) { + return Ok(self.clone()); + } + + let data = normalized_struct_array_data(self.to_data())?; + Ok(Self::from(data)) + } + + fn pushdown_nulls(&self) -> Result + where + Self: Sized, + { + let Some(validity) = self.nulls() else { + return Ok(self.clone()); + }; + let data = self.to_data(); + let children = data + .child_data() + .iter() + .map(|c| { + if c.data_type() == &DataType::Null { + // A Null array is already null in every slot, and arrow-rs rejects + // a validity buffer on it. + Ok(c.clone()) + } else if let Some(child_validity) = c.nulls() { + let new_validity = child_validity.inner() & validity.inner(); + c.clone() + .into_builder() + .nulls(Some(NullBuffer::from(new_validity))) + .build() + } else { + Ok(c.clone() + .into_builder() + .nulls(Some(validity.clone())) + .build()?) + } + }) + .collect::, _>>()?; + let arr = make_array(data.into_builder().child_data(children).build()?); + Ok(arr.as_struct().clone()) + } +} + +#[cfg(test)] +mod tests { + use arrow_array::{ + Array, Int32Array, NullArray, StructArray, cast::AsArray, make_array, types::Int32Type, + }; + use arrow_buffer::NullBuffer; + use arrow_schema::{DataType, Field, Fields}; + use std::sync::Arc; + + use crate::r#struct::StructArrayExt; + + #[test] + fn test_normalize_slicing_no_offset() { + let x = Int32Array::from(vec![1, 2, 3]); + let y = Int32Array::from(vec![4, 5, 6]); + let struct_array = StructArray::new( + Fields::from(vec![ + Field::new("x", DataType::Int32, true), + Field::new("y", DataType::Int32, true), + ]), + vec![Arc::new(x), Arc::new(y)], + None, + ); + + let normalized = struct_array.normalize_slicing().unwrap(); + assert_eq!(normalized, struct_array); + } + + #[test] + fn test_arrow_rs_slicing() { + let x = Int32Array::from(vec![1, 2, 3, 4]); + let y = Int32Array::from(vec![5, 6, 7, 8]); + let struct_array = StructArray::new( + Fields::from(vec![ + Field::new("x", DataType::Int32, true), + Field::new("y", DataType::Int32, true), + ]), + vec![Arc::new(x), Arc::new(y)], + None, + ); + + // Slicing with arrow-rs propagates the slicing to the children so there should + // be no change needed to the struct array + let sliced = struct_array.slice(1, 2); + let normalized = sliced.normalize_slicing().unwrap(); + + assert_eq!(normalized, sliced); + } + + #[test] + fn test_arrow_cpp_slicing() { + let x = Int32Array::from(vec![1, 2, 3, 4]); + let y = Int32Array::from(vec![5, 6, 7, 8]); + let struct_array = StructArray::new( + Fields::from(vec![ + Field::new("x", DataType::Int32, true), + Field::new("y", DataType::Int32, true), + ]), + vec![Arc::new(x), Arc::new(y)], + None, + ); + + let data = struct_array.to_data(); + let sliced = data.into_builder().offset(1).len(2).build().unwrap(); + let sliced = make_array(sliced); + let normalized = sliced.as_struct().clone().normalize_slicing().unwrap(); + + assert_eq!(normalized, struct_array.slice(1, 2)); + } + + #[test] + fn test_pushdown_nulls_with_null_typed_child() { + // `pa.Table.from_pylist([{"s": {"a": 1, "b": None}}, {"s": None}])` infers a + // struct with a Null-typed child. Arrow forbids a validity buffer on a Null + // array, so the struct's nulls must not be pushed into it. + let struct_array = StructArray::new( + Fields::from(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Null, true), + ]), + vec![ + Arc::new(Int32Array::from(vec![1, 2, 3])), + Arc::new(NullArray::new(3)), + ], + Some(NullBuffer::from(vec![true, false, true])), + ); + + let pushed = struct_array.pushdown_nulls().unwrap(); + + assert_eq!(pushed.nulls(), struct_array.nulls()); + assert_eq!( + pushed.column(0).as_primitive::(), + &Int32Array::from(vec![Some(1), None, Some(3)]) + ); + assert_eq!(pushed.column(1).data_type(), &DataType::Null); + assert_eq!(pushed.column(1).logical_null_count(), 3); + } +} diff --git a/release_process.md b/release_process.md index f223504a7..a1130fdf7 100644 --- a/release_process.md +++ b/release_process.md @@ -24,6 +24,68 @@ from the packaging index after a while. Once your application is stable, we recommend switching to full releases, which will never be removed from package indexes. +## Prepare a stable release + +### Select the release baseline + +Choose the SDK product commit for the planned release and record its SHA. Include +all fixes required for that release, including security fixes. Create and push a +release branch such as `release/v0.41` from that commit before opening the Lance RC +upgrade PR. For a patch to an existing stable line, reuse its release branch and +backport the required fixes. + +Keep the selected product baseline while main continues development. If main +already tracks a newer Lance development version, retain that dependency on main +and prepare the stable Lance dependency on the SDK release branch. Any additional +fixes should arrive through reviewed PRs into the release branch and be validated. + +### Validate the Lance RC + +1. Open a **draft PR targeting the SDK release branch** to consume the exact Lance + RC. Check both the PR base and dependency references when using automation. + Update the Rust declarations and lockfile, Python dependency declarations and + lockfile, and Java Maven version consistently. +2. Wait for the RC artifacts needed by each SDK to be available, then run the + relevant Rust, Python, Node.js, Java, and packaging checks. Resolve compatibility + failures and rerun CI after changes to the PR or its release-branch base. +3. Complete code and compatibility review on the RC pin PR. If draft status + skips Gatekeeper or another applicable review, mark the PR ready for review or + explicitly run the review. Read the recommendation and inline findings even + when GitHub records them as comments. Passing CI or a skipped review does not + clear an unresolved blocking finding. +4. Before the Lance vote is closed and Lance stable is published, the pin PR + must be **ready to merge**: all relevant CI and reviews are complete, with no + unresolved blocking findings at its current head and release-branch base. + Refresh reviews and comments immediately before reporting readiness. +5. Report the exact Lance tag and peeled SHA, + SDK release-branch base and PR head SHAs (and tested merge commit, when + applicable), full CI results and review outcomes to the release manager. + Label local source checks separately from checks consuming the published RC + artifacts. + +Keep the RC validation PR unmerged until Lance is approved, while completing all +substantive compatibility and review work before Lance stable publication. Once +the official stable Lance artifacts are available, only the mechanical +RC-to-stable dependency update and validation of those packages should remain. +Update the PR, rerun the relevant checks and refresh reviews. In particular, +verify that the Rust package resolves +published dependencies: Cargo only reads [`[patch]` settings at the workspace root](https://doc.rust-lang.org/cargo/reference/overriding-dependencies.html#the-patch-section), +so package consumers do not inherit a dependency's workspace override. Merge the +validated stable update into the SDK release branch. + +### Publish the validated candidate + +Run **Create Release Commit** from the verified SDK release-branch head. Do not +switch to a later main snapshot after validation. Start with a dry run, review the +expected version and lockfile updates, and use the same branch and release inputs +for the real run. + +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. + ## Making releases The release process uses a handful of GitHub actions to automate the process. @@ -54,7 +116,17 @@ To start a release, trigger a `Create Release Commit` action from (Click on "Run workflow"). * **For a preview release**, leave the default parameters. -* **For a stable release**, set the `release_type` input to `stable`. +* **For a stable release**, select the verified release branch and set the `type` input to `stable`. + +For example, dry-run a stable release from the selected branch: + +```bash +gh workflow run make-release-commit.yml --repo lancedb/lancedb \ + --ref release/v0.41 -f type=stable -f dry_run=true -f bump-minor=false +``` + +After reviewing the dry run, use the same branch and inputs with `dry_run=false`. +Select `bump-minor` according to the version and breaking-change check below. > [!IMPORTANT] > If there was a breaking change since the last stable release, and we haven't diff --git a/rust/lancedb/CHANGELOG.md b/rust/lancedb/CHANGELOG.md new file mode 100644 index 000000000..028f67128 --- /dev/null +++ b/rust/lancedb/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +## Unreleased + +- `BaseTableAdapter` now defaults to `BlobSchema::Read`, exposing the Blob v2 + descriptors returned by scans. SQL INSERT into Blob v2 tables requires opting + into `BlobSchema::Write` with `with_blob_schema`. Write-mode queries support + scalar projections that exclude blobs, scalar filters, and `COUNT(*)`. + Scans must exactly match the projected provider schema, including metadata + and nullability. Blob v2 descriptor scans fail during planning; legacy v1 + blobs expose `LargeBinary` write inputs and reject descriptor scans with a + schema mismatch. A scalar sibling inside a blob-containing struct also needs + a separate read adapter because DataFusion projects the whole parent struct. + Tables without blob columns behave the same in both modes. Generated `_rowid`, + `_rowaddr`, and `_score` columns are exposed only in read mode. diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 1daeef984..64252f772 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.9" +version = "0.41.0-beta.17" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true @@ -8,6 +8,7 @@ repository.workspace = true keywords.workspace = true categories.workspace = true rust-version.workspace = true +exclude = ["cli/**"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] @@ -22,7 +23,7 @@ arrow-ord = { workspace = true } arrow-cast = { workspace = true } arrow-ipc.workspace = true arrow-flight = { workspace = true, optional = true } -prost = { version = "0.14", optional = true } +prost = { workspace = true, optional = true } chrono = { workspace = true } datafusion-catalog.workspace = true datafusion-common.workspace = true @@ -55,6 +56,7 @@ moka = { workspace = true } pin-project = { workspace = true } tokio = { workspace = true, features = ["io-util", "net", "time"] } log.workspace = true +tracing.workspace = true async-trait = { workspace = true } bytes = { workspace = true } futures.workspace = true @@ -85,16 +87,16 @@ reqwest = { version = "0.13.0", default-features = false, features = [ "system-proxy", ], optional = true } tonic = { workspace = true, optional = true } -http = { version = "1", optional = true } # Matching what is in reqwest +http = { workspace = true, optional = true } # Matching what is in reqwest oauth2 = { workspace = true, optional = true } urlencoding = { version = "2", optional = true } -base64 = { version = "0.22", optional = true } +base64 = { workspace = true, optional = true } fs4 = { version = "0.13", optional = true } webbrowser = { version = "1", optional = true } uuid = { workspace = true, features = ["v5"] } polars-arrow = { version = ">=0.37,<0.40.0", optional = true } polars = { version = ">=0.37,<0.40.0", optional = true } -hf-hub = { version = "0.4.1", optional = true, default-features = false, features = [ +hf-hub = { workspace = true, optional = true, features = [ "rustls-tls", "tokio", "ureq", @@ -105,10 +107,10 @@ candle-nn = { version = "0.9.1", optional = true } tokenizers = { version = "0.19.1", optional = true } semver = { workspace = true } roaring = "0.11.4" -sha2 = "0.10" +sha2.workspace = true [dev-dependencies] -anyhow = "1" +anyhow.workspace = true 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. @@ -129,13 +131,16 @@ datafusion.workspace = true http-body = "1" # Matching reqwest rstest = "0.23.0" test-log = "0.2" -serial_test = "3" +serial_test.workspace = true [target.'cfg(unix)'.dev-dependencies] pprof = { version = "0.14", features = ["flamegraph"] } [features] default = [] +# Local SQL computed columns and materialized-view creation/refresh. +# Remote clients and shared server primitives do not require this feature. +experimental-functions = [] # Native spatial indexes and queries. Remote RTree requests do not require this feature. geo = ["lance/geo"] aws = [ diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml new file mode 100644 index 000000000..df9291647 --- /dev/null +++ b/rust/lancedb/cli/Cargo.toml @@ -0,0 +1,52 @@ +[package] +name = "lancedb-cli" +version = "0.1.0" +edition = "2021" +license.workspace = true +repository.workspace = true +publish = false + +[[bin]] +name = "lancedb" +path = "src/main.rs" + +[dependencies] +tempfile.workspace = true +which = "6" +anyhow.workspace = true +arrow-array.workspace = true +arrow-buffer.workspace = true +arrow-cast.workspace = true +arrow-json = "59.2.0" +arrow-schema.workspace = true +async-trait.workspace = true +clap = { version = "4.5.13", features = ["derive", "env"] } +directories = "5" +futures.workspace = true +http.workspace = true +lancedb = { workspace = true, features = ["remote"] } +rustyline = "14" +rustls = { version = "0.23", features = ["ring"] } +serde = { workspace = true, features = ["derive"] } +serde_ignored = "0.1.14" +serde_json.workspace = true +sha2.workspace = true +sqlparser = { version = "0.62", default-features = false, features = ["std"] } +termsize = "0.1" +tokio = { workspace = true, features = ["full"] } +toml = "0.8" +tracing.workspace = true +unicode-width = "0.2" + +[dev-dependencies] +arrow-flight.workspace = true +prost.workspace = true +rcgen = "0.12" +tokio-stream = { version = "0.1", features = ["net"] } +half.workspace = true +axum = "0.8" +base64.workspace = true +csv = "1" +reqwest = { version = "0.12", features = ["json"] } +tonic.workspace = true +url.workspace = true diff --git a/rust/lancedb/cli/src/auth.rs b/rust/lancedb/cli/src/auth.rs new file mode 100644 index 000000000..090bfd1d8 --- /dev/null +++ b/rust/lancedb/cli/src/auth.rs @@ -0,0 +1,419 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! CLI configuration and transport adapters for LanceDB's OAuth implementation. + +use std::collections::HashMap; +use std::path::PathBuf; + +use anyhow::{anyhow, ensure, Context, Result}; +use clap::{Args, Subcommand}; +use lancedb::remote::{ + AuthorizationCodeOptions, ClientAuthMethod, HeaderProvider, OAuthConfig, OAuthFlow, + OAuthHeaderProvider, OAuthSession, TokenCacheOptions, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tokio::sync::OnceCell; + +use crate::server_config::{Authentication, Config, DEFAULT_PROFILE}; + +const CLIENT_SECRET_ENV: &str = "LANCEDB_OIDC_CLIENT_SECRET"; +pub const OIDC_CREDENTIAL_HEADER: &str = "x-lancedb-credential-type"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OidcFlow { + ClientCredentials, + AuthorizationCode, + DeviceCode, +} + +impl std::fmt::Display for OidcFlow { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::ClientCredentials => "client_credentials", + Self::AuthorizationCode => "authorization_code", + Self::DeviceCode => "device_code", + }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OidcClientAuthMethod { + None, + ClientSecretBasic, + ClientSecretPost, +} + +impl From for ClientAuthMethod { + fn from(method: OidcClientAuthMethod) -> Self { + match method { + OidcClientAuthMethod::None => Self::None, + OidcClientAuthMethod::ClientSecretBasic => Self::ClientSecretBasic, + OidcClientAuthMethod::ClientSecretPost => Self::ClientSecretPost, + } + } +} + +/// Nonsecret configuration stored inside a connection profile. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OidcConfig { + pub flow: OidcFlow, + pub issuer_url: String, + pub client_id: String, + pub scopes: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_secret_file: Option, + /// When omitted, the SDK selects authentication based on the client secret. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_auth_method: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resource: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub audience: Option, + /// Registered loopback callback URI for authorization-code login. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub redirect_uri: Option, + /// Defaults to the SDK's callback port (8400). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub callback_port: Option, + /// Defaults to the SDK's refresh buffer (300 seconds). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refresh_buffer_secs: Option, +} + +/// One SDK provider is shared by all transports using the resolved profile. +#[derive(Debug)] +pub struct ManagedOidc { + config: OidcConfig, + cache_dir: PathBuf, + provider: OnceCell, +} + +impl PartialEq for ManagedOidc { + fn eq(&self, other: &Self) -> bool { + // Acquired tokens do not change which authentication configuration was selected. + self.config == other.config && self.cache_dir == other.cache_dir + } +} +impl Eq for ManagedOidc {} + +/// A resolved credential, with no provider state attached. +pub enum Credential { + ApiKey(String), + OidcAccessToken(String), +} + +impl std::fmt::Debug for Credential { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::ApiKey(_) => "ApiKey()", + Self::OidcAccessToken(_) => "OidcAccessToken()", + }) + } +} + +impl Credential { + pub fn headers(&self) -> Result { + let mut headers = http::HeaderMap::new(); + let (name, value) = match self { + Self::ApiKey(key) => ("x-api-key", key.clone()), + Self::OidcAccessToken(token) => { + headers.insert( + OIDC_CREDENTIAL_HEADER, + http::HeaderValue::from_static("oidc"), + ); + ("authorization", format!("Bearer {token}")) + } + }; + let mut value = http::HeaderValue::from_str(&value) + .map_err(|_| anyhow!("Invalid authentication credential: not a valid HTTP header"))?; + value + .to_str() + .map_err(|_| anyhow!("Invalid authentication credential: expected an ASCII header"))?; + value.set_sensitive(true); + headers.insert(name, value); + Ok(headers) + } +} + +impl Authentication { + pub async fn headers(&self) -> Result { + match self { + Self::ApiKey(key) => Credential::ApiKey(key.clone()).headers(), + Self::OidcAccessToken(token) => Credential::OidcAccessToken(token.clone()).headers(), + Self::OidcAccessTokenFile(path) => { + let token = tokio::fs::read_to_string(path).await.with_context(|| { + format!("Failed to read OIDC access token file {}", path.display()) + })?; + let token = token.trim(); + ensure!(!token.is_empty(), "OIDC access token file is empty"); + Credential::OidcAccessToken(token.to_owned()).headers() + } + Self::ManagedOidc(session) => session.headers().await, + } + } +} + +#[async_trait::async_trait] +impl HeaderProvider for Authentication { + async fn get_headers(&self) -> lancedb::Result> { + let headers = self + .headers() + .await + .map_err(|error| lancedb::Error::Runtime { + message: format!("Authentication failed: {error:#}"), + })?; + Ok(headers + .iter() + .map(|(key, value)| { + ( + key.as_str().to_owned(), + value + .to_str() + .expect("validated credential header") + .to_owned(), + ) + }) + .collect()) + } +} + +impl ManagedOidc { + pub fn for_profile(profile: &str, config: OidcConfig) -> Result { + let root = Config::default_config_path()?; + // Profile names are arbitrary strings; hashing prevents paths from escaping the cache. + let profile_key = format!("{:x}", Sha256::digest(profile.as_bytes())); + Self::new( + config, + root.parent().unwrap().join("auth").join(profile_key), + ) + } + + fn new(config: OidcConfig, cache_dir: PathBuf) -> Result { + ensure!( + !config.client_id.trim().is_empty(), + "OIDC client_id cannot be empty" + ); + ensure!( + !config.scopes.is_empty(), + "OIDC scopes must contain at least one scope" + ); + ensure!( + config.flow == OidcFlow::AuthorizationCode + || (config.redirect_uri.is_none() && config.callback_port.is_none()), + "redirect_uri and callback_port require flow = authorization_code" + ); + Ok(Self { + config, + cache_dir, + provider: OnceCell::new(), + }) + } + + pub fn flow(&self) -> &OidcFlow { + &self.config.flow + } + + async fn sdk_config(&self) -> Result { + let flow = match self.config.flow { + OidcFlow::ClientCredentials => OAuthFlow::ClientCredentials, + OidcFlow::DeviceCode => OAuthFlow::DeviceCode, + OidcFlow::AuthorizationCode => { + let mut options = AuthorizationCodeOptions::new(); + if let Some(uri) = &self.config.redirect_uri { + options = options.redirect_uri(uri); + } + if let Some(port) = self.config.callback_port { + options = options.callback_port(port); + } + OAuthFlow::AuthorizationCode(options) + } + }; + Ok(OAuthConfig { + issuer_url: self.config.issuer_url.clone(), + client_id: self.config.client_id.clone(), + client_secret: self.client_secret().await?, + scopes: self.config.scopes.clone(), + resource: self.config.resource.clone(), + audience: self.config.audience.clone(), + flow, + client_auth_method: self.config.client_auth_method.map(Into::into), + refresh_buffer_secs: self.config.refresh_buffer_secs, + token_cache: (self.config.flow != OidcFlow::ClientCredentials) + .then(|| TokenCacheOptions::new().cache_dir(&self.cache_dir)), + }) + } + + async fn provider(&self) -> Result<&OAuthHeaderProvider> { + self.provider + .get_or_try_init(|| async { + OAuthHeaderProvider::new(self.sdk_config().await?).map_err(sdk_error) + }) + .await + } + + async fn session(&self) -> Result { + OAuthSession::new(self.sdk_config().await?).map_err(sdk_error) + } + + async fn headers(&self) -> Result { + let values = self + .provider() + .await? + .get_headers() + .await + .map_err(sdk_error)?; + let mut headers = http::HeaderMap::new(); + for (name, value) in values { + let name = http::HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| anyhow!("Invalid authentication header name"))?; + let mut value = http::HeaderValue::from_str(&value).map_err(|_| { + anyhow!("Invalid authentication credential: not a valid HTTP header") + })?; + value.to_str().map_err(|_| { + anyhow!("Invalid authentication credential: expected an ASCII header") + })?; + if name == http::header::AUTHORIZATION || name == "x-api-key" { + value.set_sensitive(true); + } + headers.insert(name, value); + } + Ok(headers) + } + + async fn client_secret(&self) -> Result> { + if let Some(secret) = std::env::var_os(CLIENT_SECRET_ENV) { + let secret = secret + .into_string() + .map_err(|_| anyhow!("{CLIENT_SECRET_ENV} must be UTF-8"))?; + ensure!(!secret.is_empty(), "{CLIENT_SECRET_ENV} cannot be empty"); + return Ok(Some(secret)); + } + let Some(path) = self.config.client_secret_file.as_ref() else { + ensure!( + self.config.flow != OidcFlow::ClientCredentials, + "Client credentials require LANCEDB_OIDC_CLIENT_SECRET or oidc.client_secret_file" + ); + return Ok(None); + }; + let secret = tokio::fs::read_to_string(path) + .await + .context("Failed to read OIDC client secret file")?; + let secret = secret.trim(); + ensure!(!secret.is_empty(), "OIDC client secret file is empty"); + Ok(Some(secret.to_owned())) + } +} + +fn sdk_error(error: lancedb::Error) -> anyhow::Error { + // SDK runtime errors can contain provider response bodies and credentials. + // Configuration errors are local; never attach the original runtime error as a cause. + match error { + lancedb::Error::InvalidInput { message } => anyhow!("Invalid OIDC configuration: {message}"), + _ => anyhow!("OIDC authentication failed; check the issuer, client credentials, scopes, and provider availability. For a cached interactive session, try lancedb auth logout followed by lancedb auth login."), + } +} + +#[derive(Args, Debug)] +pub struct AuthArgs { + #[command(subcommand)] + pub command: AuthCommand, +} + +#[derive(Subcommand, Debug)] +pub enum AuthCommand { + /// Log in using the profile's OAuth flow; browser/device sessions cache refresh tokens. + Login(ProfileArgs), + /// Report whether an interactive session is cached, without contacting the provider. + Status(ProfileArgs), + /// Clear the profile's local interactive session; does not revoke provider credentials. + Logout(ProfileArgs), +} + +#[derive(Args, Debug)] +pub struct ProfileArgs { + #[arg(short = 'p', long, value_name = "PROFILE")] + pub profile: Option, +} + +pub async fn run(args: AuthArgs, parent_profile: Option) -> Result<()> { + let profile_args = match &args.command { + AuthCommand::Login(args) | AuthCommand::Status(args) | AuthCommand::Logout(args) => args, + }; + let config = Config::load_default()?; + let profile_name = profile_args + .profile + .clone() + .or(parent_profile) + .or(config.default_profile.clone()) + .unwrap_or_else(|| DEFAULT_PROFILE.to_owned()); + let profile = config + .profiles + .get(&profile_name) + .context("Profile does not exist")?; + profile.validate_authentication()?; + let oidc = profile + .oidc + .clone() + .context("Profile has no managed OIDC configuration")?; + let managed = ManagedOidc::for_profile(&profile_name, oidc)?; + match args.command { + AuthCommand::Login(_) => { + if managed.config.flow == OidcFlow::ClientCredentials { + managed.headers().await?; + println!("Authenticated service account for profile '{profile_name}'. Access tokens are cached only within each process."); + } else { + let status = managed.session().await?.login().await.map_err(sdk_error)?; + println!( + "Authenticated profile '{profile_name}' using {}", + managed.flow() + ); + if !status.refreshable { + eprintln!("The provider returned no refresh token; later commands will need another login. Check the provider's offline-access scope and consent settings."); + } + } + if [ + "LANCEDB_API_KEY", + "LANCEDB_OIDC_ACCESS_TOKEN", + "LANCEDB_OIDC_ACCESS_TOKEN_FILE", + ] + .iter() + .any(|key| std::env::var_os(key).is_some()) + { + eprintln!("Authentication environment overrides are set; ordinary commands will use those credentials instead of this session."); + } + } + AuthCommand::Status(_) => { + if managed.config.flow == OidcFlow::ClientCredentials { + println!("Profile '{profile_name}' uses client credentials; no persistent session is stored."); + } else { + let status = managed.session().await?.status().await.map_err(sdk_error)?; + println!( + "Profile '{profile_name}' uses {}; cached refresh token: {}", + managed.flow(), + if status.refreshable { + "present" + } else { + "not present" + } + ); + } + } + AuthCommand::Logout(_) => { + if managed.config.flow == OidcFlow::ClientCredentials { + println!("Profile '{profile_name}' uses client credentials; no persistent session to clear. Configured credentials remain usable."); + } else { + managed.session().await?.logout().await.map_err(sdk_error)?; + println!("Cleared the local session for profile '{profile_name}'. Provider credentials remain valid."); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/rust/lancedb/cli/src/auth/tests.rs b/rust/lancedb/cli/src/auth/tests.rs new file mode 100644 index 000000000..5d626f5e6 --- /dev/null +++ b/rust/lancedb/cli/src/auth/tests.rs @@ -0,0 +1,417 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use super::*; +use axum::{ + extract::{Form, Query}, + http::{HeaderMap, StatusCode}, + response::Redirect, + routing::{get, post}, + Json, Router, +}; +use base64::Engine; +use std::fs; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tempfile::TempDir; + +struct Provider { + config: OidcConfig, + requests: Arc>>>, + server: tokio::task::JoinHandle<()>, + dir: TempDir, +} + +impl Drop for Provider { + fn drop(&mut self) { + self.server.abort(); + } +} + +impl Provider { + async fn start(flow: OidcFlow, lifetime: u64) -> Self { + let dir = tempfile::tempdir().unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let issuer = format!("http://{}", listener.local_addr().unwrap()); + let secret_file = dir.path().join("secret"); + fs::write(&secret_file, "test-secret\n").unwrap(); + let config = OidcConfig { + client_auth_method: None, + client_secret_file: (flow == OidcFlow::ClientCredentials).then_some(secret_file), + flow, + issuer_url: issuer.clone(), + client_id: "cli-client".into(), + scopes: vec!["openid".into(), "offline_access".into()], + resource: Some("https://api.example.com/a?x=1&y=two".into()), + audience: Some("lancedb + audience".into()), + redirect_uri: None, + callback_port: None, + refresh_buffer_secs: Some(0), + }; + let metadata = serde_json::json!({ + "issuer": issuer, + "token_endpoint": format!("{issuer}/token"), + "authorization_endpoint": format!("{issuer}/authorize"), + "device_authorization_endpoint": format!("{issuer}/device"), + }); + let device = serde_json::json!({ + "device_code": "device-code", "user_code": "CLI-CODE", + "verification_uri": format!("{issuer}/verify"), "expires_in": 60, "interval": 1, + }); + let requests = Arc::new(Mutex::new(Vec::new())); + let device_requests = requests.clone(); + let auth_requests = requests.clone(); + let token_requests = requests.clone(); + let app = Router::new() + .route("/.well-known/openid-configuration", get(move || { + let metadata = metadata.clone(); + async move { Json(metadata) } + })) + .route("/verify", get(|| async { "verified" })) + .route("/device", post(move |Form(form): Form>| { + let device = device.clone(); + device_requests.lock().unwrap().push(form); + async move { Json(device) } + })) + .route("/authorize", get(move |Query(form): Query>| { + assert_eq!(form["code_challenge_method"], "S256"); + let mut redirect = url::Url::parse(&form["redirect_uri"]).unwrap(); + redirect.query_pairs_mut().append_pair("code", "auth-code").append_pair("state", &form["state"]); + auth_requests.lock().unwrap().push(form); + async move { Redirect::to(redirect.as_str()) } + })) + .route("/token", post(move |headers: HeaderMap, Form(form): Form>| { + let mut requests = token_requests.lock().unwrap(); + requests.push(form.clone()); + let number = requests.iter().filter(|request| request.contains_key("grant_type")).count(); + async move { + if form.get("grant_type").is_some_and(|grant| grant == "client_credentials") + && headers.get("authorization").and_then(|value| value.to_str().ok()) + != Some(format!("Basic {}", base64::engine::general_purpose::STANDARD.encode("cli-client:test-secret")).as_str()) { + return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({ + "error": "invalid_client", "error_description": "private-token test-secret invalid-secret" + }))); + } + (StatusCode::OK, Json(serde_json::json!({ + "access_token": format!("token-{number}"), "token_type": "Bearer", "expires_in": lifetime, + "refresh_token": "private-refresh-token", + }))) + } + })); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + Self { + config, + requests, + server, + dir, + } + } + + fn managed(&self) -> ManagedOidc { + ManagedOidc::new(self.config.clone(), self.dir.path().join("cache")).unwrap() + } + + fn assert_targets(&self) { + for request in self.requests.lock().unwrap().iter() { + assert_eq!(request.get("resource"), self.config.resource.as_ref()); + assert_eq!(request.get("audience"), self.config.audience.as_ref()); + } + } + + async fn child(&self, action: &str) -> std::process::Output { + let executable = std::env::current_exe().unwrap(); + let mut command = tokio::process::Command::new(&executable); + command + .args([ + "--exact", + "auth::tests::session_process_helper", + "--nocapture", + ]) + .env("LANCEDB_TEST_AUTH_ACTION", action) + .env( + "LANCEDB_TEST_AUTH_CONFIG", + serde_json::to_string(&self.config).unwrap(), + ) + .env("LANCEDB_TEST_AUTH_CACHE", self.dir.path().join("cache")) + .env_remove(CLIENT_SECRET_ENV); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let browser = self.dir.path().join("browser"); + fs::write(&browser, "#!/bin/sh\nLANCEDB_TEST_BROWSER_URL=\"$1\" exec \"$LANCEDB_TEST_AUTH_EXE\" --exact auth::tests::browser_process_helper --nocapture\n").unwrap(); + fs::set_permissions(&browser, fs::Permissions::from_mode(0o700)).unwrap(); + command + .env("LANCEDB_OAUTH_BROWSER", browser) + .env("LANCEDB_TEST_AUTH_EXE", executable); + } + let output = command.output().await.unwrap(); + assert!( + output.status.success(), + "stdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let output_text = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!(!output_text.contains("private-refresh-token")); + output + } +} + +#[tokio::test] +async fn sdk_provider_is_shared_and_renews_service_tokens_in_memory() { + let fixture = Provider::start(OidcFlow::ClientCredentials, 1).await; + let authentication = Authentication::ManagedOidc(Arc::new(fixture.managed())); + let cloned = authentication.clone(); + let (first, second) = tokio::join!(authentication.headers(), cloned.headers()); + assert_eq!(first.unwrap()["authorization"], "Bearer token-1"); + assert_eq!(second.unwrap()["authorization"], "Bearer token-1"); + assert_eq!(fixture.requests.lock().unwrap().len(), 1); + tokio::time::sleep(Duration::from_millis(1100)).await; + let headers = authentication.headers().await.unwrap(); + assert_eq!(headers["authorization"], "Bearer token-2"); + assert_eq!(headers[OIDC_CREDENTIAL_HEADER], "oidc"); + assert!(headers["authorization"].is_sensitive()); + assert!(!format!("{headers:?}").contains("token-2")); + assert!(!fixture.dir.path().join("cache").exists()); + fixture.assert_targets(); +} + +#[tokio::test] +async fn sdk_provider_errors_do_not_expose_response_bodies() { + let fixture = Provider::start(OidcFlow::ClientCredentials, 3600).await; + fs::write( + fixture.config.client_secret_file.as_ref().unwrap(), + "invalid-secret", + ) + .unwrap(); + let error = fixture.managed().headers().await.unwrap_err(); + let rendered = format!("{error:#} {error:?}"); + assert!(rendered.contains("OIDC authentication failed")); + for secret in ["private-token", "test-secret", "invalid-secret"] { + assert!(!rendered.contains(secret)); + } +} + +#[tokio::test] +async fn missing_secret_does_not_fall_back() { + let fixture = Provider::start(OidcFlow::ClientCredentials, 3600).await; + fs::remove_file(fixture.config.client_secret_file.as_ref().unwrap()).unwrap(); + assert!(fixture.managed().headers().await.is_err()); + assert!(fixture.requests.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn sdk_provider_reads_updated_external_token_files() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("token"); + fs::write(&path, "first-token\n").unwrap(); + let provider = Authentication::OidcAccessTokenFile(path.clone()); + assert_eq!( + provider.get_headers().await.unwrap()["authorization"], + "Bearer first-token" + ); + fs::write(&path, "second-token\n").unwrap(); + assert_eq!( + provider.get_headers().await.unwrap()["authorization"], + "Bearer second-token" + ); + fs::write(&path, " \n").unwrap(); + assert!(provider.get_headers().await.is_err()); + fs::write(&path, "token\r\ninjected: header").unwrap(); + assert!(provider.get_headers().await.is_err()); +} + +#[tokio::test] +async fn profile_client_auth_method_round_trips_and_reaches_sdk() { + let profile = r#" +flow = "authorization_code" +issuer_url = "http://localhost:18888/realms/lancedb" +client_id = "cli-client" +scopes = ["openid"] +"#; + for (value, expected) in [ + (None, None), + (Some("none"), Some(ClientAuthMethod::None)), + ( + Some("client_secret_basic"), + Some(ClientAuthMethod::ClientSecretBasic), + ), + ( + Some("client_secret_post"), + Some(ClientAuthMethod::ClientSecretPost), + ), + ] { + let text = match value { + Some(value) => format!("{profile}\nclient_auth_method = {value:?}\n"), + None => profile.to_owned(), + }; + let config: OidcConfig = toml::from_str(&text).unwrap(); + let serialized = toml::to_string(&config).unwrap(); + assert_eq!(serialized.contains("client_auth_method"), value.is_some()); + assert_eq!(toml::from_str::(&serialized).unwrap(), config); + let dir = tempfile::tempdir().unwrap(); + let managed = ManagedOidc::new(config, dir.path().join("cache")).unwrap(); + assert_eq!( + managed.sdk_config().await.unwrap().client_auth_method, + expected + ); + } + assert!(toml::from_str::(&format!( + "{profile}\nclient_auth_method = \"unsupported\"\n" + )) + .is_err()); +} + +#[tokio::test] +async fn sdk_rejects_public_client_auth_with_a_secret_before_requesting_tokens() { + let mut fixture = Provider::start(OidcFlow::ClientCredentials, 3600).await; + fixture.config.client_auth_method = Some(OidcClientAuthMethod::None); + assert!(fixture.managed().provider().await.is_err()); + assert!(fixture.requests.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn sdk_config_preserves_profile_options() { + let mut fixture = Provider::start(OidcFlow::AuthorizationCode, 3600).await; + fixture.config.callback_port = Some(9123); + fixture.config.redirect_uri = Some("http://127.0.0.1:9123/cli".into()); + let config = fixture.managed().sdk_config().await.unwrap(); + assert_eq!(config.resource, fixture.config.resource); + assert_eq!(config.audience, fixture.config.audience); + assert_eq!(config.scopes, fixture.config.scopes); + assert_eq!(config.refresh_buffer_secs, Some(0)); + assert_eq!( + config.token_cache.unwrap().cache_dir, + Some(fixture.dir.path().join("cache")) + ); + let OAuthFlow::AuthorizationCode(options) = config.flow else { + panic!("expected browser flow") + }; + assert!(options.use_pkce); + assert_eq!(options.callback_port, Some(9123)); + assert_eq!(options.redirect_uri, fixture.config.redirect_uri); + fixture.config.flow = OidcFlow::DeviceCode; + assert!(ManagedOidc::new(fixture.config.clone(), fixture.dir.path().join("cache")).is_err()); +} + +#[tokio::test] +async fn profile_caches_are_isolated_without_creating_directories() { + let fixture = Provider::start(OidcFlow::DeviceCode, 3600).await; + let first = ManagedOidc::for_profile("a/../b", fixture.config.clone()).unwrap(); + let second = ManagedOidc::for_profile("b", fixture.config.clone()).unwrap(); + assert_ne!(first.cache_dir, second.cache_dir); + assert_eq!(first.cache_dir.parent(), second.cache_dir.parent()); + assert_eq!(first.cache_dir.file_name().unwrap().len(), 64); +} + +#[cfg(unix)] +#[tokio::test] +async fn sdk_interactive_sessions_survive_processes_and_logout() { + for flow in [OidcFlow::AuthorizationCode, OidcFlow::DeviceCode] { + let mut fixture = Provider::start(flow, 3600).await; + if fixture.config.flow == OidcFlow::AuthorizationCode { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + fixture.config.callback_port = Some(listener.local_addr().unwrap().port()); + } + // Ordinary requests trigger acquisition, without an explicit login first. + fixture.child("fetch").await; + let original_requests = fixture.requests.lock().unwrap().len(); + fixture.child("fetch").await; + { + let requests = fixture.requests.lock().unwrap(); + assert_eq!(requests.len(), original_requests + 1); + assert_eq!(requests.last().unwrap()["grant_type"], "refresh_token"); + } + fixture.child("status").await; + fixture.child("logout").await; + assert!( + !fixture + .managed() + .session() + .await + .unwrap() + .status() + .await + .unwrap() + .refreshable + ); + fixture.child("login").await; + fixture.child("status").await; + fixture.assert_targets(); + } +} + +#[tokio::test] +async fn session_process_helper() { + let Ok(action) = std::env::var("LANCEDB_TEST_AUTH_ACTION") else { + return; + }; + let config = serde_json::from_str(&std::env::var("LANCEDB_TEST_AUTH_CONFIG").unwrap()).unwrap(); + let managed = ManagedOidc::new( + config, + std::env::var_os("LANCEDB_TEST_AUTH_CACHE").unwrap().into(), + ) + .unwrap(); + match action.as_str() { + "fetch" => { + managed.headers().await.unwrap(); + } + "login" => { + assert!( + managed + .session() + .await + .unwrap() + .login() + .await + .unwrap() + .refreshable + ); + } + "status" => { + assert!( + managed + .session() + .await + .unwrap() + .status() + .await + .unwrap() + .refreshable + ); + } + "logout" => { + assert!( + managed + .session() + .await + .unwrap() + .logout() + .await + .unwrap() + .removed + ); + } + _ => panic!("unknown action"), + } +} + +#[tokio::test] +async fn browser_process_helper() { + let Ok(url) = std::env::var("LANCEDB_TEST_BROWSER_URL") else { + return; + }; + reqwest::Client::new() + .get(url) + .send() + .await + .unwrap() + .error_for_status() + .unwrap(); +} diff --git a/rust/lancedb/cli/src/cli.rs b/rust/lancedb/cli/src/cli.rs new file mode 100644 index 000000000..aa2b4c5d4 --- /dev/null +++ b/rust/lancedb/cli/src/cli.rs @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use crate::server_config::{ConnectionArgs, ResolvedConnection}; +use anyhow::{bail, Context, Result}; +use clap::{CommandFactory, Parser, Subcommand}; + +/// Public client commands. Runtime and administrative commands live in Enterprise. +#[derive(Parser, Debug)] +#[command( + name = "lancedb", + version, + about = "LanceDB command-line client", + args_conflicts_with_subcommands = true +)] +pub struct Args { + #[command(subcommand)] + pub command: Option, + /// SQL options used when no subcommand is given. These are local to the + /// default SQL invocation, so other subcommands use their own options. + #[command(flatten)] + pub sql: SqlArgs, +} + +#[derive(Subcommand, Debug)] +pub enum Commands { + /// Manage OAuth login and cached interactive sessions + Auth(crate::auth::AuthArgs), + /// Manage connection profiles + Profile(crate::profile::ProfileArgs), + /// Run SQL or open an interactive shell against a remote server + Sql(SqlArgs), +} + +#[derive(clap::Args, Debug)] +pub struct SqlArgs { + #[command(flatten)] + pub connection: ConnectionArgs, + /// Execute SQL and exit + #[arg(short = 'c', long = "command", conflicts_with = "file")] + pub command_string: Option, + /// Execute SQL commands from a file and exit + #[arg(short = 'f', long)] + pub file: Option, + /// Output format: table, csv, json, ndjson + #[arg(long, default_value = "table")] + pub format: String, +} + +const SQL_ENDPOINT_HELP: &str = "No Flight SQL endpoint is configured. Use --sql-server-url, \ + select a profile with sql_server_url, or use --profile local for localhost."; + +pub async fn run_sql(args: SqlArgs) -> Result<()> { + let connection = args.connection.resolve_sql()?.context(SQL_ENDPOINT_HELP)?; + run_sql_with_connection(args, connection).await +} + +async fn run_sql_with_connection(args: SqlArgs, connection: ResolvedConnection) -> Result<()> { + if let Some(file) = args.file { + crate::client::run_client_script_with_writer( + &connection, + std::fs::read_to_string(file)?, + args.format, + None, + ) + .await + } else if let Some(sql) = args.command_string { + crate::client::run_client_command_with_writer(&connection, sql, args.format, None).await + } else { + crate::client::run_client_with_writer(&connection, None).await + } +} + +pub async fn run(args: Args) -> Result<()> { + match args.command { + None => match args.sql.connection.resolve_sql()? { + Some(connection) => run_sql_with_connection(args.sql, connection).await, + None if args.sql.command_string.is_none() + && args.sql.file.is_none() + && args.sql.connection.profile.is_none() => + { + println!("{SQL_ENDPOINT_HELP}\n"); + Args::command().print_help()?; + println!(); + Ok(()) + } + None => bail!(SQL_ENDPOINT_HELP), + }, + Some(Commands::Auth(args)) => crate::auth::run(args, None).await, + Some(Commands::Profile(args)) => crate::profile::run_profile_command(args).await, + Some(Commands::Sql(args)) => run_sql(args).await, + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn sql_is_the_default_command() { + let args = Args::try_parse_from(["lancedb"]).unwrap(); + assert!(args.command.is_none()); + assert_eq!(args.sql.format, "table"); + assert!(args.sql.command_string.is_none()); + assert!(args.sql.file.is_none()); + assert!(matches!( + Args::try_parse_from(["lancedb", "sql"]).unwrap().command, + Some(Commands::Sql(_)) + )); + let args = Args::try_parse_from([ + "lancedb", + "--profile", + "production", + "--command", + "SELECT 1", + "--format", + "json", + ]) + .unwrap(); + assert!(args.command.is_none()); + assert_eq!(args.sql.connection.profile.as_deref(), Some("production")); + assert_eq!(args.sql.command_string.as_deref(), Some("SELECT 1")); + assert_eq!(args.sql.format, "json"); + let args = Args::try_parse_from(["lancedb", "--file", "queries.sql"]).unwrap(); + assert_eq!(args.sql.file.as_deref(), Some("queries.sql")); + } + + #[test] + fn default_sql_options_do_not_apply_to_subcommands() { + for args in [ + vec!["lancedb", "--format", "json", "profile", "list"], + vec!["lancedb", "--profile", "production", "profile", "list"], + vec!["lancedb", "--command", "SELECT 1", "profile", "list"], + vec!["lancedb", "profile", "list", "--command", "SELECT 1"], + vec!["lancedb", "profile", "list", "--file", "queries.sql"], + vec!["lancedb", "-c", "SELECT 1", "-f", "query.sql"], + vec!["lancedb", "sql", "-c", "SELECT 1", "-f", "query.sql"], + ] { + assert!(Args::try_parse_from(&args).is_err(), "{args:?}"); + } + assert!(Args::try_parse_from(["lancedb", "profile", "list"]).is_ok()); + } + + #[test] + fn excluded_commands_are_rejected() { + for command in [ + "server", + "admin", + "bench", + "service", + "pe", + "agent", + "management", + "preflight", + "run", + "function-worker", + "job", + "acl", + "load", + ] { + assert!( + Args::try_parse_from(["lancedb", command]).is_err(), + "{command}" + ); + } + } +} diff --git a/rust/lancedb/cli/src/client.rs b/rust/lancedb/cli/src/client.rs new file mode 100644 index 000000000..34035f3c1 --- /dev/null +++ b/rust/lancedb/cli/src/client.rs @@ -0,0 +1,2110 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use crate::formatter::{OutputFormat, QueryResult, ResultFormatter}; +use crate::server_config::{ + parse_endpoint, parse_grpc_endpoint, Authentication, ResolvedConnection, DEFAULT_HTTP_PORT, + DEFAULT_SQL_PORT, +}; +use crate::sql_executor::SdkSqlExecutor; +use crate::sql_executor::{SqlQueryExecutor, SqlResult}; +use anyhow::{anyhow, Context, Result}; +use arrow_schema::Schema; +use directories::ProjectDirs; +use futures::TryStreamExt; +use lancedb::listing::ListingOptions; +use rustyline::completion::{Completer, Pair}; +use rustyline::error::ReadlineError; +use rustyline::highlight::Highlighter; +use rustyline::hint::Hinter; +use rustyline::validate::Validator; +use rustyline::{Editor, Helper}; +use sqlparser::dialect::{Dialect, GenericDialect}; +use sqlparser::tokenizer::{Location, Token, Tokenizer}; +use std::io::{self, Write}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tempfile::NamedTempFile; +use tokio::signal; + +const LANCEDB_ASCII_ART: &str = r#" _ ____ ____ +| | __ _ _ __ ___ ___| _ \| __ ) +| | / _` | '_ \ / __/ _ \ | | | _ \ +| |__| (_| | | | | (_| __/ |_| | |_) | +|_____\__,_|_| |_|\___\___|____/|____/ + "#; + +/// Information about a database table +#[derive(Debug, Clone)] +pub struct TableInfo { + pub name: String, + pub schema: Arc, + pub row_count: Option, + pub size_bytes: Option, + pub num_indices: Option, + pub num_fragments: Option, +} + +/// Information about an index +#[derive(Debug, Clone, serde::Serialize)] +pub struct IndexInfo { + pub name: String, + pub table_name: String, + pub index_type: String, + pub columns: Vec, +} + +/// Statistics about an index +#[derive(Debug, Clone)] +pub struct IndexStats { + pub num_indexed_rows: u64, + pub num_unindexed_rows: u64, + pub distance_type: Option, +} + +/// Result of executing a metacommand +enum MetaCommandResult { + /// Command was handled normally, continue REPL loop + Handled, + /// Replace the current input line with new content (for \e) + ReplaceInput(String), +} + +/// The main client structure using the new architecture +pub struct LanceDBClient { + editor: Editor, + history_path: PathBuf, + sql_executor: S, + sql_connected: bool, + connection: Option>, + formatter: ResultFormatter, + current_database: Option, + connection_info: Option, + interactive_mode: bool, + authentication: Authentication, + last_query: Option, + /// The last re-runnable command (a SQL query or a `\d*` listing + /// metacommand), used by `\watch`. Excludes `\watch` itself so it can't + /// recurse, and one-shot commands like `\c`/`\e`/`\q`. + last_command: Option, + profile_name: String, +} + +#[derive(Clone)] +struct LanceDBCompleter { + table_names: Arc>>, + index_names: Arc>>, + qualified_index_names: Arc>>, +} + +impl LanceDBCompleter { + fn new() -> Self { + Self { + table_names: Arc::new(std::sync::Mutex::new(Vec::new())), + index_names: Arc::new(std::sync::Mutex::new(Vec::new())), + qualified_index_names: Arc::new(std::sync::Mutex::new(Vec::new())), + } + } + + fn update_table_names(&mut self, tables: Vec) { + if let Ok(mut names) = self.table_names.lock() { + *names = tables; + } + } + + fn update_index_names(&mut self, indices: Vec, qualified: Vec) { + if let Ok(mut names) = self.index_names.lock() { + *names = indices; + } + if let Ok(mut names) = self.qualified_index_names.lock() { + *names = qualified; + } + } +} + +impl Completer for LanceDBCompleter { + type Candidate = Pair; + + fn complete( + &self, + line: &str, + pos: usize, + _ctx: &rustyline::Context<'_>, + ) -> rustyline::Result<(usize, Vec)> { + let mut candidates = Vec::new(); + let trimmed = line[..pos].trim_start(); + + // For \di commands, only complete index names (including qualified table.index) + if trimmed.starts_with("\\di+ ") || trimmed.starts_with("\\di ") { + let word_start = line[..pos] + .rfind(|c: char| c.is_whitespace()) + .map(|i| i + 1) + .unwrap_or(0); + let partial = &line[word_start..pos]; + let partial_lower = partial.to_lowercase(); + + // Offer both unqualified and qualified index names + if let Ok(indices) = self.index_names.lock() { + for index in indices.iter() { + if index.to_lowercase().starts_with(&partial_lower) { + candidates.push(Pair { + display: index.clone(), + replacement: index.clone(), + }); + } + } + } + if let Ok(qualified) = self.qualified_index_names.lock() { + for name in qualified.iter() { + if name.to_lowercase().starts_with(&partial_lower) { + candidates.push(Pair { + display: name.clone(), + replacement: name.clone(), + }); + } + } + } + return Ok((word_start, candidates)); + } + + // SQL keywords + let keywords = vec![ + "SELECT", "FROM", "WHERE", "INSERT", "INTO", "VALUES", "UPDATE", "DELETE", "CREATE", + "TABLE", "DROP", "ALTER", "INDEX", "ON", "SHOW", "TABLES", "DESCRIBE", "DESC", "LIMIT", + "ORDER", "BY", "GROUP", "HAVING", "AS", "JOIN", "INNER", "LEFT", "RIGHT", "OUTER", + "AND", "OR", "NOT", "IN", "LIKE", "BETWEEN", "EXISTS", "CASE", "WHEN", "THEN", "ELSE", + "END", + ]; + + // Find the word being completed + let word_start = line[..pos] + .rfind(|c: char| c.is_whitespace() || "(),;".contains(c)) + .map(|i| i + 1) + .unwrap_or(0); + + let partial = &line[word_start..pos]; + let partial_upper = partial.to_uppercase(); + + // Add SQL keywords + for keyword in keywords { + if keyword.starts_with(&partial_upper) { + candidates.push(Pair { + display: keyword.to_string(), + replacement: keyword.to_string(), + }); + } + } + + // Add table names + if let Ok(tables) = self.table_names.lock() { + for table in tables.iter() { + if table.to_lowercase().starts_with(&partial.to_lowercase()) { + candidates.push(Pair { + display: table.clone(), + replacement: table.clone(), + }); + } + } + } + + // Add index names + if let Ok(indices) = self.index_names.lock() { + for index in indices.iter() { + if index.to_lowercase().starts_with(&partial.to_lowercase()) { + candidates.push(Pair { + display: index.clone(), + replacement: index.clone(), + }); + } + } + } + + Ok((word_start, candidates)) + } +} + +impl Hinter for LanceDBCompleter { + type Hint = String; + + fn hint(&self, _line: &str, _pos: usize, _ctx: &rustyline::Context<'_>) -> Option { + None + } +} + +impl Highlighter for LanceDBCompleter {} +impl Validator for LanceDBCompleter {} +impl Helper for LanceDBCompleter {} + +/// Unwrap one of a listing's per-table requests, reporting failure instead of +/// degrading silently. +/// +/// The `\d`-family listings issue several requests per table and render a blank +/// cell for each one that fails, which reads as "this table has no stats" +/// rather than "this request failed". The error carries the request ID the +/// query node logged, so this warning is what makes such a failure traceable. +fn or_warn(result: std::result::Result, subject: &str) -> Option { + match result { + Ok(value) => Some(value), + Err(e) => { + eprintln!("warning: {subject} failed: {e}"); + None + } + } +} + +/// Point `executor` at the Flight SQL address `sql_addr`, preserving its +/// scheme so an `https://`/`grpcs://` address dials TLS. Returns the URL that +/// was dialed along with any connection error, so the caller can report both +/// endpoint failures together. +/// +/// Split out of `connect_internal` so the address-to-transport handoff is +/// reachable without a live REST endpoint. +async fn connect_sql_endpoint( + executor: &mut S, + sql_addr: &str, + database: &str, +) -> Result<(String, Option)> { + let url = parse_grpc_endpoint(sql_addr, DEFAULT_SQL_PORT)?.url(); + executor.set_database(database.to_string()); + let err = executor.connect(&url).await.err(); + Ok((url, err)) +} + +fn connection_failure_message(endpoint: &str, protocol: &str, error: &anyhow::Error) -> String { + // Include the source chain: transport errors often hide the useful cause + // (connection refused, DNS, TLS, etc.) behind a generic outer message. + format!("lancedb: connection failed: {endpoint} ({protocol}): {error:#}") +} + +/// HTTP failures are fatal; SQL-only failures allow metadata commands. +fn report_connection_failures( + sql: Option<(&str, &anyhow::Error)>, + http: Option<(&str, &anyhow::Error)>, +) { + for (protocol, failure) in [("sql", sql), ("http", http)] { + if let Some((endpoint, error)) = failure { + eprintln!("{}", connection_failure_message(endpoint, protocol, error)); + } + } + + if sql.is_none() && http.is_none() { + return; + } + + if http.is_some() { + std::process::exit(1); + } + + eprintln!("lancedb: SQL queries will not work, but metadata commands are available"); +} + +// Helper function to run async operations with Ctrl+C cancellation +async fn run_with_cancellation(operation: F) -> Result> +where + F: std::future::Future>, +{ + tokio::select! { + result = operation => { + match result { + Ok(value) => Ok(Some(value)), + Err(e) => Err(e), + } + } + _ = signal::ctrl_c() => { + println!("\n^C"); + Ok(None) + } + } +} + +/// Default interval for `\watch` when none is given (matches psql). +const DEFAULT_WATCH_INTERVAL_SECS: f64 = 2.0; + +/// Smallest accepted `\watch` interval. A positive-but-tiny value (e.g. +/// `1e-20`, or `1e-6` which converts to a nonzero 1us) passes a bare `> 0.0` +/// check yet leaves effectively no delay between runs, spinning the loop and +/// hammering the server; anything below this floor is rejected. +const MIN_WATCH_INTERVAL_SECS: f64 = 0.1; + +/// Whether a metacommand is something `\watch` should repeat. The `\d*` +/// listing/describe family (`\d`, `\di`, `\dt`, ...) qualifies; `\watch` +/// itself and one-shot commands (`\c`, `\e`, `\q`, `\?`) do not. +fn is_watchable_metacommand(cmd: &str) -> bool { + // Exact-match the recognized `\d`-family verbs, not just a `\d` prefix: + // an unrecognized `\d`-prefixed typo (`\dfoo`) is rejected by + // `handle_metacommand` yet would otherwise clobber `last_command`. + // Only the first token matters, so `\d TABLE` / `\di INDEX` still match. + matches!( + cmd.split_whitespace().next(), + Some("\\d" | "\\d+" | "\\dt" | "\\dt+" | "\\di" | "\\di+" | "\\dj" | "\\dj+") + ) +} + +/// The `SHOW JOBS` statement behind `\dj [TABLE]`. The argument is a literal +/// table name, so it is quoted: a name need not be a bare SQL identifier. +fn show_jobs_statement(table: Option<&str>) -> String { + match table { + Some(table) => format!("SHOW JOBS FOR \"{}\"", table.replace('"', "\"\"")), + None => "SHOW JOBS".to_string(), + } +} + +/// Validate a `\watch` interval in seconds to a `Duration`, or `None` if it is +/// unusable. `try_from_secs_f64` rejects negative, NaN, non-finite ("inf"), and +/// `Duration`-overflowing ("1e300") inputs (so the sleep can't panic); the floor +/// then rejects zero and positive-but-tiny values that would leave no real delay +/// between runs. See [`MIN_WATCH_INTERVAL_SECS`]. +fn watch_interval(secs: f64) -> Option { + let min = Duration::from_secs_f64(MIN_WATCH_INTERVAL_SECS); + Duration::try_from_secs_f64(secs).ok().filter(|d| *d >= min) +} + +/// Parsed `\watch` arguments: how often to repeat, and what to repeat. +struct WatchArgs { + interval: Duration, + /// Inline statement/listing to watch, or `None` to re-run the last command. + target: Option, +} + +/// Parse the argument string after `\watch` into an interval and an optional +/// inline target. A first token that parses as a number is always treated as +/// the interval (real SQL never starts with a bare number), so it is validated +/// as one; anything else means the whole string is the inline target. Thus +/// `\watch` / `\watch 5` re-run the last command, while `\watch SELECT ...` and +/// `\watch 5 SELECT ...` watch that statement (at the default / given interval). +fn parse_watch_args(args: &str) -> Result { + let args = args.trim(); + let default = Duration::from_secs_f64(DEFAULT_WATCH_INTERVAL_SECS); + if args.is_empty() { + return Ok(WatchArgs { + interval: default, + target: None, + }); + } + + let mut it = args.splitn(2, char::is_whitespace); + let first = it.next().unwrap_or(""); + let rest = it.next().unwrap_or("").trim(); + + if let Ok(secs) = first.parse::() { + let interval = watch_interval(secs).ok_or_else(|| { + format!( + "Invalid interval '{first}' (must be a number >= {MIN_WATCH_INTERVAL_SECS}s). \ + Usage: \\watch [seconds] [statement]" + ) + })?; + return Ok(WatchArgs { + interval, + target: (!rest.is_empty()).then(|| rest.to_string()), + }); + } + + Ok(WatchArgs { + interval: default, + target: Some(args.to_string()), + }) +} + +/// Sets `NO_PAGER` for as long as it is alive, restoring the prior value on +/// drop. `should_use_pager` already honours `NO_PAGER`, so this disables +/// paging during a `\watch` loop. Restored even when the loop's future is +/// dropped by Ctrl-C, because the guard is a live local at the await point. +struct NoPagerGuard { + prev: Option, +} + +impl NoPagerGuard { + fn new() -> Self { + let prev = std::env::var("NO_PAGER").ok(); + std::env::set_var("NO_PAGER", "1"); + Self { prev } + } +} + +impl Drop for NoPagerGuard { + fn drop(&mut self) { + match &self.prev { + Some(v) => std::env::set_var("NO_PAGER", v), + None => std::env::remove_var("NO_PAGER"), + } + } +} + +/// Check if output should use a pager +fn should_use_pager(output: &str) -> bool { + if std::env::var("NO_PAGER").is_ok() { + return false; + } + + let term_height = termsize::get().map(|size| size.rows as usize).unwrap_or(24); + let line_count = output.lines().count(); + + line_count > (term_height * 80 / 100) +} + +/// Find an appropriate pager +fn find_pager() -> Option { + if let Ok(pager) = std::env::var("PAGER") { + if !pager.is_empty() { + return Some(pager); + } + } + + let pagers = ["less", "more", "bat"]; + for pager in &pagers { + if which::which(pager).is_ok() { + return Some(pager.to_string()); + } + } + + None +} + +/// Leading whitespace and comments, which the server's tokenizer discards +/// before matching a statement's keywords. +fn strip_leading_trivia(query: &str) -> &str { + let mut rest = query.trim_start(); + loop { + let remainder = if let Some(after) = rest.strip_prefix("--") { + after.find('\n').map_or("", |end| &after[end + 1..]) + } else if let Some(after) = rest.strip_prefix("/*") { + after.find("*/").map_or("", |end| &after[end + 2..]) + } else { + return rest; + }; + rest = remainder.trim_start(); + } +} + +/// Rows of a `SHOW JOBS` listing the interactive shell will print. The registry +/// can hold far more jobs than anyone reads at a terminal, and the server +/// returns the listing in one shot with no cursor to resume from, so the table +/// rendering cuts the display and points at ways to narrow the listing or +/// export every row. +const MAX_DISPLAYED_JOB_ROWS: usize = 1000; + +/// Ready a `SHOW JOBS` listing for display, returning it with any notice to +/// print after the formatted output. +/// +/// The `job_id` marking applies everywhere: it is the input to `CANCEL JOB`, +/// so it has to be copyable rather than readable. The row cut applies only to +/// the interactive table rendering -- CSV/JSON/NDJSON and one-shot invocations +/// are read by programs, which need every row and nothing but the payload. +fn prepare_show_jobs_result( + result: SqlResult, + interactive_table: bool, +) -> (SqlResult, Option) { + let total = crate::formatter::row_count(&result); + let cut = interactive_table && total > MAX_DISPLAYED_JOB_ROWS; + + let notice = cut.then(|| { + format!( + "\nShowing the first {MAX_DISPLAYED_JOB_ROWS} of {total} jobs. Narrow the \ + listing with SHOW JOBS FOR

, or use lancedb sql --command 'SHOW JOBS' \ + --format json to retrieve all rows.\n" + ) + }); + let result = if cut { + crate::formatter::take_rows(result, MAX_DISPLAYED_JOB_ROWS) + } else { + result + }; + ( + crate::formatter::mark_no_truncate(result, &["job_id"]), + notice, + ) +} + +/// The first two keywords of `query`, matched on leading keywords rather than +/// a raw prefix so that `SHOW JOBS` and a comment-prefixed query both match +/// while `SHOW JOBSX` does not. +fn leading_keywords(query: &str) -> Option<(String, String)> { + let mut words = strip_leading_trivia(query) + .trim_end_matches(|c: char| c.is_whitespace() || c == ';') + .split_whitespace(); + let first = words.next()?.to_ascii_uppercase(); + let second = words.next()?.to_ascii_uppercase(); + Some((first, second)) +} + +/// Whether `query` is a `SHOW JOBS` statement. +fn is_show_jobs(query: &str) -> bool { + leading_keywords(query).is_some_and(|(first, second)| first == "SHOW" && second == "JOBS") +} + +/// Columns of a statement's result that a reader copies rather than reads +/// (identifiers), which the table view must not abbreviate. +fn copyable_columns(query: &str) -> &'static [&'static str] { + match leading_keywords(query) { + Some((first, second)) if first == "CANCEL" && second == "JOB" => &["job_id"], + // A Function version is the argument of the next statement a reader + // writes, so it has to survive display in full. + Some((first, second)) if first == "SHOW" && second == "FUNCTIONS" => &["version"], + Some((first, second)) if first == "SHOW" && second == "ERRORS" => { + &["job_id", "function_version"] + } + Some((first, second)) + if first == "REFRESH" && (second == "COLUMN" || second == "MATERIALIZED") => + { + &["job_id"] + } + _ => &[], + } +} + +/// Display output with pager if needed +fn display_with_pager(output: &str, interactive_mode: bool) -> Result<()> { + if !interactive_mode || !should_use_pager(output) { + // Just print directly + print!("{}", output); + io::stdout().flush()?; + return Ok(()); + } + + // Find pager + let Some(pager_cmd) = find_pager() else { + // No pager available, just print + print!("{}", output); + io::stdout().flush()?; + return Ok(()); + }; + + // Set up pager process + let mut cmd = Command::new(&pager_cmd); + + // If using less, add -FRX flags: + // -F: quit if one screen + // -R: raw control chars (for colors) + // -X: no init (don't clear screen) + if pager_cmd.contains("less") { + cmd.arg("-FRX"); + } + + cmd.stdin(Stdio::piped()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()); + + // Spawn pager + let mut child = cmd.spawn()?; + + // Write output to pager + if let Some(mut stdin) = child.stdin.take() { + // Ignore SIGPIPE errors when pager exits early (e.g., user presses 'q') + let _ = stdin.write_all(output.as_bytes()); + let _ = stdin.flush(); + } + + // Wait for pager to finish + let _ = child.wait(); + + Ok(()) +} + +impl LanceDBClient +where + S: SqlQueryExecutor, +{ + fn prompt(&self) -> String { + match &self.current_database { + Some(db) => format!("[{}]:{}=# ", self.profile_name, db), + None => format!("[{}]:lancedb=# ", self.profile_name), + } + } + + fn continuation_prompt(&self) -> &'static str { + " # " + } + + fn open_editor_for_last_query(&self) -> Result> { + // Use last executed query if available, otherwise empty string + let initial_query = self.last_query.as_deref().unwrap_or(""); + self.open_editor_for_query(initial_query) + } + + fn display_query_lines(&self, query: &str) { + // Display each line of the query as if the user had typed it + for (i, line) in query.lines().enumerate() { + if i == 0 { + println!("{}{}", self.prompt(), line); + } else { + println!("{}{}", self.continuation_prompt(), line); + } + } + } + + fn open_editor_for_query(&self, initial_query: &str) -> Result> { + // Determine which editor to use + let editor = std::env::var("EDITOR") + .or_else(|_| std::env::var("VISUAL")) + .unwrap_or_else(|_| { + for editor in &["vim", "vi", "emacs", "nano", "code"] { + if which::which(editor).is_ok() { + return editor.to_string(); + } + } + "vi".to_string() + }); + + // Create a temporary file with .sql extension + let mut temp_file = NamedTempFile::with_suffix(".sql") + .map_err(|e| anyhow!("Failed to create temporary file: {}", e))?; + + // Write initial query to the file + temp_file + .write_all(initial_query.as_bytes()) + .map_err(|e| anyhow!("Failed to write to temporary file: {}", e))?; + temp_file + .flush() + .map_err(|e| anyhow!("Failed to flush temporary file: {}", e))?; + + // Get the path before we move ownership + let temp_path = temp_file.path().to_path_buf(); + + // Launch the editor + let status = Command::new(&editor) + .arg(&temp_path) + .stdin(Stdio::inherit()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .status() + .map_err(|e| anyhow!("Failed to launch editor '{}': {}", editor, e))?; + + if !status.success() { + // Editor exited with error, but we'll still try to read the file + eprintln!("Editor exited with non-zero status"); + } + + // Read the edited content + let edited_content = std::fs::read_to_string(&temp_path) + .map_err(|e| anyhow!("Failed to read edited file: {}", e))?; + + // Check if the content is empty or unchanged + let trimmed = edited_content.trim(); + if trimmed.is_empty() { + return Ok(None); + } + + Ok(Some(edited_content)) + } + + pub async fn new( + database_override: Option, + interactive_mode: bool, + output_format: OutputFormat, + authentication: Authentication, + profile_name: String, + sql_executor: S, + ) -> Result { + // Set up history file + let history_path = if let Some(proj_dirs) = ProjectDirs::from("com", "lancedb", "client") { + let data_dir = proj_dirs.data_dir(); + std::fs::create_dir_all(data_dir)?; + data_dir.join("history.txt") + } else { + PathBuf::from("/tmp/lancedb-history.txt") + }; + + // Create completer + let completer = LanceDBCompleter::new(); + + // Create editor with completer + let mut editor = Editor::with_config( + rustyline::config::Config::builder() + .completion_type(rustyline::config::CompletionType::List) + .build(), + ) + .map_err(|e| anyhow!("Failed to create editor: {}", e))?; + editor.set_helper(Some(completer)); + let _ = editor.load_history(&history_path); + + // Use database override, or system username as default database + let default_database = database_override.unwrap_or_else(|| { + std::env::var("USER") + .or_else(|_| std::env::var("USERNAME")) + .unwrap_or_else(|_| "test".to_string()) + }); + + let formatter = ResultFormatter::new(output_format); + + Ok(Self { + editor, + history_path, + sql_executor, + sql_connected: false, + connection: None, + formatter, + current_database: Some(default_database), + connection_info: None, + interactive_mode, + authentication, + last_query: None, + last_command: None, + profile_name, + }) + } + + pub async fn connect(&mut self, conn: &ResolvedConnection) -> Result<()> { + self.connect_internal(conn, true).await + } + + async fn connect_internal( + &mut self, + conn: &ResolvedConnection, + show_message: bool, + ) -> Result<()> { + let sql_addr = &conn.sql_server_url; + let http_addr = &conn.http_server_url; + + // The REST address keeps whichever scheme the user configured, so an + // https:// address stays on TLS all the way to the transport. + let lancedb_uri = parse_endpoint(http_addr, DEFAULT_HTTP_PORT)?.url(); + + // Build the database URI + let db_name = self.current_database.as_deref().unwrap_or("test"); + + // Try both connections and report failures together + let (flight_server, sql_err) = + connect_sql_endpoint(&mut self.sql_executor, sql_addr, db_name).await?; + + let db_uri = format!("db://{}", db_name); + + // lancedb::connect() is lazy, so we create the connection then probe it + // with a table_names call to verify the HTTP endpoint is reachable. + let mut builder = lancedb::connect(&db_uri) + .region("self-hosted") + .host_override(&lancedb_uri); + if let Authentication::ApiKey(api_key) = &self.authentication { + builder = builder.api_key(api_key); + } else { + // The SDK requires an explicit API key even with a header provider. + // An empty key omits x-api-key; client_config supplies the OIDC headers. + builder = builder.api_key(""); + } + if let Some(client_config) = crate::lancedb_client_config(&conn.tls, &self.authentication) { + builder = builder.client_config(client_config); + } + let connection = builder + .execute() + .await + .map_err(|e| anyhow!("Failed to connect to LanceDB: {}", e))?; + + let http_err = connection + .list_tables(&[], ListingOptions::default().page_limit(1)) + .next_page() + .await + .err() + .map(anyhow::Error::from); + + report_connection_failures( + sql_err.as_ref().map(|err| (flight_server.as_str(), err)), + http_err.as_ref().map(|err| (lancedb_uri.as_str(), err)), + ); + + self.connection = Some(Arc::new(connection)); + self.sql_connected = sql_err.is_none(); + self.connection_info = Some(conn.clone()); + + // Only print connection message in interactive mode and when requested + if self.interactive_mode && show_message { + println!("Connected to SQL: {}, HTTP: {}", sql_addr, http_addr); + } + + // Update table name completions + self.update_completions().await; + + Ok(()) + } + + /// Fetch all table names with pagination + async fn table_names(connection: &lancedb::Connection) -> Result> { + let mut all_tables: Vec = connection + .list_tables(&[], ListingOptions::default().page_limit(100)) + .try_collect() + .await + .map_err(|e| anyhow!("Failed to list tables: {}", e))?; + + // The listing resumes from the store's own cursor, so its pages arrive in key order + // rather than name order. Callers here -- `\d`, `\dt`, and completion -- present the + // whole list to a person, and this walk already holds it in memory, so sort it once. + all_tables.sort(); + + Ok(all_tables) + } + + async fn update_completions(&mut self) { + if let Some(connection) = &self.connection { + if let Ok(table_names) = Self::table_names(connection).await { + if let Some(helper) = self.editor.helper_mut() { + helper.update_table_names(table_names.clone()); + + // Also gather all index names (unqualified and qualified) + let mut all_index_names = Vec::new(); + let mut qualified_index_names = Vec::new(); + for table_name in &table_names { + if let Ok(table) = connection.open_table(table_name).execute().await { + if let Ok(indices) = table.list_indices().await { + for index in indices { + qualified_index_names + .push(format!("{}.{}", table_name, index.name)); + all_index_names.push(index.name); + } + } + } + } + helper.update_index_names(all_index_names, qualified_index_names); + } + } + } + } + + pub async fn run_repl(&mut self) -> Result<()> { + println!("{}", LANCEDB_ASCII_ART); + println!("LanceDB CLI v{}", crate::build_version()); + println!("Type \\? for help or \\q to quit\n"); + + let mut multiline_query = String::new(); + let mut in_multiline = false; + + loop { + let prompt_string; + let prompt = if in_multiline { + self.continuation_prompt() + } else { + prompt_string = self.prompt(); + &prompt_string + }; + + match self.editor.readline(prompt) { + Ok(mut line) => { + let trimmed = line.trim(); + + // Skip empty lines + if trimmed.is_empty() { + continue; + } + + // Handle metacommands + if !in_multiline && trimmed.starts_with('\\') { + match run_with_cancellation(self.handle_metacommand(trimmed)).await { + Err(e) => { + eprintln!("ERROR: {}", e); + continue; + } + Ok(None) => { + // Cancelled + continue; + } + Ok(Some(result)) => { + match result { + MetaCommandResult::Handled => { + // Successful metacommand + self.editor.add_history_entry(&line)?; + // Remember listing metacommands so + // \watch can repeat them. + if is_watchable_metacommand(trimmed) { + self.last_command = Some(trimmed.to_string()); + } + continue; + } + MetaCommandResult::ReplaceInput(new_input) => { + line = new_input; + self.display_query_lines(&line); + // Fall through to process the new input + } + } + } + } + } + + // Now process line normally (either from readline or editor) + let trimmed = line.trim(); + + // Skip empty lines (in case editor returned empty) + if trimmed.is_empty() { + continue; + } + + // Add to history + self.editor.add_history_entry(&line)?; + + // Normal query accumulation + if in_multiline { + multiline_query.push('\n'); + } + multiline_query.push_str(&line); + + // Check if query is complete (ends with semicolon) + if multiline_query.trim().ends_with(';') { + // Store the complete query with semicolon before removing it + self.last_query = Some(multiline_query.clone()); + + // Remove the semicolon + multiline_query.pop(); + // Remember the query so \watch can repeat it. + self.last_command = Some(multiline_query.clone()); + + // Execute the query + match run_with_cancellation(self.execute_query(&multiline_query)).await { + Ok(Some(())) => {} + Ok(None) => {} + Err(e) => { + eprintln!("ERROR: {}", e); + } + } + + // Reset for next query + multiline_query.clear(); + in_multiline = false; + } else { + in_multiline = true; + } + } + Err(ReadlineError::Interrupted) => { + println!("^C"); + multiline_query.clear(); + in_multiline = false; + } + Err(ReadlineError::Eof) => { + println!("\\q"); + break; + } + Err(err) => { + eprintln!("Error: {:?}", err); + break; + } + } + } + + // Save history + self.editor.save_history(&self.history_path)?; + Ok(()) + } + + async fn execute_query(&mut self, query: &str) -> Result<()> { + let start_time = Instant::now(); + + // Check if this is a DDL statement and get the command type + let ddl_command = { + let trimmed = query.trim().to_uppercase(); + if trimmed.starts_with("CREATE TABLE") { + Some("CREATE TABLE") + } else if trimmed.starts_with("CREATE INDEX") { + Some("CREATE INDEX") + } else if trimmed.starts_with("CREATE VIEW") { + Some("CREATE VIEW") + } else if trimmed.starts_with("CREATE") { + Some("CREATE") + } else if trimmed.starts_with("ALTER TABLE") { + Some("ALTER TABLE") + } else if trimmed.starts_with("ALTER INDEX") { + Some("ALTER INDEX") + } else if trimmed.starts_with("ALTER VIEW") { + Some("ALTER VIEW") + } else if trimmed.starts_with("ALTER") { + Some("ALTER") + } else if trimmed.starts_with("DROP TABLE") { + Some("DROP TABLE") + } else if trimmed.starts_with("DROP INDEX") { + Some("DROP INDEX") + } else if trimmed.starts_with("DROP VIEW") { + Some("DROP VIEW") + } else if trimmed.starts_with("DROP") { + Some("DROP") + } else { + None + } + }; + + if !self.sql_connected { + return Err(anyhow!("SQL endpoint is not connected")); + } + + // Execute the query + let result = self.sql_executor.execute_query(query).await?; + + // Display output based on whether it's DDL or not + if let Some(command) = ddl_command { + // For DDL, just echo the command type + println!("{}", command); + } else { + // For non-DDL, format and display the result. + let (result, notice) = if is_show_jobs(query) { + let interactive_table = self.interactive_mode + && matches!(self.formatter.output_format(), OutputFormat::Table); + prepare_show_jobs_result(result, interactive_table) + } else { + ( + crate::formatter::mark_no_truncate(result, copyable_columns(query)), + None, + ) + }; + let query_result = QueryResult::SqlResult(result); + let mut output = self.formatter.format(&query_result)?; + // Appended rather than printed ahead of the payload, so the notice + // travels through the pager with the table it describes. + if let Some(notice) = notice { + output.push_str(¬ice); + } + display_with_pager(&output, self.interactive_mode)?; + } + + let elapsed = start_time.elapsed(); + if self.interactive_mode { + println!("Time: {:.3} ms", elapsed.as_secs_f64() * 1000.0); + } + + Ok(()) + } + + async fn handle_metacommand(&mut self, command: &str) -> Result { + let parts: Vec<&str> = command.split_whitespace().collect(); + if parts.is_empty() { + return Ok(MetaCommandResult::Handled); + } + + let cmd = parts[0]; + match cmd { + "\\?" | "\\h" | "\\help" | "help" => { + self.print_help(); + } + "\\d" | "\\d+" => { + let detailed = cmd.ends_with('+'); + if parts.len() < 2 { + // \d without argument lists tables + self.list_tables(detailed).await?; + } else { + // \d
describes the table + self.describe_table(parts[1]).await?; + } + } + "\\di" | "\\di+" => { + let detailed = cmd.ends_with('+'); + if parts.len() < 2 { + // \di without argument lists all indexes + self.list_all_indexes(detailed).await?; + } else { + // \di describes the specific index + self.describe_index(parts[1], detailed).await?; + } + } + "\\dt" | "\\dt+" => { + let detailed = cmd.ends_with('+'); + self.list_tables(detailed).await?; + } + // `\dj+` is a synonym for now. + "\\dj" | "\\dj+" => { + let statement = show_jobs_statement(parts.get(1).copied()); + self.execute_query(&statement).await?; + } + "\\watch" => { + let args = command.strip_prefix("\\watch").unwrap_or(""); + let spec = match parse_watch_args(args) { + Ok(spec) => spec, + Err(msg) => { + eprintln!("{msg}"); + return Ok(MetaCommandResult::Handled); + } + }; + + // Resolve what to repeat: an inline statement/listing if given, + // otherwise the last command. An inline `\`-target must be a + // repeatable `\d`-family listing -- this also rejects `\watch + // \watch ...`, which would otherwise recurse. + let target = match spec.target { + Some(t) if t.starts_with('\\') => { + if !is_watchable_metacommand(&t) { + eprintln!( + "\\watch: cannot watch '{t}'. Watch a SQL query or a \\d-family listing." + ); + return Ok(MetaCommandResult::Handled); + } + t + } + // Drop a trailing ';' so inline SQL matches the re-run form. + Some(t) => t.trim_end_matches(';').trim_end().to_string(), + None => { + let Some(last) = self.last_command.clone() else { + eprintln!("\\watch: no previous query or listing to watch."); + return Ok(MetaCommandResult::Handled); + }; + last + } + }; + self.watch_loop(target, spec.interval).await?; + } + "\\c" => { + if parts.len() < 2 { + match &self.current_database { + Some(db) => println!("You are now connected to database \"{}\".", db), + None => println!("You are not connected to a database."), + } + } else { + let new_db = parts[1].to_string(); + + // Check if we're already connected to this database + if let Some(current_db) = &self.current_database { + if current_db == &new_db { + println!("You are now connected to database \"{}\".", new_db); + return Ok(MetaCommandResult::Handled); + } + } + + let old_db = self.current_database.clone(); + self.current_database = Some(new_db.clone()); + + // If we're connected, reconnect with the new database + if let Some(conn) = &self.connection_info.clone() { + match self.connect_internal(conn, false).await { + Ok(_) => { + println!("You are now connected to database \"{}\".", new_db); + } + Err(e) => { + eprintln!("connection to database \"{}\" failed: {}", new_db, e); + // Restore the previous database on failure + self.current_database = old_db; + } + } + } else { + println!("You are now connected to database \"{}\".", new_db); + } + } + } + "\\e" => { + // Open editor and return the edited query + match self.open_editor_for_last_query() { + Ok(Some(edited)) => { + return Ok(MetaCommandResult::ReplaceInput(edited.trim().to_string())); + } + Ok(None) => { + // User cancelled or cleared editor + return Ok(MetaCommandResult::Handled); + } + Err(e) => { + return Err(e); + } + } + } + "\\q" | "\\quit" => { + println!("Use Ctrl+D to exit"); + } + _ => { + eprintln!("Invalid command \\{}. Try \\? for help.", &cmd[1..]); + } + } + Ok(MetaCommandResult::Handled) + } + + /// Re-run `command` (a SQL query or a `\d*` listing) every `interval` + /// seconds, clearing the screen between runs, until interrupted with + /// Ctrl-C. The REPL wraps this in `run_with_cancellation`, so Ctrl-C + /// drops this future and returns to the prompt; `NoPagerGuard` restores + /// the pager setting on that drop. Paging is suppressed for the duration + /// so a long listing doesn't block the loop waiting on the pager. + async fn watch_loop(&mut self, command: String, interval: Duration) -> Result<()> { + let _no_pager = NoPagerGuard::new(); + loop { + // Clear screen, cursor home, then a header line. + print!("\x1b[2J\x1b[H"); + println!( + "Watch every {:.1}s -- {} (Ctrl-C to stop)\n", + interval.as_secs_f64(), + command + ); + let _ = io::stdout().flush(); + + let result = if command.starts_with('\\') { + // Recursion (handle_metacommand -> watch_loop -> + // handle_metacommand) needs boxing to keep the future sized. + Box::pin(self.handle_metacommand(&command)) + .await + .map(|_| ()) + } else { + Box::pin(self.execute_query(&command)).await + }; + if let Err(e) = result { + eprintln!("ERROR: {}", e); + } + let _ = io::stdout().flush(); + + tokio::time::sleep(interval).await; + } + } + + fn print_help(&self) { + println!("\nGeneral"); + println!(" \\h, \\?, help show this help"); + println!(" \\q quit lancedb (or use Ctrl+D)"); + println!("\nEditing"); + println!(" \\e edit query buffer in external editor"); + println!("\nInformational"); + println!(" \\d list tables (simple)"); + println!(" \\d+ list tables with stats (detailed)"); + println!(" \\d TABLE describe table (show columns and indexes)"); + println!(" \\di list all indexes (simple)"); + println!(" \\di+ list all indexes with stats (detailed)"); + println!(" \\di [TABLE.]INDEX describe index"); + println!(" \\dt list tables (simple)"); + println!(" \\dt+ list tables with stats (detailed)"); + println!(" \\dj [TABLE] list jobs, optionally only those for TABLE"); + println!(" \\dj+ [TABLE] same as \\dj"); + println!("\nRepeat"); + println!(" \\watch [SEC] re-run the last query or listing every SEC seconds"); + println!( + " \\watch [SEC] STMT watch STMT (a SQL query or \\d-family listing) instead" + ); + println!(" (default 2s; Ctrl-C to stop)"); + println!("\nConnection"); + println!(" \\c [DBNAME] connect to database"); + println!("\nSQL"); + println!(" SQL queries end with semicolon (;)"); + println!(" Use Ctrl+C to cancel current input"); + println!(" Use Ctrl+D to exit"); + println!("\nOutput"); + println!(" Large results are automatically displayed in pager"); + println!(" Set NO_PAGER=1 to disable pager"); + println!(); + } + + async fn list_tables(&mut self, detailed: bool) -> Result<()> { + let connection = self + .connection + .as_ref() + .ok_or_else(|| anyhow!("Not connected to LanceDB"))?; + + let tables = Self::table_names(connection).await?; + + if tables.is_empty() { + println!("Did not find any relations."); + return Ok(()); + } + + if detailed { + // For \d+ and \dt+, we need to show detailed table information with stats + // Fetch table info for each table + let mut table_infos = Vec::new(); + for table_name in &tables { + let Some(table) = or_warn( + connection.open_table(table_name).execute().await, + &format!("opening table '{table_name}'"), + ) else { + table_infos.push(TableInfo { + name: table_name.clone(), + schema: Arc::new(Schema::empty()), + row_count: None, + size_bytes: None, + num_indices: None, + num_fragments: None, + }); + continue; + }; + + let schema = or_warn( + table.schema().await, + &format!("reading schema for table '{table_name}'"), + ) + .unwrap_or_else(|| Arc::new(Schema::empty())); + let stats = or_warn( + table.stats().await, + &format!("reading stats for table '{table_name}'"), + ); + let row_count = match stats.as_ref() { + Some(s) => Some(s.num_rows as u64), + None => or_warn( + table.count_rows(None).await, + &format!("counting rows for table '{table_name}'"), + ) + .map(|n| n as u64), + }; + + table_infos.push(TableInfo { + name: table_name.clone(), + schema, + row_count, + size_bytes: stats.as_ref().map(|s| s.total_bytes as u64), + num_indices: stats.as_ref().map(|s| s.num_indices as u64), + num_fragments: stats + .as_ref() + .map(|s| s.fragment_stats.num_fragments as u64), + }); + } + + // Use the formatter to display the results + let result = QueryResult::TableListDetailed(table_infos); + let output = self.formatter.format(&result)?; + display_with_pager(&output, self.interactive_mode)?; + } else { + // Simple list without stats + let result = QueryResult::TableList(tables); + let output = self.formatter.format(&result)?; + display_with_pager(&output, self.interactive_mode)?; + } + Ok(()) + } + + async fn describe_table(&mut self, table_name: &str) -> Result<()> { + let connection = self + .connection + .as_ref() + .ok_or_else(|| anyhow!("Not connected to LanceDB"))?; + + let table = connection + .open_table(table_name) + .execute() + .await + .map_err(|e| anyhow!("Failed to open table '{}': {}", table_name, e))?; + + let schema = table + .schema() + .await + .map_err(|e| anyhow!("Failed to get schema: {}", e))?; + + let stats = table.stats().await.ok(); + let row_count = if let Some(s) = stats.as_ref() { + Some(s.num_rows as u64) + } else { + table.count_rows(None).await.ok().map(|n| n as u64) + }; + + // Get index information + let indices = table.list_indices().await.ok(); + let mut index_info = Vec::new(); + if let Some(indices) = indices { + for index in indices { + let mut info = IndexInfo { + name: index.name.clone(), + table_name: table_name.to_string(), + index_type: index.index_type.to_string(), + columns: index.columns.clone(), + }; + + // Try to get distance type for vector indices + if let Ok(Some(stats)) = table.index_stats(&index.name).await { + if let Some(distance_type) = stats.distance_type { + info.index_type = + format!("{} distance={}", index.index_type, distance_type); + } + } + + index_info.push(info); + } + } + + let table_info = TableInfo { + name: table_name.to_string(), + schema, + row_count, + size_bytes: stats.as_ref().map(|s| s.total_bytes as u64), + num_indices: stats.as_ref().map(|s| s.num_indices as u64), + num_fragments: stats + .as_ref() + .map(|s| s.fragment_stats.num_fragments as u64), + }; + + let result = QueryResult::TableInfoWithIndices(table_info, index_info); + let output = self.formatter.format(&result)?; + display_with_pager(&output, self.interactive_mode)?; + Ok(()) + } + + async fn list_all_indexes(&mut self, detailed: bool) -> Result<()> { + let connection = self + .connection + .as_ref() + .ok_or_else(|| anyhow!("Not connected to LanceDB"))?; + + let tables = Self::table_names(connection).await?; + + // Each opened table is kept alongside its indexes because the `\di+` + // pass below needs the same handle: reopening per index would issue one + // request per index where one per table suffices. + let mut per_table = Vec::new(); + for table_name in tables { + // A failure here drops the table from the listing entirely, so it + // has to be reported: an incomplete index list is indistinguishable + // from a table that genuinely has no indexes. + let Some(table) = or_warn( + connection.open_table(&table_name).execute().await, + &format!("opening table '{table_name}'"), + ) else { + continue; + }; + let Some(indices) = or_warn( + table.list_indices().await, + &format!("listing indexes for table '{table_name}'"), + ) else { + continue; + }; + let infos: Vec = indices + .into_iter() + .map(|index| IndexInfo { + name: index.name, + table_name: table_name.clone(), + index_type: index.index_type.to_string(), + columns: index.columns, + }) + .collect(); + per_table.push((table_name, table, infos)); + } + + if detailed { + // Fetch stats for each index + let mut indices_with_stats = Vec::new(); + for (table_name, table, infos) in per_table { + for index in infos { + // `Ok(None)` is an index that legitimately has no stats; + // only `Err` is a failed request. Collapsing the two is what + // makes a failure read as an index without statistics. + let stats = or_warn( + table.index_stats(&index.name).await, + &format!( + "reading stats for index '{}' on table '{}'", + index.name, table_name + ), + ) + .flatten() + .map(|s| IndexStats { + num_indexed_rows: s.num_indexed_rows as u64, + num_unindexed_rows: s.num_unindexed_rows as u64, + distance_type: s.distance_type.map(|dt| dt.to_string()), + }); + indices_with_stats.push((index, stats)); + } + } + let result = QueryResult::IndexListDetailed(indices_with_stats); + let output = self.formatter.format(&result)?; + display_with_pager(&output, self.interactive_mode)?; + } else { + let all_indices: Vec = per_table + .into_iter() + .flat_map(|(_, _, infos)| infos) + .collect(); + let result = QueryResult::IndexList(all_indices); + let output = self.formatter.format(&result)?; + display_with_pager(&output, self.interactive_mode)?; + } + Ok(()) + } + + async fn describe_index(&mut self, index_name: &str, detailed: bool) -> Result<()> { + let connection = self + .connection + .as_ref() + .ok_or_else(|| anyhow!("Not connected to LanceDB"))?; + + // Support qualified table.index_name syntax + if let Some((table_name, idx_name)) = index_name.split_once('.') { + let table = connection + .open_table(table_name) + .execute() + .await + .map_err(|_| anyhow!("Table \"{}\" not found.", table_name))?; + let indices = table.list_indices().await?; + for index in indices { + if index.name == idx_name { + Self::print_index_details(&index, table_name, detailed, &table).await; + return Ok(()); + } + } + eprintln!( + "Did not find index \"{}\" on table \"{}\".", + idx_name, table_name + ); + return Ok(()); + } + + // Unqualified: search all tables + let tables = Self::table_names(connection).await?; + let mut found_count = 0u32; + + for table_name in &tables { + if let Ok(table) = connection.open_table(table_name).execute().await { + if let Ok(indices) = table.list_indices().await { + for index in &indices { + if index.name == index_name { + if found_count == 0 { + Self::print_index_details(index, table_name, detailed, &table) + .await; + } + found_count += 1; + } + } + } + } + } + + if found_count == 0 { + eprintln!("Did not find any index named \"{}\".", index_name); + } else if found_count > 1 { + eprintln!( + "\nNote: {} indexes named \"{}\" exist across different tables. \ + Use \\di TABLE.INDEX to specify.", + found_count, index_name + ); + } + Ok(()) + } + + async fn print_index_details( + index: &lancedb::index::IndexConfig, + table_name: &str, + detailed: bool, + table: &lancedb::Table, + ) { + println!("Index \"{}\"", index.name); + println!(" Table: {}", table_name); + println!(" Type: {}", index.index_type); + println!(" Columns: {}", index.columns.join(", ")); + + if detailed { + if let Ok(Some(stats)) = table.index_stats(&index.name).await { + println!("\nStatistics:"); + println!(" Indexed rows: {}", stats.num_indexed_rows); + println!(" Unindexed rows: {}", stats.num_unindexed_rows); + if let Some(dist) = stats.distance_type { + println!(" Distance type: {}", dist); + } + } + } + } +} + +// Compatibility functions for tests that use writer +pub async fn run_client_with_writer( + conn: &ResolvedConnection, + writer: Option>, +) -> anyhow::Result<()> { + // If writer is provided, we need different behavior for tests + // For now, just ignore the writer and use the new implementation + let _ = writer; + + // Create concrete implementations + let sql_executor = + SdkSqlExecutor::new_with_authentication(String::new(), conn.authentication.clone()) + .with_tls(conn.tls.clone()); + + let mut client = LanceDBClient::new( + Some(conn.database.clone()), + true, + OutputFormat::Table, + conn.authentication.clone(), + conn.profile_name.clone(), + sql_executor, + ) + .await?; + + if !conn.sql_server_url.is_empty() { + client.connect(conn).await?; + } + + client.run_repl().await +} + +pub async fn run_client_command_with_writer( + conn: &ResolvedConnection, + command: String, + format: String, + writer: Option>, +) -> anyhow::Result<()> { + // If writer is provided, we need to capture output + let _ = writer; + + let output_format = format.parse::()?; + + // Create concrete implementations + let sql_executor = + SdkSqlExecutor::new_with_authentication(String::new(), conn.authentication.clone()) + .with_tls(conn.tls.clone()); + let mut client = LanceDBClient::new( + Some(conn.database.clone()), + false, + output_format, + conn.authentication.clone(), + conn.profile_name.clone(), + sql_executor, + ) + .await?; + + if !conn.sql_server_url.is_empty() { + client.connect(conn).await?; + } + + let trimmed = command.trim(); + if trimmed.starts_with('\\') { + client.handle_metacommand(trimmed).await?; + } else { + client.execute_query(&command).await?; + } + + Ok(()) +} + +/// SQL lexical rules for scripts. Comments, including MySQL-style hints, must +/// remain comments when deciding which statements to submit independently. +#[derive(Debug, Default)] +struct ScriptDialect(GenericDialect); + +impl Dialect for ScriptDialect { + fn dialect(&self) -> std::any::TypeId { + self.0.dialect() + } + + fn is_identifier_start(&self, ch: char) -> bool { + self.0.is_identifier_start(ch) + } + + fn is_identifier_part(&self, ch: char) -> bool { + self.0.is_identifier_part(ch) + } + + fn is_delimited_identifier_start(&self, ch: char) -> bool { + self.0.is_delimited_identifier_start(ch) + } + + fn supports_nested_comments(&self) -> bool { + true + } + + fn supports_multiline_comment_hints(&self) -> bool { + false + } + + fn supports_string_escape_constant(&self) -> bool { + true + } + + fn supports_unicode_string_literal(&self) -> bool { + true + } +} + +/// Split only on SQL delimiter tokens, retaining the original spelling of each +/// statement. Tokenize the whole script before executing any of its statements. +fn split_sql_script(script: &str) -> Result> { + let tokens = Tokenizer::new(&ScriptDialect::default(), script) + .tokenize_with_location() + .context("Failed to tokenize SQL script")?; + // Token locations count characters rather than bytes. Walk the source once + // to translate delimiter locations without changing Unicode or line endings. + let mut offsets = script + .char_indices() + .scan(Location::new(1, 1), |location, (offset, ch)| { + let start = *location; + if ch == '\n' { + location.line += 1; + location.column = 1; + } else { + location.column += 1; + } + Some((start, offset)) + }); + let mut commands = Vec::new(); + let mut start = 0; + let mut has_statement = false; + for token in tokens { + match token.token { + Token::SemiColon => { + let (_, end) = offsets + .find(|(location, _)| *location == token.span.start) + .context("SQL delimiter location is outside the script")?; + if has_statement { + commands.push(script[start..end].trim()); + } + start = end + 1; + has_statement = false; + } + Token::Whitespace(_) => {} + _ => has_statement = true, + } + } + if has_statement { + commands.push(script[start..].trim()); + } + Ok(commands) +} + +pub async fn run_client_script_with_writer( + conn: &ResolvedConnection, + script: String, + format: String, + writer: Option>, +) -> anyhow::Result<()> { + let _ = writer; + let commands = split_sql_script(&script)?; + + let output_format = format.parse::()?; + + // Create concrete implementations + let sql_executor = + SdkSqlExecutor::new_with_authentication(String::new(), conn.authentication.clone()) + .with_tls(conn.tls.clone()); + let mut client = LanceDBClient::new( + Some(conn.database.clone()), + false, + output_format, + conn.authentication.clone(), + conn.profile_name.clone(), + sql_executor, + ) + .await?; + + if !conn.sql_server_url.is_empty() { + client.connect(conn).await?; + } + + for command in commands { + if command.starts_with('\\') { + client.handle_metacommand(command).await?; + } else { + client.execute_query(command).await?; + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{ + connect_sql_endpoint, copyable_columns, is_show_jobs, prepare_show_jobs_result, + MAX_DISPLAYED_JOB_ROWS, + }; + use crate::formatter::{row_count, OutputFormat, QueryResult, ResultFormatter}; + use crate::mocks::test_mocks::MockSqlExecutor; + use crate::sql_executor::SqlResult; + + #[tokio::test] + async fn table_names_follows_short_and_empty_pages_and_sorts() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let app = axum::Router::new().fallback( + |axum::extract::Query(query): axum::extract::Query< + std::collections::HashMap, + >| async move { + assert_eq!(query.get("limit").map(String::as_str), Some("100")); + let page = match query.get("page_token").map(String::as_str) { + None => serde_json::json!({"tables": ["zebra"], "page_token": "empty"}), + Some("empty") => serde_json::json!({"tables": [], "page_token": "last"}), + Some("last") => serde_json::json!({"tables": ["apple"], "page_token": ""}), + token => panic!("unexpected page token: {token:?}"), + }; + axum::Json(page) + }, + ); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let connection = lancedb::connect("db://test") + .api_key("test") + .region("self-hosted") + .host_override(&endpoint) + .execute() + .await + .unwrap(); + + let tables = super::LanceDBClient::::table_names(&connection).await; + server.abort(); + assert_eq!(tables.unwrap(), ["apple", "zebra"]); + } + + #[tokio::test] + async fn http_connection_failure_preserves_status() { + for status in [ + axum::http::StatusCode::UNAUTHORIZED, + axum::http::StatusCode::FORBIDDEN, + ] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let app = axum::Router::new().fallback(move || async move { status }); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let connection = lancedb::connect("db://test") + .api_key("test") + .region("self-hosted") + .host_override(&endpoint) + .execute() + .await + .unwrap(); + let error = connection + .list_tables( + &[], + lancedb::listing::ListingOptions::default().page_limit(1), + ) + .next_page() + .await + .unwrap_err(); + server.abort(); + let message = super::connection_failure_message(&endpoint, "http", &error.into()); + assert!(message.contains(status.as_str()), "{message}"); + assert!(message.contains(&format!("{endpoint} (http)")), "{message}"); + assert!(!message.contains("connection refused"), "{message}"); + } + } + + #[tokio::test] + async fn sql_connection_failure_preserves_transport_cause() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + let mut executor = super::SdkSqlExecutor::new_with_api_key(String::new(), String::new()); + let (_, error) = connect_sql_endpoint(&mut executor, &endpoint, "test") + .await + .unwrap(); + let message = super::connection_failure_message(&endpoint, "sql", &error.unwrap()); + assert!( + message.to_lowercase().contains("connection refused"), + "{message}" + ); + assert!(message.contains(&format!("{endpoint} (sql)")), "{message}"); + } + + /// The scheme a user configures must survive all the way to the transport; + /// the CLI used to rebuild every address as plaintext http. + #[tokio::test] + async fn sql_endpoint_preserves_the_configured_scheme() { + for (configured, dialed) in [ + ("localhost:10025", "http://localhost:10025"), + ("localhost", "http://localhost:10025"), + ("http://sql.example.com", "http://sql.example.com:80"), + ("https://sql.example.com", "https://sql.example.com:443"), + ( + "https://sql.example.com:10025", + "https://sql.example.com:10025", + ), + ( + "grpc://sql.example.com:10025", + "http://sql.example.com:10025", + ), + ( + "grpcs://sql.example.com:10025", + "https://sql.example.com:10025", + ), + ("grpcs://[fd00::1]:10025", "https://[fd00::1]:10025"), + ] { + let mut executor = MockSqlExecutor::new(); + let (url, err) = connect_sql_endpoint(&mut executor, configured, "analytics") + .await + .unwrap(); + + assert!(err.is_none()); + assert_eq!(url, dialed, "returned url for {configured}"); + assert_eq!( + executor.get_connected_urls(), + vec![dialed.to_string()], + "url handed to the executor for {configured}" + ); + } + } + + #[tokio::test] + async fn sql_endpoint_rejects_an_unusable_address() { + let mut executor = MockSqlExecutor::new(); + assert!( + connect_sql_endpoint(&mut executor, "ftp://sql.example.com", "analytics") + .await + .is_err() + ); + // A rejected address must not reach the transport at all. + assert!(executor.get_connected_urls().is_empty()); + } + + fn jobs(rows: usize) -> SqlResult { + let ids: Vec = (0..rows as i32).collect(); + SqlResult::Query(vec![ + arrow_array::record_batch!(("job_id", Int32, ids)).unwrap() + ]) + } + + #[test] + fn interactive_table_output_is_cut_and_annotated() { + let over = MAX_DISPLAYED_JOB_ROWS + 1; + let (result, notice) = prepare_show_jobs_result(jobs(over), true); + assert_eq!(row_count(&result), MAX_DISPLAYED_JOB_ROWS); + let notice = notice.unwrap(); + assert!(notice.contains(&format!("first {MAX_DISPLAYED_JOB_ROWS} of {over} jobs"))); + assert!(notice.contains("SHOW JOBS FOR
")); + assert!(notice.contains("lancedb sql --command 'SHOW JOBS' --format json")); + + // At or under the cap the listing is whole and says nothing. + let (result, notice) = prepare_show_jobs_result(jobs(MAX_DISPLAYED_JOB_ROWS), true); + assert_eq!(row_count(&result), MAX_DISPLAYED_JOB_ROWS); + assert!(notice.is_none()); + } + + /// A script reading `--format json` needs every row and a payload its + /// parser accepts, so neither the cut nor the notice may reach it. + #[test] + fn programmatic_output_keeps_every_row_and_stays_parsable() { + let over = MAX_DISPLAYED_JOB_ROWS + 1; + let (result, notice) = prepare_show_jobs_result(jobs(over), false); + assert_eq!(row_count(&result), over); + assert!(notice.is_none()); + + for format in [OutputFormat::Json, OutputFormat::Ndjson, OutputFormat::Csv] { + let output = ResultFormatter::new(format) + .format(&QueryResult::SqlResult(jobs(over))) + .unwrap(); + assert!( + !output.contains("Showing the first"), + "{format:?} output must carry no prose" + ); + } + } + + #[test] + fn show_jobs_is_recognized_through_leading_trivia() { + assert!(is_show_jobs("SHOW JOBS")); + assert!(is_show_jobs(" show jobs ;")); + assert!(is_show_jobs("-- list jobs\nSHOW JOBS;")); + assert!(is_show_jobs("/* list jobs */ SHOW JOBS")); + assert!(is_show_jobs("SHOW JOBS FOR t")); + + assert!(!is_show_jobs("SHOW JOBSX")); + assert!(!is_show_jobs("SELECT job_id FROM t")); + // A query that is only a comment names no statement at all. + assert!(!is_show_jobs("-- SHOW JOBS")); + } + + #[test] + fn copyable_columns_follow_the_statement() { + assert_eq!(copyable_columns("SELECT 1"), &[] as &[&str]); + assert_eq!(copyable_columns("cancel job 'x'"), &["job_id"]); + assert_eq!(copyable_columns("/* run */ Cancel Job 'x';"), &["job_id"]); + assert_eq!(copyable_columns("SHOW FUNCTIONS"), &["version"]); + assert_eq!( + copyable_columns("show errors on t"), + &["job_id", "function_version"] + ); + assert_eq!(copyable_columns("REFRESH COLUMN c ON t"), &["job_id"]); + assert_eq!(copyable_columns("REFRESH MATERIALIZED VIEW v"), &["job_id"]); + assert!(!is_show_jobs("/* SHOW JOBS")); + } +} + +#[cfg(test)] +mod watch_tests { + use super::*; + + #[test] + fn d_family_is_watchable() { + for cmd in [ + "\\d", + "\\d+", + "\\dt", + "\\dt+", + "\\di", + "\\di+", + "\\dj", + "\\dj+", + "\\d mytable", + "\\dj mytable", + ] { + assert!(is_watchable_metacommand(cmd), "{cmd} should be watchable"); + } + } + + #[test] + fn dj_maps_to_show_jobs() { + assert_eq!(show_jobs_statement(None), "SHOW JOBS"); + assert_eq!(show_jobs_statement(Some("t")), r#"SHOW JOBS FOR "t""#); + // Names that do not tokenize as a bare identifier; the parser-side + // round trip is pinned by `parses_show_jobs_for_quoted_table`. + assert_eq!( + show_jobs_statement(Some("my-table")), + r#"SHOW JOBS FOR "my-table""# + ); + assert_eq!(show_jobs_statement(Some("a.b")), r#"SHOW JOBS FOR "a.b""#); + assert_eq!( + show_jobs_statement(Some(r#"a"b"#)), + r#"SHOW JOBS FOR "a""b""# + ); + } + + #[test] + fn one_shot_and_watch_are_not_watchable() { + for cmd in [ + "\\watch", + "\\watch 5", + "\\c", + "\\e", + "\\q", + "\\?", + "\\h", + "", + ] { + assert!( + !is_watchable_metacommand(cmd), + "{cmd} should not be watchable" + ); + } + } + + #[test] + fn unrecognized_d_prefixed_commands_are_not_watchable() { + // A `\d`-prefixed typo/unsupported verb is rejected by + // `handle_metacommand`; it must not be treated as watchable, else it + // would clobber `last_command` and make `\watch` loop an error. + for cmd in ["\\dfoo", "\\ds", "\\dn", "\\dd", "\\d++"] { + assert!( + !is_watchable_metacommand(cmd), + "{cmd} should not be watchable" + ); + } + } + + #[test] + fn watch_interval_accepts_only_sane_positive_seconds() { + // Accept normal intervals, including exactly the floor. + assert!(watch_interval(2.0).is_some()); + assert!(watch_interval(0.5).is_some()); + assert!(watch_interval(MIN_WATCH_INTERVAL_SECS).is_some()); + // Reject non-positive, non-finite, and overflowing values (which would + // panic the sleep), plus positive-but-tiny values below the floor that + // would spin the loop with no real delay (e.g. 1e-20 rounds to a + // zero-length sleep; 1e-6 to a nonzero-but-negligible 1us). + for bad in [f64::INFINITY, 1e300, 0.0, -1.0, f64::NAN, 1e-20, 1e-6, 0.05] { + assert!(watch_interval(bad).is_none(), "{bad} should be rejected"); + } + } + + #[test] + fn parse_watch_args_reads_interval_and_optional_statement() { + // (input after `\watch`, expected secs, expected target) + let cases: &[(&str, f64, Option<&str>)] = &[ + ("", 2.0, None), + (" ", 2.0, None), + ("5", 5.0, None), + ("0.5", 0.5, None), + ("SELECT 1", 2.0, Some("SELECT 1")), + ("5 SELECT * FROM t", 5.0, Some("SELECT * FROM t")), + ("2.5 SELECT 1", 2.5, Some("SELECT 1")), + ("\\di+", 2.0, Some("\\di+")), + ("3 \\dt+", 3.0, Some("\\dt+")), + ]; + for (input, secs, target) in cases { + let got = parse_watch_args(input).unwrap_or_else(|e| panic!("{input:?}: {e}")); + assert_eq!( + got.interval, + Duration::from_secs_f64(*secs), + "interval for {input:?}" + ); + assert_eq!(got.target.as_deref(), *target, "target for {input:?}"); + } + } + + #[test] + fn parse_watch_args_rejects_numeric_but_invalid_intervals() { + // A numeric first token is always an interval attempt (never SQL), so + // an unusable one is an error rather than being treated as a statement. + for bad in [ + "0", + "-1", + "inf", + "1e300", + "1e-20", + "0 SELECT 1", + "-2 SELECT 1", + "1e-20 SELECT 1", + ] { + assert!(parse_watch_args(bad).is_err(), "{bad:?} should be rejected"); + } + } +} diff --git a/rust/lancedb/cli/src/dml_result.rs b/rust/lancedb/cli/src/dml_result.rs new file mode 100644 index 000000000..5955ce458 --- /dev/null +++ b/rust/lancedb/cli/src/dml_result.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Typed DML result serializable to/from RecordBatch for Arrow Flight transport. + +use arrow_array::{Int64Array, RecordBatch, StringArray}; +use arrow_schema::{DataType, Field, Schema}; +use std::fmt; +use std::sync::Arc; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum DmlOperation { + Insert, + Update, + Delete, +} + +impl DmlOperation { + pub fn as_str(self) -> &'static str { + match self { + Self::Insert => "INSERT", + Self::Update => "UPDATE", + Self::Delete => "DELETE", + } + } + + fn parse(s: &str) -> Option { + match s { + "INSERT" => Some(Self::Insert), + "UPDATE" => Some(Self::Update), + "DELETE" => Some(Self::Delete), + _ => None, + } + } +} + +impl fmt::Display for DmlOperation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DmlResult { + pub table: String, + pub operation: DmlOperation, + pub rows_affected: i64, + pub version: i64, +} + +fn schema() -> Schema { + Schema::new(vec![ + Field::new("table", DataType::Utf8, false), + Field::new("operation", DataType::Utf8, false), + Field::new("rows_affected", DataType::Int64, false), + Field::new("version", DataType::Int64, false), + ]) +} + +impl DmlResult { + pub fn new( + table: impl Into, + operation: DmlOperation, + rows_affected: i64, + version: i64, + ) -> Self { + Self { + table: table.into(), + operation, + rows_affected, + version, + } + } + + pub fn to_record_batch(&self) -> RecordBatch { + RecordBatch::try_new( + Arc::new(schema()), + vec![ + Arc::new(StringArray::from(vec![self.table.as_str()])), + Arc::new(StringArray::from(vec![self.operation.as_str()])), + Arc::new(Int64Array::from(vec![self.rows_affected])), + Arc::new(Int64Array::from(vec![self.version])), + ], + ) + .expect("static schema") + } + + pub fn try_from_batch(batch: &RecordBatch) -> Option { + if *batch.schema().as_ref() != schema() || batch.num_rows() != 1 { + return None; + } + Some(Self { + table: batch + .column(0) + .as_any() + .downcast_ref::()? + .value(0) + .to_string(), + operation: DmlOperation::parse( + batch + .column(1) + .as_any() + .downcast_ref::()? + .value(0), + )?, + rows_affected: batch + .column(2) + .as_any() + .downcast_ref::()? + .value(0), + version: batch + .column(3) + .as_any() + .downcast_ref::()? + .value(0), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn roundtrip() { + let original = DmlResult::new("foo", DmlOperation::Insert, 1, 3); + let batch = original.to_record_batch(); + assert_eq!(DmlResult::try_from_batch(&batch), Some(original)); + } + + #[test] + fn non_dml_returns_none() { + let s = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); + let batch = RecordBatch::try_new(s, vec![Arc::new(Int64Array::from(vec![1]))]).unwrap(); + assert_eq!(DmlResult::try_from_batch(&batch), None); + } +} diff --git a/rust/lancedb/cli/src/formatter.rs b/rust/lancedb/cli/src/formatter.rs new file mode 100644 index 000000000..05e6deb4d --- /dev/null +++ b/rust/lancedb/cli/src/formatter.rs @@ -0,0 +1,2516 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use crate::client::{IndexInfo, IndexStats, TableInfo}; +use crate::sql_executor::SqlResult; +use crate::table_writer::TableWriter; +use anyhow::Result; +use arrow_array::types::ArrowDictionaryKeyType; +use arrow_array::{ + downcast_dictionary_array, Array, BinaryArray, BooleanArray, DictionaryArray, + FixedSizeListArray, Float32Array, Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, + LargeBinaryArray, ListArray, RecordBatch, StringArray, UInt16Array, UInt32Array, UInt64Array, + UInt8Array, +}; +use arrow_buffer::ArrowNativeType; +use arrow_cast::display::{ArrayFormatter, FormatOptions}; +use arrow_json::writer::{make_encoder, Encoder, EncoderFactory, EncoderOptions, NullableEncoder}; +use arrow_schema::{DataType, Field, Schema}; +use std::io::Write; +use std::str::FromStr; +use std::sync::Arc; +use tracing::warn; + +/// Result of a query engine command +#[derive(Debug)] +pub enum QueryResult { + /// SQL query result + SqlResult(SqlResult), + /// List of table names + TableList(Vec), + /// List of tables with detailed stats + TableListDetailed(Vec), + /// Table information + TableInfo(TableInfo), + /// Table information with indices + TableInfoWithIndices(TableInfo, Vec), + /// Index information + IndexList(Vec), + /// List of indices with detailed stats + IndexListDetailed(Vec<(IndexInfo, Option)>), +} + +/// Output format options +#[derive(Debug, Clone, Copy)] +pub enum OutputFormat { + Table, + Csv, + Json, + Ndjson, +} + +impl FromStr for OutputFormat { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "table" => Ok(Self::Table), + "csv" => Ok(Self::Csv), + "json" => Ok(Self::Json), + "ndjson" => Ok(Self::Ndjson), + _ => Err(anyhow::anyhow!( + "Invalid output format: {}. Must be one of: table, csv, json, ndjson", + s + )), + } + } +} + +/// Formats query results for display +pub struct ResultFormatter { + output_format: OutputFormat, + /// Optional override for the terminal width used to choose between table + /// and expanded rendering. `None` auto-detects from the terminal; + /// tests pin it so output is independent of the ambient terminal size. + terminal_width: Option, +} + +impl ResultFormatter { + /// Create a new ResultFormatter + pub fn new(output_format: OutputFormat) -> Self { + Self { + output_format, + terminal_width: None, + } + } + + pub fn with_terminal_width(mut self, width: usize) -> Self { + self.terminal_width = Some(width); + self + } + + pub fn output_format(&self) -> OutputFormat { + self.output_format + } + + /// Format a QueryResult to string + pub fn format(&self, result: &QueryResult) -> Result { + let mut output = Vec::new(); + self.format_to_writer(result, &mut output)?; + Ok(String::from_utf8(output)?) + } + + /// Format a QueryResult to a writer + pub fn format_to_writer(&self, result: &QueryResult, writer: &mut W) -> Result<()> { + match result { + QueryResult::SqlResult(sql_result) => self.format_sql_result(sql_result, writer), + QueryResult::TableList(tables) => self.format_table_list(tables, writer), + QueryResult::TableListDetailed(tables) => { + self.format_table_list_detailed(tables, writer) + } + QueryResult::TableInfo(info) => self.format_table_info(info, writer), + QueryResult::TableInfoWithIndices(info, indices) => { + self.format_table_info_with_indices(info, indices, writer) + } + QueryResult::IndexList(indices) => self.format_index_list(indices, writer), + QueryResult::IndexListDetailed(indices) => { + self.format_index_list_detailed(indices, writer) + } + } + } + + /// Format SQL result + fn format_sql_result(&self, result: &SqlResult, writer: &mut W) -> Result<()> { + match result { + SqlResult::Query(batches) => self.format_record_batches(batches, writer), + SqlResult::Dml(dml) => { + writeln!( + writer, + "{} {} row(s), version {}", + dml.operation, dml.rows_affected, dml.version + )?; + Ok(()) + } + SqlResult::Success => { + writeln!(writer, "Success")?; + Ok(()) + } + } + } + + /// Format record batches + pub fn format_record_batches( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + if batches.is_empty() { + return Ok(()); + } + + match self.output_format { + OutputFormat::Table => self.format_batches_as_table(batches, writer), + OutputFormat::Csv => self.format_batches_as_csv(batches, writer), + OutputFormat::Json => self.format_batches_as_json(batches, writer), + OutputFormat::Ndjson => self.format_batches_as_ndjson(batches, writer), + } + } + + /// Format batches as table + fn format_batches_as_table( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + let schema = batches[0].schema(); + let column_names: Vec = schema.fields().iter().map(|f| f.name().clone()).collect(); + + // Check if this is an EXPLAIN query (has plan_type and plan columns) + let is_explain = + column_names.len() == 2 && column_names[0] == "plan_type" && column_names[1] == "plan"; + + if is_explain { + return self.format_explain_results(batches, writer); + } + + let mut rows = Vec::new(); + let mut total_rows = 0; + + for batch in batches { + total_rows += batch.num_rows(); + for row_idx in 0..batch.num_rows() { + let mut row = Vec::new(); + for col_idx in 0..batch.num_columns() { + let column = batch.column(col_idx); + let field = schema.field(col_idx); + let value = format_arrow_value(column, row_idx, field); + row.push(value); + } + rows.push(row); + } + } + + TableWriter::print_table(writer, &column_names, &rows, self.terminal_width)?; + writeln!( + writer, + "({} row{})", + total_rows, + if total_rows == 1 { "" } else { "s" } + )?; + Ok(()) + } + + /// Format EXPLAIN query results + fn format_explain_results( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + writeln!( + writer, + " QUERY PLAN" + )?; + writeln!(writer, "---------------------------------------------------------------------------------------------------")?; + + let mut logical_plan = String::new(); + let mut physical_plan = String::new(); + let mut plan_with_metrics = String::new(); + + // Extract the plans from the batches + for batch in batches { + for row_idx in 0..batch.num_rows() { + if batch.num_columns() >= 2 { + let plan_type_col = batch.column(0); + let plan_col = batch.column(1); + + let plan_type = plan_type_col + .as_any() + .downcast_ref::() + .map(|arr| arr.value(row_idx)) + .unwrap_or(""); + + let plan = plan_col + .as_any() + .downcast_ref::() + .map(|arr| arr.value(row_idx)) + .unwrap_or(""); + + match plan_type { + "logical_plan" => logical_plan = plan.to_string(), + "physical_plan" => physical_plan = plan.to_string(), + "Plan with Metrics" => plan_with_metrics = plan.to_string(), + _ => {} + } + } + } + } + + // Display logical plan + if !logical_plan.is_empty() { + writeln!(writer, "Logical Plan:")?; + for line in logical_plan.lines() { + writeln!(writer, " {}", line)?; + } + } + + // Display physical plan + if !physical_plan.is_empty() { + if !logical_plan.is_empty() { + writeln!(writer)?; + } + writeln!(writer, "Physical Plan:")?; + for line in physical_plan.lines() { + writeln!(writer, " {}", line)?; + } + } + + // Display plan with metrics (EXPLAIN ANALYZE) + if !plan_with_metrics.is_empty() { + if !logical_plan.is_empty() || !physical_plan.is_empty() { + writeln!(writer)?; + } + for line in plan_with_metrics.lines() { + writeln!(writer, "{}", line)?; + } + } + + writeln!( + writer, + "({} row{})", + batches.iter().map(|b| b.num_rows()).sum::(), + if batches.iter().map(|b| b.num_rows()).sum::() == 1 { + "" + } else { + "s" + } + )?; + Ok(()) + } + + /// Format batches as CSV + fn format_batches_as_csv( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + let schema = batches[0].schema(); + + for (index, field) in schema.fields().iter().enumerate() { + if index > 0 { + write!(writer, ",")?; + } + write_csv_value(writer, field.name())?; + } + writeln!(writer)?; + + let scalar_options = FormatOptions::default(); + let json_options = EncoderOptions::default() + .with_explicit_nulls(true) + .with_encoder_factory(Arc::new(CsvJsonEncoderFactory)); + let mut json_value = Vec::new(); + + for batch in batches { + if batch.num_rows() == 0 { + continue; + } + let schema = batch.schema(); + let mut formatters = schema + .fields() + .iter() + .zip(batch.columns()) + .map(|(field, column)| { + if csv_uses_json(column.data_type()) { + Ok(CsvValueFormatter::Json(make_encoder( + field, + column.as_ref(), + &json_options, + )?)) + } else { + Ok(CsvValueFormatter::Scalar(ArrayFormatter::try_new( + column.as_ref(), + &scalar_options, + )?)) + } + }) + .collect::>>()?; + let nulls: Vec<_> = batch + .columns() + .iter() + .map(|column| column.logical_nulls()) + .collect(); + + for row_idx in 0..batch.num_rows() { + for (col_idx, formatter) in formatters.iter_mut().enumerate() { + if col_idx > 0 { + write!(writer, ",")?; + } + // Logical nulls include null dictionary values and Null arrays. + if nulls[col_idx] + .as_ref() + .is_some_and(|nulls| nulls.is_null(row_idx)) + { + write!(writer, "{CSV_NULL_VALUE}")?; + continue; + } + match formatter { + CsvValueFormatter::Scalar(formatter) => { + write_csv_cell(writer, &formatter.value(row_idx).try_to_string()?)?; + } + CsvValueFormatter::Json(encoder) => { + json_value.clear(); + encoder.encode(row_idx, &mut json_value); + write_csv_cell(writer, std::str::from_utf8(&json_value)?)?; + } + } + } + writeln!(writer)?; + } + } + Ok(()) + } + + /// Format batches as JSON + fn format_batches_as_json( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + if batches.is_empty() { + writeln!(writer, "[]")?; + return Ok(()); + } + // Arrow's bytes go out as written. Re-reading them through + // `serde_json::Value` to pretty-print would round every decimal the + // writer emitted exactly. + let mut json = Vec::new(); + let mut json_writer = arrow_json::writer::WriterBuilder::new() + .with_explicit_nulls(true) + .build::<_, arrow_json::writer::JsonArray>(&mut json); + for batch in batches { + json_writer.write(batch)?; + } + json_writer.finish()?; + writer.write_all(&json)?; + writeln!(writer)?; + Ok(()) + } + + /// Format batches as NDJSON + fn format_batches_as_ndjson( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + if batches.is_empty() { + return Ok(()); + } + let mut json = Vec::new(); + let mut json_writer = arrow_json::writer::WriterBuilder::new() + .with_explicit_nulls(true) + .build::<_, arrow_json::writer::LineDelimited>(&mut json); + for batch in batches { + json_writer.write(batch)?; + } + json_writer.finish()?; + writer.write_all(&json)?; + Ok(()) + } + + /// Format table list + fn format_table_list(&self, tables: &[String], writer: &mut W) -> Result<()> { + match self.output_format { + OutputFormat::Json => { + let json = serde_json::to_string_pretty(&tables)?; + writeln!(writer, "{}", json)?; + } + _ => { + if tables.is_empty() { + writeln!(writer, "Did not find any relations.")?; + } else { + let headers = vec!["Tables".to_string()]; + let data: Vec> = tables.iter().map(|t| vec![t.clone()]).collect(); + TableWriter::print_table_with_title( + writer, + "List of relations", + &headers, + &data, + self.terminal_width, + )?; + writeln!( + writer, + "({} row{})", + tables.len(), + if tables.len() == 1 { "" } else { "s" } + )?; + } + } + } + Ok(()) + } + + /// Format detailed table list with stats + fn format_table_list_detailed( + &self, + tables: &[TableInfo], + writer: &mut W, + ) -> Result<()> { + match self.output_format { + OutputFormat::Json => { + let json = serde_json::json!(tables + .iter() + .map(|t| { + serde_json::json!({ + "name": t.name, + "type": "table", + "rows": t.row_count, + "size_bytes": t.size_bytes, + "indices": t.num_indices, + "fragments": t.num_fragments, + }) + }) + .collect::>()); + let json_string = serde_json::to_string_pretty(&json)?; + writeln!(writer, "{}", json_string)?; + } + _ => { + if tables.is_empty() { + writeln!(writer, "Did not find any relations.")?; + } else { + let headers = vec![ + "Name".to_string(), + "Type".to_string(), + "Rows".to_string(), + "Size".to_string(), + "Indices".to_string(), + "Fragments".to_string(), + ]; + + let data: Vec> = tables + .iter() + .map(|t| { + vec![ + t.name.clone(), + "table".to_string(), + t.row_count.map_or("".to_string(), |r| r.to_string()), + t.size_bytes.map_or("".to_string(), format_bytes), + t.num_indices + .filter(|&n| n > 0) + .map_or("".to_string(), |n| n.to_string()), + t.num_fragments + .filter(|&n| n > 0) + .map_or("".to_string(), |n| n.to_string()), + ] + }) + .collect(); + + TableWriter::print_table_with_title( + writer, + "List of relations", + &headers, + &data, + self.terminal_width, + )?; + writeln!( + writer, + "({} row{})", + tables.len(), + if tables.len() == 1 { "" } else { "s" } + )?; + } + } + } + Ok(()) + } + + /// Format table info + fn format_table_info(&self, info: &TableInfo, writer: &mut W) -> Result<()> { + match self.output_format { + OutputFormat::Json => { + let json = serde_json::json!({ + "name": info.name, + "schema": schema_to_json(&info.schema), + "row_count": info.row_count, + "size_bytes": info.size_bytes, + "num_indices": info.num_indices, + "num_fragments": info.num_fragments, + }); + let json_string = serde_json::to_string_pretty(&json)?; + writeln!(writer, "{}", json_string)?; + } + _ => { + // Format as table + writeln!(writer, " Table \"{}\"", info.name)?; + + let headers = vec![ + "Column".to_string(), + "Type".to_string(), + "Nullable".to_string(), + ]; + let mut data = Vec::new(); + + for field in info.schema.fields() { + let data_type = format_data_type(field.data_type()); + let nullable = if field.is_nullable() { "YES" } else { "" }; + data.push(vec![field.name().clone(), data_type, nullable.to_string()]); + } + + TableWriter::print_table(writer, &headers, &data, self.terminal_width)?; + + // Add stats if available + if let Some(row_count) = info.row_count { + writeln!(writer, "\nRows: {}", row_count)?; + } + if let Some(size) = info.size_bytes { + writeln!(writer, "Size: {}", format_bytes(size))?; + } + } + } + Ok(()) + } + + /// Format table info with indices (similar to psql \d
) + fn format_table_info_with_indices( + &self, + info: &TableInfo, + indices: &[IndexInfo], + writer: &mut W, + ) -> Result<()> { + match self.output_format { + OutputFormat::Table => { + // Format as table (psql style) + writeln!(writer, " Table \"{}\"", info.name)?; + + let headers = vec![ + "Column".to_string(), + "Type".to_string(), + "Nullable".to_string(), + ]; + let mut data = Vec::new(); + for field in info.schema.fields() { + let data_type = format_data_type(field.data_type()); + let nullable = if field.is_nullable() { "YES" } else { "" }; + data.push(vec![field.name().clone(), data_type, nullable.to_string()]); + } + TableWriter::print_table(writer, &headers, &data, self.terminal_width)?; + + // List indexes if any + if !indices.is_empty() { + writeln!(writer, "Indexes:")?; + for index in indices { + let columns = index.columns.join(", "); + writeln!( + writer, + " \"{}\" {} ({})", + index.name, index.index_type, columns + )?; + } + } + + // Add stats if available + if let Some(row_count) = info.row_count { + writeln!(writer, "\nRows: {}", row_count)?; + } + if let Some(size) = info.size_bytes { + writeln!(writer, "Size: {}", format_bytes(size))?; + } + } + OutputFormat::Csv => { + // CSV format: output schema info and indices as separate sections + writeln!(writer, "# Table: {}", info.name)?; + writeln!(writer, "# Schema")?; + writeln!(writer, "Column,Type,Nullable")?; + for field in info.schema.fields() { + let data_type = format_data_type(field.data_type()); + let nullable = if field.is_nullable() { "YES" } else { "NO" }; + writeln!(writer, "{},{},{}", field.name(), data_type, nullable)?; + } + + if !indices.is_empty() { + writeln!(writer, "\n# Indices")?; + writeln!(writer, "Index Name,Index Type,Columns")?; + for index in indices { + let columns = index.columns.join(";"); + writeln!(writer, "{},{},{}", index.name, index.index_type, columns)?; + } + } + + if let Some(row_count) = info.row_count { + writeln!(writer, "\n# Row Count: {}", row_count)?; + } + if let Some(size) = info.size_bytes { + writeln!(writer, "# Size: {}", format_bytes(size))?; + } + } + OutputFormat::Json => { + let json = serde_json::json!({ + "name": info.name, + "schema": schema_to_json(&info.schema), + "row_count": info.row_count, + "size_bytes": info.size_bytes, + "num_indices": info.num_indices, + "num_fragments": info.num_fragments, + "indices": indices, + }); + let json_string = serde_json::to_string_pretty(&json)?; + writeln!(writer, "{}", json_string)?; + } + OutputFormat::Ndjson => { + // NDJSON: one line for table info, one line per index + let table_json = serde_json::json!({ + "type": "table_info", + "name": info.name, + "schema": schema_to_json(&info.schema), + "row_count": info.row_count, + "size_bytes": info.size_bytes, + "num_indices": info.num_indices, + "num_fragments": info.num_fragments, + }); + writeln!(writer, "{}", serde_json::to_string(&table_json)?)?; + + for index in indices { + let index_json = serde_json::json!({ + "type": "index_info", + "table": info.name, + "name": index.name, + "index_type": index.index_type, + "columns": index.columns, + }); + writeln!(writer, "{}", serde_json::to_string(&index_json)?)?; + } + } + } + Ok(()) + } + + /// Format index list + fn format_index_list(&self, indices: &[IndexInfo], writer: &mut W) -> Result<()> { + match self.output_format { + OutputFormat::Json => { + let json = serde_json::to_string_pretty(&indices)?; + writeln!(writer, "{}", json)?; + } + _ => { + if indices.is_empty() { + writeln!(writer, "Did not find any indexes.")?; + } else { + let headers = vec!["Name".to_string(), "Type".to_string(), "Table".to_string()]; + let data: Vec> = indices + .iter() + .map(|idx| { + vec![ + idx.name.clone(), + idx.index_type.clone(), + idx.table_name.clone(), + ] + }) + .collect(); + + TableWriter::print_table_with_title( + writer, + "List of indices", + &headers, + &data, + self.terminal_width, + )?; + writeln!( + writer, + "({} row{})", + indices.len(), + if indices.len() == 1 { "" } else { "s" } + )?; + } + } + } + Ok(()) + } + + /// Format detailed index list with stats + fn format_index_list_detailed( + &self, + indices: &[(IndexInfo, Option)], + writer: &mut W, + ) -> Result<()> { + match self.output_format { + OutputFormat::Json => { + let json = serde_json::json!(indices + .iter() + .map(|(info, stats)| { + let mut obj = serde_json::json!({ + "name": info.name, + "type": info.index_type, + "table": info.table_name, + "columns": info.columns, + }); + if let Some(stats) = stats { + obj["distance_type"] = serde_json::json!(stats.distance_type); + obj["indexed_rows"] = serde_json::json!(stats.num_indexed_rows); + obj["unindexed_rows"] = serde_json::json!(stats.num_unindexed_rows); + } + obj + }) + .collect::>()); + let json_string = serde_json::to_string_pretty(&json)?; + writeln!(writer, "{}", json_string)?; + } + _ => { + if indices.is_empty() { + writeln!(writer, "Did not find any indexes.")?; + } else { + let headers = vec![ + "Name".to_string(), + "Type".to_string(), + "Distance".to_string(), + "Indexed Rows".to_string(), + "Unindexed Rows".to_string(), + "Table".to_string(), + ]; + + let data: Vec> = indices + .iter() + .map(|(info, stats)| { + let (distance, indexed, unindexed) = if let Some(s) = stats { + ( + s.distance_type.as_deref().unwrap_or(""), + s.num_indexed_rows.to_string(), + s.num_unindexed_rows.to_string(), + ) + } else { + ("", "".to_string(), "".to_string()) + }; + + vec![ + info.name.clone(), + info.index_type.clone(), + distance.to_string(), + indexed, + unindexed, + info.table_name.clone(), + ] + }) + .collect(); + + TableWriter::print_table_with_title( + writer, + "List of relations", + &headers, + &data, + self.terminal_width, + )?; + writeln!( + writer, + "({} row{})", + indices.len(), + if indices.len() == 1 { "" } else { "s" } + )?; + } + } + } + Ok(()) + } +} + +// Helper functions + +enum CsvValueFormatter<'a> { + Scalar(ArrayFormatter<'a>), + Json(NullableEncoder<'a>), +} + +fn csv_uses_json(data_type: &DataType) -> bool { + match data_type { + DataType::Dictionary(_, value) => csv_uses_json(value), + DataType::RunEndEncoded(_, value) => csv_uses_json(value.data_type()), + _ => data_type.is_nested(), + } +} + +const CSV_NULL_VALUE: &str = r"\N"; + +fn write_csv_cell(writer: &mut W, value: &str) -> Result<()> { + // Escape leading backslashes so the null marker cannot collide with data. + if value.starts_with('\\') { + write_csv_value(writer, &format!("\\{value}")) + } else { + write_csv_value(writer, value) + } +} + +fn write_csv_value(writer: &mut W, value: &str) -> Result<()> { + // An empty single-column record must not become a blank line. + if value.is_empty() || value.contains([',', '"', '\n', '\r']) { + write!(writer, "\"{}\"", value.replace('"', "\"\""))?; + } else { + write!(writer, "{value}")?; + } + Ok(()) +} + +#[derive(Debug)] +struct CsvJsonEncoderFactory; + +impl EncoderFactory for CsvJsonEncoderFactory { + fn make_default_encoder<'a>( + &self, + field: &'a arrow_schema::FieldRef, + array: &'a dyn arrow_array::Array, + options: &'a EncoderOptions, + ) -> std::result::Result>, arrow_schema::ArrowError> { + downcast_dictionary_array! { + array => { + let values = make_encoder(field, array.values().as_ref(), options)?; + // Parent encoders must see keys pointing to null values as nulls. + return Ok(Some(NullableEncoder::new( + Box::new(CsvJsonDictionaryEncoder { dictionary: array, values }), + array.logical_nulls(), + ))); + } + _ => {} + } + if !matches!( + array.data_type(), + DataType::Float16 | DataType::Float32 | DataType::Float64 + ) { + return Ok(None); + } + let formatter = ArrayFormatter::try_new(array, &FormatOptions::default())?; + Ok(Some(NullableEncoder::new( + Box::new(CsvJsonFloatEncoder(formatter)), + array.nulls().cloned(), + ))) + } +} + +struct CsvJsonDictionaryEncoder<'a, K: ArrowDictionaryKeyType> { + dictionary: &'a DictionaryArray, + values: NullableEncoder<'a>, +} + +impl Encoder for CsvJsonDictionaryEncoder<'_, K> { + fn encode(&mut self, idx: usize, out: &mut Vec) { + self.values + .encode(self.dictionary.keys().value(idx).as_usize(), out); + } +} + +struct CsvJsonFloatEncoder<'a>(ArrayFormatter<'a>); + +impl Encoder for CsvJsonFloatEncoder<'_> { + fn encode(&mut self, idx: usize, out: &mut Vec) { + let value = self.0.value(idx).to_string(); + // JSON has no non-finite numbers; keep their names instead of turning + // them into nulls, as Arrow's default JSON float encoder does. + if matches!(value.as_str(), "NaN" | "inf" | "-inf") { + out.push(b'"'); + out.extend_from_slice(value.as_bytes()); + out.push(b'"'); + } else { + out.extend_from_slice(value.as_bytes()); + } + } +} + +/// Longest string rendered in full when a column has not opted out of +/// truncation. +const MAX_UNTRUNCATED_STRING_LEN: usize = 50; + +/// Arrow field metadata key marking a column that must be rendered in full. +const NO_TRUNCATE_METADATA_KEY: &str = "lancedb.display.no_truncate"; + +/// Whether this field is marked to render in full. +fn field_opts_out_of_truncation(field: &Field) -> bool { + field + .metadata() + .get(NO_TRUNCATE_METADATA_KEY) + .is_some_and(|value| value == "true") +} + +/// Rows a query returned, across batches. Zero for non-query results. +pub fn row_count(result: &SqlResult) -> usize { + match result { + SqlResult::Query(batches) => batches.iter().map(RecordBatch::num_rows).sum(), + _ => 0, + } +} + +/// Keep the first `limit` rows, for a listing whose reader is a human at a +/// terminal rather than a program. Slices are zero-copy, so the dropped rows +/// cost nothing beyond the memory they already occupy. Non-query results pass +/// through. +pub fn take_rows(result: SqlResult, limit: usize) -> SqlResult { + let SqlResult::Query(batches) = result else { + return result; + }; + + let mut remaining = limit; + let mut kept = Vec::with_capacity(batches.len()); + for batch in batches { + if remaining == 0 { + break; + } + let take = remaining.min(batch.num_rows()); + remaining -= take; + kept.push(batch.slice(0, take)); + } + SqlResult::Query(kept) +} + +/// Mark `columns` so rendering keeps their values whole, for results whose +/// consumer needs to copy a value verbatim rather than read it. +pub fn mark_no_truncate(result: SqlResult, columns: &[&str]) -> SqlResult { + match result { + SqlResult::Query(batches) => SqlResult::Query( + batches + .into_iter() + .map(|batch| mark_batch_columns(batch, columns)) + .collect(), + ), + other => other, + } +} + +/// Rebuild `batch` with the named fields marked, leaving its data untouched. +fn mark_batch_columns(batch: RecordBatch, columns: &[&str]) -> RecordBatch { + let schema = batch.schema(); + let fields: Vec = schema + .fields() + .iter() + .map(|field| { + if !columns.contains(&field.name().as_str()) { + return field.as_ref().clone(); + } + let mut metadata = field.metadata().clone(); + metadata.insert(NO_TRUNCATE_METADATA_KEY.to_string(), "true".to_string()); + field.as_ref().clone().with_metadata(metadata) + }) + .collect(); + + let marked = Arc::new(Schema::new_with_metadata(fields, schema.metadata().clone())); + match RecordBatch::try_new(marked, batch.columns().to_vec()) { + Ok(batch) => batch, + // Only the metadata changed, so this should not fail. Render the + // original rather than the error, at the cost of abbreviating them. + Err(err) => { + warn!("could not mark columns to render in full, values may be abbreviated: {err}"); + batch + } + } +} + +/// Render a string cell, abbreviating it unless the field opts out. +fn format_string_value(value: &str, field: &Field) -> String { + if value.len() <= MAX_UNTRUNCATED_STRING_LEN || field_opts_out_of_truncation(field) { + return value.to_string(); + } + let end = value.floor_char_boundary(MAX_UNTRUNCATED_STRING_LEN); + format!("{}...({} chars)", &value[..end], value.chars().count()) +} + +/// Format arrow value as string +fn format_arrow_value(column: &dyn arrow_array::Array, row_idx: usize, field: &Field) -> String { + if column.is_null(row_idx) { + return "NULL".to_string(); + } + + match field.data_type() { + DataType::Utf8 => { + let array = column.as_any().downcast_ref::().unwrap(); + format_string_value(array.value(row_idx), field) + } + DataType::LargeUtf8 => { + let array = column + .as_any() + .downcast_ref::() + .unwrap(); + format_string_value(array.value(row_idx), field) + } + DataType::Utf8View => { + let array = column + .as_any() + .downcast_ref::() + .unwrap(); + format_string_value(array.value(row_idx), field) + } + DataType::Int8 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Int16 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Int32 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Int64 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::UInt8 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::UInt16 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::UInt32 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::UInt64 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Float32 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Float64 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Boolean => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::FixedSizeList(inner_field, size) => { + // Handle fixed size vectors (e.g., embeddings) + let list_array = column + .as_any() + .downcast_ref::() + .unwrap(); + let values = list_array.value(row_idx); + + // Format as [value1, value2, ...] for short vectors, with size info for long ones + match inner_field.data_type() { + DataType::Float32 => { + let float_array = values.as_any().downcast_ref::().unwrap(); + if float_array.len() > 10 { + let first = float_array.value(0); + let second = float_array.value(1); + format!("[{}, {}, ...{} more]", first, second, float_array.len() - 2) + } else { + // Show all values if 10 or fewer + let values: Vec = (0..float_array.len()) + .map(|i| float_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::Float64 => { + let float_array = values.as_any().downcast_ref::().unwrap(); + if float_array.len() > 10 { + let first = float_array.value(0); + let second = float_array.value(1); + format!("[{}, {}, ...{} more]", first, second, float_array.len() - 2) + } else { + // Show all values if 10 or fewer + let values: Vec = (0..float_array.len()) + .map(|i| float_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + _ => { + format!("[{} items]", *size) + } + } + } + DataType::List(inner_field) => { + // Handle variable size lists + let list_array = column.as_any().downcast_ref::().unwrap(); + let values = list_array.value(row_idx); + let size = values.len(); + + // Format as [value1, value2, ...] for short vectors, truncated for long ones + match inner_field.data_type() { + DataType::Float32 => { + let float_array = values.as_any().downcast_ref::().unwrap(); + if float_array.len() > 10 { + let first = float_array.value(0); + let second = float_array.value(1); + format!("[{}, {}, ...{} more]", first, second, float_array.len() - 2) + } else { + // Show all values if 10 or fewer + let values: Vec = (0..float_array.len()) + .map(|i| float_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::Float64 => { + let float_array = values.as_any().downcast_ref::().unwrap(); + if float_array.len() > 10 { + let first = float_array.value(0); + let second = float_array.value(1); + format!("[{}, {}, ...{} more]", first, second, float_array.len() - 2) + } else { + // Show all values if 10 or fewer + let values: Vec = (0..float_array.len()) + .map(|i| float_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::Int32 => { + let int_array = values.as_any().downcast_ref::().unwrap(); + if int_array.len() > 10 { + let first = int_array.value(0); + let second = int_array.value(1); + format!("[{}, {}, ...{} more]", first, second, int_array.len() - 2) + } else { + let values: Vec = (0..int_array.len()) + .map(|i| int_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::Int64 => { + let int_array = values.as_any().downcast_ref::().unwrap(); + if int_array.len() > 10 { + let first = int_array.value(0); + let second = int_array.value(1); + format!("[{}, {}, ...{} more]", first, second, int_array.len() - 2) + } else { + let values: Vec = (0..int_array.len()) + .map(|i| int_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + _ => { + format!("[{} items]", size) + } + } + } + DataType::Binary => { + let array = column.as_any().downcast_ref::().unwrap(); + let bytes = array.value(row_idx); + if bytes.len() > 32 { + // Show first few bytes with ellipsis for large binary data + let preview: Vec = bytes[..8].iter().map(|b| format!("{}", b)).collect(); + format!( + "[{}, ...{} more bytes]", + preview.join(", "), + bytes.len() - 8 + ) + } else { + // Show all bytes if small + let values: Vec = bytes.iter().map(|b| format!("{}", b)).collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::LargeBinary => { + let array = column.as_any().downcast_ref::().unwrap(); + let bytes = array.value(row_idx); + if bytes.len() > 32 { + // Show first few bytes with ellipsis for large binary data + let preview: Vec = bytes[..8].iter().map(|b| format!("{}", b)).collect(); + format!( + "[{}, ...{} more bytes]", + preview.join(", "), + bytes.len() - 8 + ) + } else { + // Show all bytes if small + let values: Vec = bytes.iter().map(|b| format!("{}", b)).collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::Struct(fields) => { + let struct_array = column + .as_any() + .downcast_ref::() + .unwrap(); + let mut field_strs = Vec::new(); + + for (i, field) in fields.iter().enumerate() { + let field_column = struct_array.column(i); + let field_value = format_arrow_value(field_column, row_idx, field); + field_strs.push(format!("{}: {}", field.name(), field_value)); + } + + format!("{{{}}}", field_strs.join(", ")) + } + _ => arrow_cast::display::array_value_to_string(column, row_idx) + .unwrap_or_else(|_| format!("{:?}", column.slice(row_idx, 1))), + } +} + +/// Format arrow value as JSON +/// Convert batches to JSON +/// Format data type for display +fn format_data_type(data_type: &arrow_schema::DataType) -> String { + use arrow_schema::DataType; + + match data_type { + DataType::Boolean => "BOOLEAN".to_string(), + DataType::Int8 => "TINYINT".to_string(), + DataType::Int16 => "SMALLINT".to_string(), + DataType::Int32 => "INT".to_string(), + DataType::Int64 => "BIGINT".to_string(), + DataType::UInt8 => "TINYINT UNSIGNED".to_string(), + DataType::UInt16 => "SMALLINT UNSIGNED".to_string(), + DataType::UInt32 => "INT UNSIGNED".to_string(), + DataType::UInt64 => "BIGINT UNSIGNED".to_string(), + DataType::Float32 => "FLOAT".to_string(), + DataType::Float64 => "DOUBLE".to_string(), + DataType::Utf8 => "TEXT".to_string(), + DataType::LargeUtf8 => "TEXT".to_string(), + DataType::Binary => "BLOB".to_string(), + DataType::LargeBinary => "BLOB".to_string(), + DataType::Date32 => "DATE".to_string(), + DataType::Date64 => "DATE".to_string(), + DataType::Timestamp(_unit, tz) => { + let tz_str = tz.as_ref().map(|s| format!(" ({})", s)).unwrap_or_default(); + format!("TIMESTAMP{}", tz_str) + } + DataType::Time32(_) => "TIME".to_string(), + DataType::Time64(_) => "TIME".to_string(), + DataType::Decimal128(precision, scale) => format!("DECIMAL({}, {})", precision, scale), + DataType::Decimal256(precision, scale) => format!("DECIMAL({}, {})", precision, scale), + DataType::List(field) => format!("LIST<{}>", format_data_type(field.data_type())), + DataType::FixedSizeList(field, size) => { + format!("{}[{}]", format_data_type(field.data_type()), size) + } + DataType::Struct(fields) => { + let field_types: Vec = fields + .iter() + .map(|f| format!("{}: {}", f.name(), format_data_type(f.data_type()))) + .collect(); + format!("STRUCT<{}>", field_types.join(", ")) + } + _ => format!("{:?}", data_type), + } +} + +/// Format bytes to human readable +fn format_bytes(bytes: u64) -> String { + const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB", "PB"]; + if bytes == 0 { + return "0 B".to_string(); + } + + let mut size = bytes as f64; + let mut unit_index = 0; + + while size >= 1024.0 && unit_index < UNITS.len() - 1 { + size /= 1024.0; + unit_index += 1; + } + + if unit_index == 0 { + format!("{} {}", bytes, UNITS[unit_index]) + } else { + format!("{:.1} {}", size, UNITS[unit_index]) + } +} + +/// Convert schema to JSON +fn schema_to_json(schema: &Schema) -> serde_json::Value { + use serde_json::json; + + let fields: Vec = schema + .fields() + .iter() + .map(|field| { + json!({ + "name": field.name(), + "type": format_data_type(field.data_type()), + "nullable": field.is_nullable(), + }) + }) + .collect(); + + json!(fields) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::client::IndexStats; + use crate::dml_result::{DmlOperation, DmlResult}; + use arrow_array::{ + ArrayRef, BooleanArray, FixedSizeListArray, Float32Array, Int32Array, StringArray, + }; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + fn create_test_batch() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("name", DataType::Utf8, false), + Field::new("score", DataType::Float32, true), + Field::new("active", DataType::Boolean, false), + ])); + + let id_array = Int32Array::from(vec![1, 2, 3]); + let name_array = StringArray::from(vec!["Alice", "Bob", "Charlie"]); + let score_array = Float32Array::from(vec![Some(95.5), None, Some(87.3)]); + let active_array = BooleanArray::from(vec![true, false, true]); + + RecordBatch::try_new( + schema, + vec![ + Arc::new(id_array) as ArrayRef, + Arc::new(name_array) as ArrayRef, + Arc::new(score_array) as ArrayRef, + Arc::new(active_array) as ArrayRef, + ], + ) + .unwrap() + } + + fn create_vector_batch() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "embedding", + DataType::FixedSizeList( + Arc::new(Field::new("item", DataType::Float32, true)), + 1024, + ), + false, + ), + ])); + + let id_array = Int32Array::from(vec![1, 2]); + + // Create vectors for 2 rows, each with 1024 elements + let mut vector_data = vec![]; + for row in 0..2 { + for i in 0..1024 { + vector_data.push((row * 1024 + i) as f32 * 0.001); + } + } + let values = Float32Array::from(vector_data); + let list_array = FixedSizeListArray::new( + Arc::new(Field::new("item", DataType::Float32, true)), + 1024, + Arc::new(values), + None, + ); + + RecordBatch::try_new( + schema, + vec![ + Arc::new(id_array) as ArrayRef, + Arc::new(list_array) as ArrayRef, + ], + ) + .unwrap() + } + + #[test] + fn test_table_format() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let batch = create_test_batch(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + + let expected = concat!( + " id | name | score | active\n", + "----+---------+-------+--------\n", + " 1 | Alice | 95.5 | true \n", + " 2 | Bob | NULL | false \n", + " 3 | Charlie | 87.3 | true \n", + "(3 rows)\n", + ); + + assert_eq!(output, expected); + } + + #[test] + fn test_csv_format() { + let formatter = ResultFormatter::new(OutputFormat::Csv); + let batch = create_test_batch(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + + // Check CSV header + assert!(output.starts_with("id,name,score,active\n")); + + // Check data rows + assert!(output.contains("1,Alice,95.5,true")); + assert!(output.contains("2,Bob,\\N,false")); + assert!(output.contains("3,Charlie,87.3,true")); + } + + #[test] + fn test_json_format() { + let formatter = ResultFormatter::new(OutputFormat::Json); + let batch = create_test_batch(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + let json: serde_json::Value = serde_json::from_str(&output).unwrap(); + + assert!(json.is_array()); + let array = json.as_array().unwrap(); + assert_eq!(array.len(), 3); + + // Check first row + assert_eq!(array[0]["id"], 1); + assert_eq!(array[0]["name"], "Alice"); + assert_eq!(array[0]["score"], 95.5); + assert_eq!(array[0]["active"], true); + + // Check NULL handling + assert_eq!(array[1]["score"], serde_json::Value::Null); + } + + /// A timestamp renders as its value, not the `Debug` dump of a one-row array. + #[test] + fn test_table_renders_timestamp_value() { + let ts = arrow_array::TimestampMillisecondArray::from(vec![1_758_217_603_403]) + .with_timezone("UTC"); + let batch = + RecordBatch::try_from_iter(vec![("last_refresh", Arc::new(ts) as ArrayRef)]).unwrap(); + + let output = ResultFormatter::new(OutputFormat::Table) + .format(&QueryResult::SqlResult(SqlResult::Query(vec![batch]))) + .unwrap(); + + assert_eq!( + output, + " last_refresh \n--------------------------\n 2025-09-18T17:46:43.403Z\n(1 row)\n" + ); + } + + /// Arrow writes the exact decimal token; re-reading it through a + /// `serde_json::Value` would round it to the nearest double. + #[test] + fn test_json_preserves_exact_decimal_tokens() { + let amounts = + arrow_array::Decimal128Array::from(vec![123_456_789_012_345_678_901_234_567_890_i128]) + .with_precision_and_scale(30, 10) + .unwrap(); + let batch = RecordBatch::try_from_iter(vec![( + "amount", + Arc::new(amounts) as arrow_array::ArrayRef, + )]) + .unwrap(); + + let output = ResultFormatter::new(OutputFormat::Json) + .format(&QueryResult::SqlResult(SqlResult::Query(vec![batch]))) + .unwrap(); + + assert!( + output.contains("12345678901234567890.1234567890"), + "decimal token was rewritten: {output}" + ); + } + + /// The display path elides a long value and previews a list; a machine + /// format has to carry both whole. + #[test] + fn test_json_is_lossless_for_long_and_nested_values() { + let long = "x".repeat(80); + let listed = + arrow_array::ListArray::from_iter_primitive::([ + Some(vec![Some(1), Some(2), Some(3)]), + ]); + let batch = RecordBatch::try_from_iter(vec![ + ( + "note", + Arc::new(arrow_array::LargeStringArray::from(vec![long.as_str()])) + as arrow_array::ArrayRef, + ), + ("scores", Arc::new(listed) as arrow_array::ArrayRef), + ]) + .unwrap(); + + let output = ResultFormatter::new(OutputFormat::Json) + .format(&QueryResult::SqlResult(SqlResult::Query(vec![batch]))) + .unwrap(); + let json: serde_json::Value = serde_json::from_str(&output).unwrap(); + + assert_eq!(json[0]["note"], long); + assert_eq!(json[0]["scores"], serde_json::json!([1, 2, 3])); + } + + /// A narrow integer used to fall through to a debug dump of the sliced + /// array; `SHOW ERRORS` returns `row_offset` as one. + #[test] + fn test_json_renders_narrow_integers_as_numbers() { + let batch = arrow_array::record_batch!( + ("row_offset", UInt32, [1_u32, 2]), + ("attempt", UInt8, [3_u8, 4]) + ) + .unwrap(); + let output = ResultFormatter::new(OutputFormat::Json) + .format(&QueryResult::SqlResult(SqlResult::Query(vec![batch]))) + .unwrap(); + let json: serde_json::Value = serde_json::from_str(&output).unwrap(); + + assert_eq!(json[0]["row_offset"], 1); + assert_eq!(json[0]["attempt"], 3); + assert_eq!(json[1]["row_offset"], 2); + } + + #[test] + fn test_ndjson_format() { + let formatter = ResultFormatter::new(OutputFormat::Ndjson); + let batch = create_test_batch(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + let lines: Vec<&str> = output.trim().split('\n').collect(); + + assert_eq!(lines.len(), 3); + + // Parse each line as JSON + for line in lines.iter() { + let json: serde_json::Value = serde_json::from_str(line).unwrap(); + assert!(json.is_object()); + assert!(json["id"].is_number()); + assert!(json["name"].is_string()); + } + } + + #[test] + fn test_vector_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let batch = create_vector_batch(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + + // Check that vectors are abbreviated + assert!(output.contains("[0, 0.001, ...1022 more]")); + assert!(!output.contains("0.999")); // Should not show all values + } + + #[test] + fn test_empty_result() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = RecordBatch::new_empty(schema); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + + assert!(output.contains("(0 rows)")); + } + + #[test] + fn test_table_list_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let tables = vec![ + "users".to_string(), + "products".to_string(), + "orders".to_string(), + ]; + let result = QueryResult::TableList(tables); + + let output = formatter.format(&result).unwrap(); + + let expected = "List of relations + Tables +---------- + users + products + orders +(3 rows) +"; + + assert_eq!(output, expected); + } + + #[test] + fn test_table_list_detailed_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table).with_terminal_width(200); + let tables = vec![ + TableInfo { + name: "users".to_string(), + schema: Arc::new(Schema::empty()), + row_count: Some(1000), + size_bytes: Some(1024 * 1024), // 1 MB + num_indices: Some(2), + num_fragments: Some(1), + }, + TableInfo { + name: "products".to_string(), + schema: Arc::new(Schema::empty()), + row_count: Some(500), + size_bytes: Some(512 * 1024), // 512 KB + num_indices: None, + num_fragments: None, + }, + ]; + let result = QueryResult::TableListDetailed(tables); + + let output = formatter.format(&result).unwrap(); + + let expected = " List of relations + Name | Type | Rows | Size | Indices | Fragments +----------+-------+------+----------+---------+----------- + users | table | 1000 | 1.0 MB | 2 | 1 + products | table | 500 | 512.0 KB | | +(2 rows) +"; + + assert_eq!(output, expected); + } + + #[test] + fn test_index_list_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let indices = vec![ + IndexInfo { + name: "idx_users_email".to_string(), + table_name: "users".to_string(), + index_type: "IVF_PQ".to_string(), + columns: vec!["email".to_string()], + }, + IndexInfo { + name: "idx_products_name".to_string(), + table_name: "products".to_string(), + index_type: "BTREE".to_string(), + columns: vec!["name".to_string()], + }, + ]; + let result = QueryResult::IndexList(indices); + + let output = formatter.format(&result).unwrap(); + + let expected = " List of indices + Name | Type | Table +-------------------+--------+---------- + idx_users_email | IVF_PQ | users + idx_products_name | BTREE | products +(2 rows) +"; + + assert_eq!(output, expected); + } + + #[test] + fn test_csv_escaping() { + let formatter = ResultFormatter::new(OutputFormat::Csv); + let schema = Arc::new(Schema::new(vec![Field::new("text", DataType::Utf8, false)])); + + let array = StringArray::from(vec!["simple", "with,comma", "with\"quote", "with\nnewline"]); + + let batch = RecordBatch::try_new(schema, vec![Arc::new(array) as ArrayRef]).unwrap(); + + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + let output = formatter.format(&result).unwrap(); + + assert!(output.contains("simple")); + assert!(output.contains("\"with,comma\"")); + assert!(output.contains("\"with\"\"quote\"")); + assert!(output.contains("\"with\nnewline\"")); + } + + #[test] + fn test_csv_preserves_scalar_values() { + let long = "µ".repeat(300); + let binary = vec![0xab; 100]; + let batch = RecordBatch::try_from_iter(vec![ + ( + "long", + Arc::new(StringArray::from(vec![long.as_str()])) as ArrayRef, + ), + ( + "large", + Arc::new(arrow_array::LargeStringArray::from(vec![long.as_str()])), + ), + ( + "view", + Arc::new(arrow_array::StringViewArray::from(vec![long.as_str()])), + ), + ("small", Arc::new(Float64Array::from(vec![0.000123]))), + ("f32", Arc::new(Float32Array::from(vec![0.00693]))), + ( + "f64", + Arc::new(Float64Array::from(vec![1.2345678901234567])), + ), + ("literal_null", Arc::new(StringArray::from(vec!["NULL"]))), + ("null", Arc::new(StringArray::from(vec![None::<&str>]))), + ("empty", Arc::new(StringArray::from(vec![""]))), + ( + "binary", + Arc::new(BinaryArray::from(vec![binary.as_slice()])), + ), + ( + "decimal", + Arc::new( + arrow_array::Decimal128Array::from(vec![123456789012345678901234567890_i128]) + .with_precision_and_scale(30, 10) + .unwrap(), + ), + ), + ]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch], &mut output) + .unwrap(); + + let row = csv::Reader::from_reader(output.as_slice()) + .records() + .next() + .unwrap() + .unwrap(); + for index in 0..3 { + assert_eq!(&row[index], long); + } + assert_eq!(row[3].parse::().unwrap(), 0.000123); + assert_eq!( + row[4].parse::().unwrap().to_bits(), + 0.00693_f32.to_bits() + ); + assert_eq!( + row[5].parse::().unwrap().to_bits(), + 1.2345678901234567_f64.to_bits() + ); + assert_eq!(&row[6], "NULL"); + assert_eq!(&row[7], CSV_NULL_VALUE); + assert_eq!(&row[8], ""); + assert!(String::from_utf8(output) + .unwrap() + .contains(",NULL,\\N,\"\",")); + assert_eq!(&row[9], "ab".repeat(100)); + assert_eq!(&row[10], "12345678901234567890.1234567890"); + } + + #[test] + fn test_csv_preserves_nested_values() { + use arrow_array::builder::{ListBuilder, StringBuilder}; + use arrow_array::types::{Float16Type, Float32Type, UInt8Type}; + use arrow_array::Array; + + let mut tags = ListBuilder::new(StringBuilder::new()); + for value in [ + Some("a,b"), + Some("\"quoted\""), + Some("NULL"), + Some(""), + None, + ] { + tags.values().append_option(value); + } + tags.append(true); + let tags = tags.finish(); + let vector = FixedSizeListArray::from_iter_primitive::( + [Some( + (0..12) + .map(|i| Some(i as f32 + 0.000123)) + .collect::>(), + )], + 12, + ); + let small = ListArray::from_iter_primitive::([Some(vec![ + Some(half::f16::from_f32(0.00693)), + None, + ])]); + let bytes = ListArray::from_iter_primitive::([Some(vec![ + Some(0), + Some(255), + None, + ])]); + let multivector = ListArray::new( + Arc::new(Field::new("item", vector.data_type().clone(), true)), + arrow_buffer::OffsetBuffer::new(vec![0, 1].into()), + Arc::new(vector.clone()), + None, + ); + let special = ListArray::from_iter_primitive::([Some(vec![ + Some(f32::NAN), + Some(f32::INFINITY), + Some(f32::NEG_INFINITY), + None, + ])]); + let nested = arrow_array::StructArray::from(vec![( + Arc::new(Field::new("tags", tags.data_type().clone(), true)), + { + let mut values = ListBuilder::new(StringBuilder::new()); + values.values().append_value("NULL"); + values.values().append_null(); + values.append(true); + Arc::new(values.finish()) as ArrayRef + }, + )]); + let batch = RecordBatch::try_from_iter(vec![ + ("tags", Arc::new(tags) as ArrayRef), + ("vector", Arc::new(vector)), + ("f16", Arc::new(small)), + ("bytes", Arc::new(bytes)), + ("multivector", Arc::new(multivector)), + ("struct", Arc::new(nested)), + ("special", Arc::new(special)), + ]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch], &mut output) + .unwrap(); + let row = csv::Reader::from_reader(output.as_slice()) + .records() + .next() + .unwrap() + .unwrap(); + let values: Vec = row + .iter() + .map(|cell| serde_json::from_str(cell).unwrap()) + .collect(); + assert_eq!( + values[0], + serde_json::json!(["a,b", "\"quoted\"", "NULL", "", null]) + ); + assert_eq!(values[1].as_array().unwrap().len(), 12); + for (index, value) in values[1].as_array().unwrap().iter().enumerate() { + assert_eq!(value.as_f64().unwrap() as f32, index as f32 + 0.000123); + } + assert_eq!( + values[2][0].as_f64().unwrap() as f32, + half::f16::from_f32(0.00693).to_f32() + ); + assert!(values[2][1].is_null()); + assert_eq!(values[3], serde_json::json!([0, 255, null])); + assert_eq!(values[4], serde_json::json!([values[1]])); + assert_eq!(values[5], serde_json::json!({"tags": ["NULL", null]})); + assert_eq!(values[6], serde_json::json!(["NaN", "inf", "-inf", null])); + } + + #[test] + fn test_csv_distinguishes_nulls_from_empty_values() { + use arrow_array::types::{Float64Type, Int8Type}; + let dictionary = arrow_array::DictionaryArray::::try_new( + Int8Array::from(vec![Some(0), Some(1), None]), + Arc::new(StringArray::from(vec![None, Some("")])), + ) + .unwrap(); + let lists = ListArray::from_iter_primitive::([ + None, + Some(vec![]), + Some(vec![None]), + ]); + let batch = RecordBatch::try_from_iter(vec![ + ("null", Arc::new(arrow_array::NullArray::new(3)) as ArrayRef), + ("dictionary", Arc::new(dictionary)), + ("list", Arc::new(lists)), + ]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch], &mut output) + .unwrap(); + assert_eq!( + String::from_utf8(output).unwrap(), + "null,dictionary,list\n\\N,\\N,\\N\n\\N,\"\",[]\n\\N,\\N,[null]\n" + ); + } + + #[test] + fn test_csv_preserves_single_column_null_rows() { + let original = vec![ + Some("before"), + None, + Some(""), + Some("NULL"), + Some(r"\N"), + Some(r"\\N"), + Some(r"\path"), + Some("after"), + ]; + let batch = RecordBatch::try_from_iter(vec![( + "v", + Arc::new(StringArray::from(original.clone())) as ArrayRef, + )]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch], &mut output) + .unwrap(); + let rows = csv::Reader::from_reader(output.as_slice()) + .records() + .collect::, _>>() + .unwrap(); + assert_eq!(rows.len(), 8); + let values: Vec<_> = rows.iter().map(|row| &row[0]).collect(); + assert_eq!( + values, + ["before", r"\N", "", "NULL", r"\\N", r"\\\N", r"\\path", "after"] + ); + let decoded: Vec<_> = values + .iter() + .map(|&value| { + if value == CSV_NULL_VALUE { + None + } else if value.starts_with(r"\\") { + Some(&value[1..]) + } else { + Some(value) + } + }) + .collect(); + assert_eq!(decoded, original); + } + + #[test] + fn test_csv_preserves_nested_dictionary_nulls() { + use arrow_array::types::Int8Type; + use arrow_array::{Array, DictionaryArray, StructArray}; + + let dictionary = DictionaryArray::::try_new( + Int8Array::from(vec![Some(0), Some(1), None]), + Arc::new(StringArray::from(vec![None, Some("")])), + ) + .unwrap(); + let field = Arc::new(Field::new("item", dictionary.data_type().clone(), true)); + let list = ListArray::new( + field.clone(), + arrow_buffer::OffsetBuffer::new(vec![0, 3].into()), + Arc::new(dictionary.clone()), + None, + ); + let structs = StructArray::from(vec![(field, Arc::new(dictionary) as ArrayRef)]); + let struct_list = ListArray::new( + Arc::new(Field::new("item", structs.data_type().clone(), true)), + arrow_buffer::OffsetBuffer::new(vec![0, 3].into()), + Arc::new(structs), + None, + ); + let encoded_list = + DictionaryArray::::try_new(Int8Array::from(vec![0]), Arc::new(list.clone())) + .unwrap(); + let batch = RecordBatch::try_from_iter(vec![ + ("list", Arc::new(list) as ArrayRef), + ("structs", Arc::new(struct_list)), + ("encoded_list", Arc::new(encoded_list)), + ]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch], &mut output) + .unwrap(); + let row = csv::Reader::from_reader(output.as_slice()) + .records() + .next() + .unwrap() + .unwrap(); + assert_eq!(&row[0], r#"[null,"",null]"#); + assert_eq!(&row[1], r#"[{"item":null},{"item":""},{"item":null}]"#); + assert_eq!(&row[2], r#"[null,"",null]"#); + } + + #[test] + fn test_csv_escapes_headers_and_carriage_returns_across_batches() { + let batch = RecordBatch::try_from_iter(vec![ + ( + "with,comma", + Arc::new(StringArray::from(vec!["with\rcarriage return"])) as ArrayRef, + ), + ( + "with\"quote", + Arc::new(StringArray::from(vec!["with\"quote"])), + ), + ( + "with\nnewline", + Arc::new(StringArray::from(vec!["with\nnewline"])), + ), + ]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch.slice(0, 0), batch.clone(), batch], &mut output) + .unwrap(); + let mut reader = csv::Reader::from_reader(output.as_slice()); + assert_eq!( + reader.headers().unwrap(), + &csv::StringRecord::from(vec!["with,comma", "with\"quote", "with\nnewline"]) + ); + let rows = reader + .records() + .collect::, _>>() + .unwrap(); + assert_eq!(rows.len(), 2); + for row in rows { + assert_eq!( + row, + csv::StringRecord::from(vec![ + "with\rcarriage return", + "with\"quote", + "with\nnewline" + ]) + ); + } + } + + #[test] + fn test_table_preserves_small_float_precision() { + let batch = arrow_array::record_batch!(("small", Float64, [0.000123, 0.00693])).unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Table) + .with_terminal_width(200) + .format_record_batches(&[batch], &mut output) + .unwrap(); + let output = String::from_utf8(output).unwrap(); + assert!(output.contains("0.000123")); + assert!(output.contains("0.00693")); + } + + #[test] + fn test_format_bytes() { + assert_eq!(format_bytes(0), "0 B"); + assert_eq!(format_bytes(1023), "1023 B"); + assert_eq!(format_bytes(1024), "1.0 KB"); + assert_eq!(format_bytes(1536), "1.5 KB"); + assert_eq!(format_bytes(1024 * 1024), "1.0 MB"); + assert_eq!(format_bytes(1024 * 1024 * 1024), "1.0 GB"); + } + + #[test] + fn test_format_data_type() { + assert_eq!(format_data_type(&DataType::Boolean), "BOOLEAN"); + assert_eq!(format_data_type(&DataType::Int32), "INT"); + assert_eq!(format_data_type(&DataType::Float64), "DOUBLE"); + assert_eq!(format_data_type(&DataType::Utf8), "TEXT"); + assert_eq!( + format_data_type(&DataType::FixedSizeList( + Arc::new(Field::new("item", DataType::Float32, true)), + 128 + )), + "FLOAT[128]" + ); + } + + #[test] + fn test_sql_result_dml_insert() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let dml = DmlResult::new("foo", DmlOperation::Insert, 1, 3); + let result = QueryResult::SqlResult(SqlResult::Dml(dml)); + + let output = formatter.format(&result).unwrap(); + assert_eq!(output, "INSERT 1 row(s), version 3\n"); + } + + #[test] + fn test_sql_result_dml_delete() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let dml = DmlResult::new("bar", DmlOperation::Delete, 0, 4); + let result = QueryResult::SqlResult(SqlResult::Dml(dml)); + + let output = formatter.format(&result).unwrap(); + assert_eq!(output, "DELETE 0 row(s), version 4\n"); + } + + #[test] + fn test_sql_result_success() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let result = QueryResult::SqlResult(SqlResult::Success); + + let output = formatter.format(&result).unwrap(); + assert_eq!(output, "Success\n"); + } + + #[test] + fn test_table_info_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("email", DataType::Utf8, false), + Field::new( + "created_at", + DataType::Timestamp(arrow_schema::TimeUnit::Microsecond, None), + false, + ), + Field::new("score", DataType::Float64, true), + ])); + + let table_info = TableInfo { + name: "users".to_string(), + schema, + row_count: Some(1500), + size_bytes: Some(2 * 1024 * 1024), // 2 MB + num_indices: Some(3), + num_fragments: Some(2), + }; + + let result = QueryResult::TableInfo(table_info); + let output = formatter.format(&result).unwrap(); + + let expected = " Table \"users\" + Column | Type | Nullable +------------+-----------+---------- + id | INT | + email | TEXT | + created_at | TIMESTAMP | + score | DOUBLE | YES + +Rows: 1500 +Size: 2.0 MB +"; + + assert_eq!(output, expected); + } + + #[test] + fn test_data_type_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table); + + struct TestCase { + name: &'static str, + field: Field, + data: ArrayRef, + expected_values: Vec<&'static str>, + } + + let test_cases = vec![ + TestCase { + name: "timestamp", + field: Field::new( + "ts", + DataType::Timestamp(arrow_schema::TimeUnit::Microsecond, None), + false, + ), + data: Arc::new(arrow_array::TimestampMicrosecondArray::from(vec![ + 1609459200000000, // 2021-01-01 00:00:00 UTC + 1625097600000000, // 2021-07-01 00:00:00 UTC + ])) as ArrayRef, + expected_values: vec!["2021-01-01", "2021-07-01"], + }, + TestCase { + name: "date", + field: Field::new("date", DataType::Date64, false), + data: Arc::new(arrow_array::Date64Array::from(vec![ + 1622505600000, // 2021-06-01 + 1622592000000, // 2021-06-02 + ])) as ArrayRef, + expected_values: vec!["2021-06-01", "2021-06-02"], + }, + TestCase { + name: "largeutf8", + field: Field::new("text", DataType::LargeUtf8, false), + data: Arc::new(arrow_array::LargeStringArray::from(vec![ + "Hello, World!", + "Large UTF-8 String", + ])) as ArrayRef, + expected_values: vec!["Hello, World!", "Large UTF-8 String"], + }, + TestCase { + name: "utf8view", + field: Field::new("view", DataType::Utf8View, false), + data: Arc::new(arrow_array::StringViewArray::from(vec![ + "View String 1", + "View String 2", + ])) as ArrayRef, + expected_values: vec!["View String 1", "View String 2"], + }, + TestCase { + name: "struct", + field: Field::new( + "data", + DataType::Struct( + vec![ + Field::new("name", DataType::Utf8, false), + Field::new("age", DataType::Int32, false), + ] + .into(), + ), + false, + ), + data: Arc::new(arrow_array::StructArray::from(vec![ + ( + Arc::new(Field::new("name", DataType::Utf8, false)), + Arc::new(StringArray::from(vec!["Alice", "Bob"])) as ArrayRef, + ), + ( + Arc::new(Field::new("age", DataType::Int32, false)), + Arc::new(Int32Array::from(vec![30, 25])) as ArrayRef, + ), + ])) as ArrayRef, + expected_values: vec!["{name: Alice, age: 30}", "{name: Bob, age: 25}"], + }, + ]; + + for test_case in test_cases { + let schema = Arc::new(Schema::new(vec![test_case.field])); + let batch = RecordBatch::try_new(schema, vec![test_case.data]).unwrap(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + let output = formatter.format(&result).unwrap(); + + for expected in test_case.expected_values { + assert!( + output.contains(expected), + "Test case '{}' failed: expected output to contain '{}', but got:\n{}", + test_case.name, + expected, + output + ); + } + } + } + + #[test] + fn marked_columns_render_in_full() { + let formatter = ResultFormatter::new(OutputFormat::Table).with_terminal_width(500); + let long_string = format!("j1_{}", "a".repeat(300)); + + let schema = Arc::new(Schema::new(vec![ + Field::new("job_id", DataType::Utf8, false), + Field::new("state", DataType::Utf8, false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec![long_string.as_str()])) as ArrayRef, + Arc::new(StringArray::from(vec![long_string.as_str()])) as ArrayRef, + ], + ) + .unwrap(); + + let marked = mark_no_truncate(SqlResult::Query(vec![batch]), &["job_id"]); + let output = formatter.format(&QueryResult::SqlResult(marked)).unwrap(); + + assert!( + output.contains(&long_string), + "a marked column must render in full: {output}" + ); + assert!( + output.contains("...(303 chars)"), + "an unmarked column must still be abbreviated: {output}" + ); + } + + fn job_ids(result: &SqlResult) -> Vec { + let SqlResult::Query(batches) = result else { + panic!("expected a query result"); + }; + batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + + #[test] + fn taking_rows_cuts_across_batch_boundaries() { + let first = arrow_array::record_batch!(("job_id", Int32, [1, 2, 3])).unwrap(); + let second = arrow_array::record_batch!(("job_id", Int32, [4, 5, 6])).unwrap(); + let batches = vec![first, second]; + + assert_eq!(row_count(&SqlResult::Query(batches.clone())), 6); + + // A cut inside the second batch keeps the first whole and slices the + // second; a limit at or past the total is a no-op. + let capped = take_rows(SqlResult::Query(batches.clone()), 4); + assert_eq!(job_ids(&capped), vec![1, 2, 3, 4]); + assert_eq!( + job_ids(&take_rows(SqlResult::Query(batches.clone()), 6)), + vec![1, 2, 3, 4, 5, 6] + ); + assert_eq!( + job_ids(&take_rows(SqlResult::Query(batches), 99)), + vec![1, 2, 3, 4, 5, 6] + ); + } + + #[test] + fn taking_rows_leaves_non_query_results_alone() { + assert!(matches!( + take_rows(SqlResult::Success, 0), + SqlResult::Success + )); + assert_eq!(row_count(&SqlResult::Success), 0); + } + + #[test] + fn test_string_elision() { + let formatter = ResultFormatter::new(OutputFormat::Table); + + // Create a long string that should be elided + let long_string = "a".repeat(100); + let short_string = "short string"; + + let schema = Arc::new(Schema::new(vec![ + Field::new("short", DataType::Utf8, false), + Field::new("long", DataType::Utf8, false), + Field::new("long_large", DataType::LargeUtf8, false), + ])); + + let short_array = StringArray::from(vec![short_string]); + let long_array = StringArray::from(vec![long_string.as_str()]); + let long_large_array = arrow_array::LargeStringArray::from(vec![long_string.as_str()]); + + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(short_array) as ArrayRef, + Arc::new(long_array) as ArrayRef, + Arc::new(long_large_array) as ArrayRef, + ], + ) + .unwrap(); + + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + let output = formatter.format(&result).unwrap(); + + // Short string should appear in full + assert!(output.contains(short_string)); + + // Long strings should be truncated with char count + assert!(output.contains("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...(100 chars)")); + assert!(!output.contains(&long_string)); // Full string should not appear + } + + #[test] + fn test_string_truncation_with_multibyte_utf8() { + let formatter = ResultFormatter::new(OutputFormat::Table); + + // The en-dash '–' is 3 bytes in UTF-8. Place it so byte index 50 falls + // inside the character, which would panic with naive &value[..50]. + // 48 ASCII bytes + '–' (3 bytes) + padding = well over 50 bytes + let multibyte_string = format!("{}{}", "x".repeat(48), "–".repeat(20)); + + let schema = Arc::new(Schema::new(vec![ + Field::new("text", DataType::Utf8, false), + Field::new("text_large", DataType::LargeUtf8, false), + Field::new("text_view", DataType::Utf8View, false), + ])); + + let utf8_array = StringArray::from(vec![multibyte_string.as_str()]); + let large_array = arrow_array::LargeStringArray::from(vec![multibyte_string.as_str()]); + let view_array = arrow_array::StringViewArray::from(vec![multibyte_string.as_str()]); + + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(utf8_array) as ArrayRef, + Arc::new(large_array) as ArrayRef, + Arc::new(view_array) as ArrayRef, + ], + ) + .unwrap(); + + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + let output = formatter.format(&result).unwrap(); + + // Should not panic, and should contain truncation indicator + // 48 ASCII chars + 20 en-dashes = 68 chars total + assert!(output.contains("...(68 chars)")); + // The truncated prefix should end at a char boundary (48 x's, not mid en-dash) + assert!(output.contains(&"x".repeat(48))); + } + + #[test] + fn test_struct_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table).with_terminal_width(200); + + // Create a struct with multiple fields + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "user_info", + DataType::Struct( + vec![ + Field::new("name", DataType::Utf8, false), + Field::new("age", DataType::Int32, false), + Field::new("email", DataType::Utf8, true), + ] + .into(), + ), + false, + ), + ])); + + let id_array = Int32Array::from(vec![1, 2]); + let name_array = StringArray::from(vec!["Alice", "Bob"]); + let age_array = Int32Array::from(vec![30, 25]); + let email_array = StringArray::from(vec![Some("alice@example.com"), None]); + + let struct_array = arrow_array::StructArray::from(vec![ + ( + Arc::new(Field::new("name", DataType::Utf8, false)), + Arc::new(name_array) as ArrayRef, + ), + ( + Arc::new(Field::new("age", DataType::Int32, false)), + Arc::new(age_array) as ArrayRef, + ), + ( + Arc::new(Field::new("email", DataType::Utf8, true)), + Arc::new(email_array) as ArrayRef, + ), + ]); + + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(id_array) as ArrayRef, + Arc::new(struct_array) as ArrayRef, + ], + ) + .unwrap(); + + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + let output = formatter.format(&result).unwrap(); + + // Check the exact literal output for proper struct formatting + let expected = " id | user_info +----+-------------------------------------------------- + 1 | {name: Alice, age: 30, email: alice@example.com} + 2 | {name: Bob, age: 25, email: NULL} +(2 rows) +"; + + assert_eq!(output, expected); + } + + #[test] + fn test_index_list_detailed_formatting() { + // Pin a wide terminal so the table renders columnar ("hotdog") rather + // than auto-expanding ("hamburger") in a narrow terminal — keeps the + // golden output independent of the ambient terminal width. + let formatter = ResultFormatter::new(OutputFormat::Table).with_terminal_width(200); + let indices = vec![ + ( + IndexInfo { + name: "idx_embeddings".to_string(), + table_name: "documents".to_string(), + index_type: "IVF_PQ".to_string(), + columns: vec!["embedding".to_string()], + }, + Some(IndexStats { + num_indexed_rows: 10000, + num_unindexed_rows: 500, + distance_type: Some("L2".to_string()), + }), + ), + ( + IndexInfo { + name: "idx_created_at".to_string(), + table_name: "documents".to_string(), + index_type: "BTREE".to_string(), + columns: vec!["created_at".to_string()], + }, + None, + ), + ]; + let result = QueryResult::IndexListDetailed(indices); + + let output = formatter.format(&result).unwrap(); + + let expected = " List of relations + Name | Type | Distance | Indexed Rows | Unindexed Rows | Table +----------------+--------+----------+--------------+----------------+----------- + idx_embeddings | IVF_PQ | L2 | 10000 | 500 | documents + idx_created_at | BTREE | | | | documents +(2 rows) +"; + + assert_eq!(output, expected); + } +} diff --git a/rust/lancedb/cli/src/lib.rs b/rust/lancedb/cli/src/lib.rs new file mode 100644 index 000000000..46a32122e --- /dev/null +++ b/rust/lancedb/cli/src/lib.rs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +pub mod auth; +pub mod cli; +pub mod client; +pub mod dml_result; +pub mod formatter; +pub mod mocks; +pub mod profile; +pub mod server_config; +pub mod sql_executor; +pub mod table_writer; + +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); +pub use cli::{run, Args, Commands}; +pub(crate) fn format_host_port(host: &str, port: impl std::fmt::Display) -> String { + match host.parse::() { + Ok(std::net::IpAddr::V6(_)) => format!("[{host}]:{port}"), + _ => format!("{host}:{port}"), + } +} + +pub(crate) fn lancedb_client_config( + tls: &server_config::TlsOptions, + authentication: &server_config::Authentication, +) -> Option { + if tls == &server_config::TlsOptions::default() + && matches!(authentication, server_config::Authentication::ApiKey(_)) + { + return None; + } + let mut config = lancedb::remote::ClientConfig::default(); + if tls != &server_config::TlsOptions::default() { + config.tls_config = Some(lancedb::remote::TlsConfig { + ssl_ca_cert: tls.ca_cert.clone(), + cert_file: tls.client_cert.clone(), + key_file: tls.client_key.clone(), + ..Default::default() + }); + } + if !matches!(authentication, server_config::Authentication::ApiKey(_)) { + config.header_provider = Some(std::sync::Arc::new(authentication.clone())); + } + Some(config) +} + +static BUILD_VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new(); +/// Set the version displayed by shared command handlers when embedded in another binary. +pub fn set_build_version(version: &'static str) { + let _ = BUILD_VERSION.set(version); +} +pub fn build_version() -> &'static str { + BUILD_VERSION.get().copied().unwrap_or(VERSION) +} diff --git a/rust/lancedb/cli/src/main.rs b/rust/lancedb/cli/src/main.rs new file mode 100644 index 000000000..01f65e386 --- /dev/null +++ b/rust/lancedb/cli/src/main.rs @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use clap::Parser; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let _ = rustls::crypto::ring::default_provider().install_default(); + lancedb_cli::run(lancedb_cli::Args::parse()).await +} diff --git a/rust/lancedb/cli/src/mocks.rs b/rust/lancedb/cli/src/mocks.rs new file mode 100644 index 000000000..ac8a66e7b --- /dev/null +++ b/rust/lancedb/cli/src/mocks.rs @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/// Mock implementations for testing +#[cfg(test)] +pub mod test_mocks { + use crate::sql_executor::{SqlQueryExecutor, SqlResult}; + use anyhow::Result; + use arrow_array::RecordBatch; + use arrow_schema::{DataType, Field, Schema}; + use async_trait::async_trait; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + + /// Mock SQL executor for testing + pub struct MockSqlExecutor { + pub is_connected: bool, + pub queries: Arc>>, + pub query_results: HashMap>, + /// URLs passed to `connect`, in call order. + pub connected_urls: Arc>>, + } + + impl Default for MockSqlExecutor { + fn default() -> Self { + Self::new() + } + } + + impl MockSqlExecutor { + pub fn new() -> Self { + Self { + is_connected: false, + queries: Arc::new(Mutex::new(Vec::new())), + query_results: HashMap::new(), + connected_urls: Arc::new(Mutex::new(Vec::new())), + } + } + + pub fn set_query_result(&mut self, query: &str, result: Vec) { + self.query_results.insert(query.to_string(), result); + } + + pub fn get_executed_queries(&self) -> Vec { + self.queries.lock().unwrap().clone() + } + + pub fn get_connected_urls(&self) -> Vec { + self.connected_urls.lock().unwrap().clone() + } + } + + #[async_trait] + impl SqlQueryExecutor for MockSqlExecutor { + async fn execute_query(&mut self, query: &str) -> Result { + self.queries.lock().unwrap().push(query.to_string()); + + if let Some(result) = self.query_results.get(query) { + Ok(SqlResult::Query(result.clone())) + } else { + // Return empty result by default + Ok(SqlResult::Query(vec![])) + } + } + + async fn is_connected(&self) -> bool { + self.is_connected + } + + fn connection_info(&self) -> Option { + if self.is_connected { + Some("Mock SQL connection".to_string()) + } else { + None + } + } + + async fn connect(&mut self, server_url: &str) -> Result<()> { + self.connected_urls + .lock() + .unwrap() + .push(server_url.to_string()); + self.is_connected = true; + Ok(()) + } + + fn set_database(&mut self, _database: String) { + // Mock implementation - no-op + } + } + + /// Helper function to create a simple test schema + pub fn create_test_schema() -> Arc { + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("name", DataType::Utf8, false), + Field::new("value", DataType::Float64, true), + ])) + } + + /// Helper function to create test RecordBatch + pub fn create_test_batch() -> RecordBatch { + use arrow_array::{Float64Array, Int64Array, StringArray}; + + let id_array = Int64Array::from(vec![1, 2, 3]); + let name_array = StringArray::from(vec!["Alice", "Bob", "Charlie"]); + let value_array = Float64Array::from(vec![Some(10.5), None, Some(20.0)]); + + RecordBatch::try_new( + create_test_schema(), + vec![ + Arc::new(id_array), + Arc::new(name_array), + Arc::new(value_array), + ], + ) + .unwrap() + } +} diff --git a/rust/lancedb/cli/src/profile.rs b/rust/lancedb/cli/src/profile.rs new file mode 100644 index 000000000..55e854c68 --- /dev/null +++ b/rust/lancedb/cli/src/profile.rs @@ -0,0 +1,494 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::borrow::Cow; +use std::io::{self, Write}; + +use anyhow::{anyhow, Result}; +use clap::{Args, Subcommand}; +use rustyline::highlight::Highlighter; +use rustyline::{Editor, Helper}; + +use crate::server_config::{Config, Profile}; + +#[derive(Args, Debug)] +pub struct ProfileArgs { + #[command(subcommand)] + pub command: ProfileCommand, +} + +/// The settable fields of a profile, shared by `create` and `edit`. +/// +/// `create` writes them all; `edit` applies only the ones that were passed. +#[derive(Args, Debug, Default)] +pub struct ProfileFields { + /// SQL server URL (Flight SQL endpoint), as host:port or grpc(s)://host:port + #[arg(long)] + pub sql_server_url: Option, + + /// HTTP server URL (REST endpoint), as host:port or http(s)://host:port + #[arg(long)] + pub http_server_url: Option, + + /// API key for authentication + #[arg(long, conflicts_with = "oidc_access_token_file")] + pub api_key: Option, + + /// Path to a file containing an OIDC access token + #[arg(long, value_name = "PATH", conflicts_with = "api_key")] + pub oidc_access_token_file: Option, + + /// Default database name + #[arg(long, short)] + pub database: Option, + + /// Azure storage account name for Azure-backed databases + #[arg(long)] + pub azure_storage_account_name: Option, + + /// Path to a PEM CA certificate trusted in addition to the platform roots + #[arg(long, value_name = "PATH")] + pub ca_cert: Option, + + /// Path to a PEM client certificate presented for mTLS + #[arg(long, value_name = "PATH")] + pub client_cert: Option, + + /// Path to the PKCS#8 PEM private key for the client certificate + #[arg(long, value_name = "PATH")] + pub client_key: Option, +} + +impl ProfileFields { + /// Whether any field was supplied, which is what makes `create` + /// non-interactive. Destructured so a new field cannot be forgotten here. + fn any_set(&self) -> bool { + let Self { + sql_server_url, + http_server_url, + api_key, + oidc_access_token_file, + database, + azure_storage_account_name, + ca_cert, + client_cert, + client_key, + } = self; + [ + sql_server_url, + http_server_url, + api_key, + oidc_access_token_file, + database, + azure_storage_account_name, + ca_cert, + client_cert, + client_key, + ] + .iter() + .any(|field| field.is_some()) + } +} + +impl From<&ProfileFields> for Profile { + fn from(fields: &ProfileFields) -> Self { + Self { + sql_server_url: fields.sql_server_url.clone(), + http_server_url: fields.http_server_url.clone(), + api_key: fields.api_key.clone(), + oidc_access_token_file: fields.oidc_access_token_file.clone(), + oidc: None, + database: fields.database.clone(), + azure_storage_account_name: fields.azure_storage_account_name.clone(), + ca_cert: fields.ca_cert.clone(), + client_cert: fields.client_cert.clone(), + client_key: fields.client_key.clone(), + } + } +} + +#[derive(Subcommand, Debug)] +pub enum ProfileCommand { + /// List all configured profiles + List, + + /// Show details of a specific profile + Show { + /// Name of the profile to show (uses default if not specified) + name: Option, + }, + + /// Create a new profile (interactive by default) + Create { + /// Name for the new profile + name: String, + + #[command(flatten)] + fields: ProfileFields, + }, + + /// Set the default profile + #[command(name = "set")] + SetDefault { + /// Name of the profile to set as default + name: String, + }, + + /// Delete a profile + Delete { + /// Name of the profile to delete + name: String, + }, + + /// Edit an existing profile + Edit { + /// Name of the profile to edit + name: String, + + #[command(flatten)] + fields: ProfileFields, + }, +} + +pub async fn run_profile_command(args: ProfileArgs) -> Result<()> { + match args.command { + ProfileCommand::List => list_profiles(), + ProfileCommand::Show { name } => show_profile(name), + ProfileCommand::Create { name, fields } => { + // If any flags are provided, use non-interactive mode + if fields.any_set() { + create_profile(&name, Profile::from(&fields)) + } else { + create_profile_interactive(&name) + } + } + ProfileCommand::SetDefault { name } => set_default_profile(&name), + ProfileCommand::Delete { name } => delete_profile(&name), + ProfileCommand::Edit { name, fields } => edit_profile(&name, Profile::from(&fields)), + } +} + +fn list_profiles() -> Result<()> { + let config = Config::load_default()?; + let default_profile = config.default_profile.as_deref().unwrap_or("local"); + + println!("Configured profiles:"); + + // Always show "local" as it's built-in + let is_default = default_profile == "local"; + let default_marker = if is_default { "*" } else { " " }; + let in_config = if config.profiles.contains_key("local") { + "" + } else { + " [built-in]" + }; + println!(" {} local{}", default_marker, in_config); + + // Show configured profiles + let mut profile_names: Vec<_> = config.profiles.keys().collect(); + profile_names.sort(); + + for name in profile_names { + if name == "local" { + continue; // Already shown above + } + let is_default = default_profile == name; + let default_marker = if is_default { "*" } else { " " }; + println!(" {} {}", default_marker, name); + } + + if config.profiles.is_empty() + || (config.profiles.len() == 1 && config.profiles.contains_key("local")) + { + println!(); + println!("No custom profiles configured. Use 'lancedb profile create ' to add one."); + } + + Ok(()) +} + +fn show_profile(name: Option) -> Result<()> { + let config = Config::load_default()?; + let profile_name = name + .as_deref() + .or(config.default_profile.as_deref()) + .unwrap_or("local"); + + let profile = config.get_profile(Some(profile_name)); + let is_builtin = !config.profiles.contains_key(profile_name) && profile_name == "local"; + + let builtin_marker = if is_builtin { " [built-in]" } else { "" }; + println!("Profile: {}{}", profile_name, builtin_marker); + println!( + " sql_server_url: {}", + profile.sql_server_url.as_deref().unwrap_or("") + ); + println!( + " http_server_url: {}", + profile.http_server_url.as_deref().unwrap_or("") + ); + println!( + " api_key: {}", + profile + .api_key + .as_ref() + .map(|_| "********") + .unwrap_or("") + ); + println!( + " oidc_access_token_file: {}", + profile + .oidc_access_token_file + .as_deref() + .unwrap_or("") + ); + if let Some(oidc) = &profile.oidc { + println!(" oidc: {}", toml::to_string(oidc)?); + } + println!( + " database: {}", + profile.database.as_deref().unwrap_or("") + ); + println!( + " azure_storage_account_name: {}", + profile + .azure_storage_account_name + .as_deref() + .unwrap_or("") + ); + println!( + " ca_cert: {}", + profile.ca_cert.as_deref().unwrap_or("") + ); + println!( + " client_cert: {}", + profile.client_cert.as_deref().unwrap_or("") + ); + println!( + " client_key: {}", + profile.client_key.as_deref().unwrap_or("") + ); + + Ok(()) +} + +fn create_profile(name: &str, profile: Profile) -> Result<()> { + let mut config = Config::load_default()?; + + if config.profiles.contains_key(name) { + return Err(anyhow!( + "Profile '{}' already exists. Use 'lancedb profile edit {}' to modify it.", + name, + name + )); + } + + config.set_profile(name, profile); + config.save_default()?; + + println!("Created profile '{}'", name); + Ok(()) +} + +fn create_profile_interactive(name: &str) -> Result<()> { + let mut config = Config::load_default()?; + + if config.profiles.contains_key(name) { + return Err(anyhow!( + "Profile '{}' already exists. Use 'lancedb profile edit {}' to modify it.", + name, + name + )); + } + + println!("Creating profile '{}'", name); + println!("Press Enter to skip optional fields."); + println!(); + + let sql_server_url = + prompt_optional("SQL server URL (host:port, or grpcs://host:port for TLS)")?; + let http_server_url = + prompt_optional("HTTP server URL (host:port, or https://host:port for TLS)")?; + let api_key = prompt_secret("API key")?; + let oidc_access_token_file = if api_key.is_none() { + prompt_optional("OIDC access token file")? + } else { + None + }; + let database = prompt_optional("Default database")?; + let azure_storage_account_name = prompt_optional("Azure storage account name")?; + let ca_cert = prompt_optional("CA certificate path (PEM, for a private CA)")?; + let client_cert = prompt_optional("Client certificate path (PEM, for mTLS)")?; + let client_key = prompt_optional("Client key path (PKCS#8 PEM, for mTLS)")?; + + let profile = Profile { + sql_server_url, + http_server_url, + api_key, + oidc_access_token_file, + oidc: None, + database, + azure_storage_account_name, + ca_cert, + client_cert, + client_key, + }; + config.set_profile(name, profile); + config.save_default()?; + + println!(); + println!("Created profile '{}'", name); + Ok(()) +} + +fn set_default_profile(name: &str) -> Result<()> { + let mut config = Config::load_default()?; + + // Verify profile exists (or is built-in "local") + if name != "local" && !config.profiles.contains_key(name) { + return Err(anyhow!( + "Profile '{}' does not exist. Use 'lancedb profile list' to see available profiles.", + name + )); + } + + // Persist the addresses when localhost is explicitly selected, so a later + // default SQL invocation can distinguish this choice from an unset endpoint. + if name == "local" && !config.profiles.contains_key(name) { + config.set_profile(name, Profile::local_default()); + } + config.set_default_profile(name); + config.save_default()?; + + println!("Set '{}' as the default profile", name); + Ok(()) +} + +fn delete_profile(name: &str) -> Result<()> { + if name == "local" { + return Err(anyhow!("Cannot delete the built-in 'local' profile")); + } + + let mut config = Config::load_default()?; + + if !config.profiles.contains_key(name) { + return Err(anyhow!("Profile '{}' does not exist", name)); + } + + config.remove_profile(name); + + // If we deleted the default profile, reset to "local" + if config.default_profile.as_deref() == Some(name) { + config.set_default_profile("local"); + println!("Default profile reset to 'local'"); + } + + config.save_default()?; + + println!("Deleted profile '{}'", name); + Ok(()) +} + +fn edit_profile(name: &str, updates: Profile) -> Result<()> { + let mut config = Config::load_default()?; + + // Get existing profile or create from built-in + let mut profile = if config.profiles.contains_key(name) { + config.profiles.get(name).cloned().unwrap() + } else if name == "local" { + Profile::local_default() + } else { + return Err(anyhow!( + "Profile '{}' does not exist. Use 'lancedb profile create {}' to create it.", + name, + name + )); + }; + + // Update only the fields that were provided + let Profile { + sql_server_url, + http_server_url, + api_key, + oidc_access_token_file, + oidc, + database, + azure_storage_account_name, + ca_cert, + client_cert, + client_key, + } = updates; + profile.sql_server_url = sql_server_url.or(profile.sql_server_url); + profile.http_server_url = http_server_url.or(profile.http_server_url); + if let Some(api_key) = api_key { + profile.oidc = None; + profile.api_key = Some(api_key); + profile.oidc_access_token_file = None; + } else if let Some(oidc_access_token_file) = oidc_access_token_file { + profile.oidc = None; + profile.api_key = None; + profile.oidc_access_token_file = Some(oidc_access_token_file); + } + if let Some(oidc) = oidc { + profile.api_key = None; + profile.oidc_access_token_file = None; + profile.oidc = Some(oidc); + } + profile.database = database.or(profile.database); + profile.azure_storage_account_name = + azure_storage_account_name.or(profile.azure_storage_account_name); + profile.ca_cert = ca_cert.or(profile.ca_cert); + profile.client_cert = client_cert.or(profile.client_cert); + profile.client_key = client_key.or(profile.client_key); + + config.set_profile(name, profile); + config.save_default()?; + + println!("Updated profile '{}'", name); + Ok(()) +} + +fn prompt_optional(field: &str) -> Result> { + print!("{}: ", field); + io::stdout().flush()?; + + let mut input = String::new(); + io::stdin().read_line(&mut input)?; + + let value = input.trim(); + if value.is_empty() { + Ok(None) + } else { + Ok(Some(value.to_string())) + } +} + +fn prompt_secret(field: &str) -> Result> { + struct MaskHelper; + impl Highlighter for MaskHelper { + fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> { + Cow::Owned("*".repeat(line.len())) + } + fn highlight_char(&self, _line: &str, _pos: usize, _forced: bool) -> bool { + true + } + } + impl rustyline::completion::Completer for MaskHelper { + type Candidate = String; + } + impl rustyline::hint::Hinter for MaskHelper { + type Hint = String; + } + impl rustyline::validate::Validator for MaskHelper {} + impl Helper for MaskHelper {} + + let mut editor = Editor::new()?; + editor.set_helper(Some(MaskHelper)); + let input = editor.readline(&format!("{}: ", field))?; + let value = input.trim(); + if value.is_empty() { + Ok(None) + } else { + Ok(Some(value.to_string())) + } +} diff --git a/rust/lancedb/cli/src/server_config.rs b/rust/lancedb/cli/src/server_config.rs new file mode 100644 index 000000000..eb483c44e --- /dev/null +++ b/rust/lancedb/cli/src/server_config.rs @@ -0,0 +1,1310 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use anyhow::{anyhow, bail, Context, Result}; +use clap::Args; +use directories::UserDirs; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::fs; +use std::io::Write; +#[cfg(unix)] +use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; +use std::path::{Path, PathBuf}; + +/// The default profile name used when no profile is specified +pub const DEFAULT_PROFILE: &str = "local"; + +/// Port assumed for a Flight SQL address that carries neither scheme nor port. +pub const DEFAULT_SQL_PORT: u16 = 10025; + +/// Port assumed for a REST address that carries neither scheme nor port. +pub const DEFAULT_HTTP_PORT: u16 = 10024; + +const DEFAULT_API_KEY: &str = "sk_localtest"; +const API_KEY_ENV: &str = "LANCEDB_API_KEY"; +const OIDC_ACCESS_TOKEN_ENV: &str = "LANCEDB_OIDC_ACCESS_TOKEN"; +const OIDC_ACCESS_TOKEN_FILE_ENV: &str = "LANCEDB_OIDC_ACCESS_TOKEN_FILE"; + +/// Authentication material selected for a CLI connection. +#[derive(Clone, PartialEq, Eq)] +pub enum Authentication { + ApiKey(String), + OidcAccessToken(String), + OidcAccessTokenFile(PathBuf), + ManagedOidc(std::sync::Arc), +} + +impl std::fmt::Debug for Authentication { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::ApiKey(_) => f.write_str("ApiKey()"), + Self::OidcAccessToken(_) => f.write_str("OidcAccessToken()"), + Self::OidcAccessTokenFile(path) => { + f.debug_tuple("OidcAccessTokenFile").field(path).finish() + } + Self::ManagedOidc(session) => f.debug_tuple("ManagedOidc").field(session).finish(), + } + } +} + +/// Transport scheme of a server address. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Scheme { + Http, + Https, +} + +impl Scheme { + pub fn as_str(&self) -> &'static str { + match self { + Self::Http => "http", + Self::Https => "https", + } + } + + /// Port to use when the address names this scheme but no port. + fn default_port(&self) -> u16 { + match self { + Self::Http => 80, + Self::Https => 443, + } + } +} + +impl std::fmt::Display for Scheme { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } +} + +/// A server address split into the parts needed to rebuild a connection URL. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Endpoint { + pub scheme: Scheme, + /// Host without IPv6 brackets, as it would appear in a certificate. + pub host: String, + pub port: u16, +} + +impl Endpoint { + /// `host:port`, bracketing IPv6 literals. + pub fn host_port(&self) -> String { + crate::format_host_port(&self.host, self.port) + } + + /// Full `scheme://host:port` URL. + pub fn url(&self) -> String { + format!("{}://{}", self.scheme, self.host_port()) + } + + pub fn is_tls(&self) -> bool { + self.scheme == Scheme::Https + } +} + +impl std::fmt::Display for Endpoint { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.url()) + } +} + +/// Parse a user-supplied REST address into scheme, host, and port. +/// +/// An explicit `https://` prefix is how a user asks for TLS; without a scheme +/// the address is assumed to be plaintext. `default_port` applies only when the +/// address names neither a scheme nor a port, so `https://host` still resolves +/// to 443 rather than to a LanceDB-specific default. +pub fn parse_endpoint(addr: &str, default_port: u16) -> Result { + parse_endpoint_with_schemes(addr, default_port, &["http", "https"]) +} + +/// Parse a user-supplied Flight SQL address, which additionally accepts the +/// gRPC scheme names. `grpc://` and `grpcs://` are aliases for `http://` and +/// `https://`: gRPC runs over the same HTTP/2 transport, and only the TLS +/// distinction reaches the connection. +pub fn parse_grpc_endpoint(addr: &str, default_port: u16) -> Result { + parse_endpoint_with_schemes(addr, default_port, &["http", "https", "grpc", "grpcs"]) +} + +fn parse_endpoint_with_schemes( + addr: &str, + default_port: u16, + accepted: &[&str], +) -> Result { + let addr = addr.trim(); + + let (scheme, rest, scheme_was_explicit) = match addr.split_once("://") { + Some((scheme, rest)) => { + let scheme = scheme.to_ascii_lowercase(); + if !accepted.contains(&scheme.as_str()) { + bail!( + "Unsupported scheme '{scheme}' in server address '{addr}'; expected one of {}", + accepted.join(", ") + ); + } + let scheme = match scheme.as_str() { + "https" | "grpcs" => Scheme::Https, + _ => Scheme::Http, + }; + (scheme, rest, true) + } + None => (Scheme::Http, addr, false), + }; + + // Drop any path, query, or fragment: only the authority is dialed. + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + if authority.is_empty() { + bail!("Server address '{addr}' is missing a host"); + } + + let (host, port) = split_host_port(authority, addr)?; + let port = port.unwrap_or(if scheme_was_explicit { + scheme.default_port() + } else { + default_port + }); + + Ok(Endpoint { scheme, host, port }) +} + +/// Split an authority into host and optional port, accepting bracketed IPv6 +/// (`[::1]:10025`) and bare IPv6 literals (`::1`). +fn split_host_port(authority: &str, addr: &str) -> Result<(String, Option)> { + let parse_port = |port: &str| -> Result { + port.parse::() + .with_context(|| format!("Invalid port '{port}' in server address '{addr}'")) + }; + + if let Some(rest) = authority.strip_prefix('[') { + let (host, rest) = rest + .split_once(']') + .ok_or_else(|| anyhow!("Unterminated IPv6 address in server address '{addr}'"))?; + let port = match rest { + "" => None, + _ => Some(parse_port(rest.strip_prefix(':').ok_or_else(|| { + anyhow!("Expected ':port' after IPv6 address in server address '{addr}'") + })?)?), + }; + return Ok((host.to_string(), port)); + } + + // More than one colon means a bare IPv6 literal; a port would require brackets. + match authority.split_once(':') { + Some((host, port)) if !port.contains(':') => { + Ok((host.to_string(), Some(parse_port(port)?))) + } + _ => Ok((authority.to_string(), None)), + } +} + +/// Client-side TLS material, shared by every transport the CLI dials. +/// +/// The two settings are independent: `ca_cert` decides whether the client +/// trusts the *server's* certificate, while `client_cert`/`client_key` are what +/// the client presents so the *server* can authenticate it (mTLS). A deployment +/// using a private CA for both directions needs both. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct TlsOptions { + /// PEM CA certificate trusted in addition to the platform roots. + pub ca_cert: Option, + /// PEM client certificate presented for mTLS. + pub client_cert: Option, + /// PKCS#8 PEM private key for `client_cert`. + pub client_key: Option, +} + +impl TlsOptions { + /// The client certificate and key, read from disk. `None` when no client + /// identity is configured. + pub fn read_client_identity(&self) -> Result, Vec)>> { + let (Some(cert), Some(key)) = (&self.client_cert, &self.client_key) else { + return Ok(None); + }; + let cert_pem = fs::read(cert) + .with_context(|| format!("Failed to read client certificate '{cert}'"))?; + let key_pem = + fs::read(key).with_context(|| format!("Failed to read client key '{key}'"))?; + Ok(Some((cert_pem, key_pem))) + } + + /// The CA certificate, read from disk. + pub fn read_ca_cert(&self) -> Result>> { + let Some(ca_cert) = &self.ca_cert else { + return Ok(None); + }; + let pem = fs::read(ca_cert) + .with_context(|| format!("Failed to read CA certificate '{ca_cert}'"))?; + Ok(Some(pem)) + } +} + +/// Resolved connection settings with guaranteed values. +/// +/// This is returned by `ConnectionArgs::resolve()` after applying +/// the precedence rules: CLI/env args > profile > defaults. +#[derive(Debug, Clone)] +pub struct ResolvedConnection { + pub sql_server_url: String, + pub http_server_url: String, + pub database: String, + pub authentication: Authentication, + pub azure_storage_account_name: Option, + pub tls: TlsOptions, + pub profile_name: String, +} + +/// Common connection arguments that can be embedded in command structs. +/// +/// Use `#[command(flatten)]` to embed these in your command's args struct. +#[derive(Args, Debug, Clone, Default)] +pub struct ConnectionArgs { + /// Connection profile to use (from ~/.lancedb/config.toml) + #[arg(short = 'p', long, value_name = "PROFILE")] + pub profile: Option, + + /// SQL Server URL (Flight SQL endpoint), as host:port or grpc(s)://host:port - overrides profile + #[arg(long, value_name = "URL")] + pub sql_server_url: Option, + + /// HTTP Server URL, as host:port or http(s)://host:port - overrides profile + #[arg(long, value_name = "URL")] + pub http_server_url: Option, + + /// Database name - overrides profile + #[arg(short = 'd', long)] + pub database: Option, + + /// API key - overrides profile and authentication environment variables + /// + /// Without explicit credential flags, environment precedence is LANCEDB_API_KEY, + /// LANCEDB_OIDC_ACCESS_TOKEN, then LANCEDB_OIDC_ACCESS_TOKEN_FILE. + #[arg(long, conflicts_with = "oidc_access_token_file")] + pub api_key: Option, + + /// File containing an OIDC access token - overrides profile and authentication environment variables + #[arg(long, value_name = "PATH", conflicts_with = "api_key")] + pub oidc_access_token_file: Option, + + /// Azure storage account name - overrides profile + #[arg(long, env = "AZURE_STORAGE_ACCOUNT_NAME")] + pub azure_storage_account_name: Option, + + /// Path to a PEM CA certificate that signed the server's TLS certificate, + /// trusted in addition to the platform roots - overrides profile + #[arg(long, value_name = "PATH", env = "LANCEDB_CA_CERT")] + pub ca_cert: Option, + + /// Path to a PEM client certificate to present for mTLS; requires + /// --client-key - overrides profile + #[arg(long, value_name = "PATH", env = "LANCEDB_CLIENT_CERT")] + pub client_cert: Option, + + /// Path to the PKCS#8 PEM private key for --client-cert - overrides profile + #[arg(long, value_name = "PATH", env = "LANCEDB_CLIENT_KEY")] + pub client_key: Option, +} + +/// The database a connection uses when none is configured: the system username. +pub fn default_database_name() -> String { + std::env::var("USER") + .or_else(|_| std::env::var("USERNAME")) + .unwrap_or_else(|_| "default".to_string()) +} + +impl ConnectionArgs { + /// Resolve connection settings from profile with a custom default database. + /// + /// Precedence: CLI/env args > profile > defaults + pub fn resolve(&self, default_database: Option<&str>) -> Result { + let config = Config::load_default()?; + self.resolve_with_config(&config, default_database) + } + + /// Resolve SQL only when an endpoint was supplied by a flag or saved + /// profile. The built-in localhost endpoint requires `--profile local`. + pub(crate) fn resolve_sql(&self) -> Result> { + self.resolve_sql_with_config(&Config::load_default()?) + } + + fn resolve_sql_with_config(&self, config: &Config) -> Result> { + let profile_name = self + .profile + .as_deref() + .or(config.default_profile.as_deref()) + .unwrap_or(DEFAULT_PROFILE); + let endpoint = self.sql_server_url.as_deref().or_else(|| { + config + .profiles + .get(profile_name) + .and_then(|profile| profile.sql_server_url.as_deref()) + }); + if let Some(endpoint) = endpoint { + if endpoint.trim().is_empty() { + bail!("Flight SQL endpoint cannot be empty"); + } + } else if self.profile.as_deref() != Some(DEFAULT_PROFILE) { + return Ok(None); + } + self.resolve_with_config(config, None).map(Some) + } + + fn resolve_with_config( + &self, + config: &Config, + default_database: Option<&str>, + ) -> Result { + // Determine the effective profile name + let profile_name = self + .profile + .clone() + .or_else(|| config.default_profile.clone()) + .unwrap_or_else(|| DEFAULT_PROFILE.to_string()); + + let profile = config.get_profile(self.profile.as_deref()); + let authentication = self.resolve_authentication(&profile, &profile_name)?; + + let sql_server_url = self + .sql_server_url + .clone() + .or(profile.sql_server_url) + .unwrap_or_else(|| "localhost:10025".to_string()); + + let http_server_url = self + .http_server_url + .clone() + .or(profile.http_server_url) + .unwrap_or_else(|| "localhost:10024".to_string()); + + let database = self + .database + .clone() + .or(profile.database) + .unwrap_or_else(|| { + default_database + .map(|s| s.to_string()) + .unwrap_or_else(default_database_name) + }); + + let azure_storage_account_name = self + .azure_storage_account_name + .clone() + .or(profile.azure_storage_account_name); + + // A client certificate is unusable without its key, so resolve the pair + // together rather than letting one side come from the profile and the + // other from a flag. + let (client_cert, client_key) = match (&self.client_cert, &self.client_key) { + (None, None) => (profile.client_cert, profile.client_key), + (cert, key) => (cert.clone(), key.clone()), + }; + if client_cert.is_some() != client_key.is_some() { + bail!("--client-cert and --client-key must be provided together"); + } + + let tls = TlsOptions { + ca_cert: self.ca_cert.clone().or(profile.ca_cert), + client_cert, + client_key, + }; + + Ok(ResolvedConnection { + sql_server_url, + http_server_url, + database, + authentication, + azure_storage_account_name, + tls, + profile_name, + }) + } + + fn resolve_authentication( + &self, + profile: &Profile, + profile_name: &str, + ) -> Result { + self.resolve_authentication_with_env(profile, profile_name, |name| std::env::var_os(name)) + } + + fn resolve_authentication_with_env( + &self, + profile: &Profile, + profile_name: &str, + getenv: impl Fn(&str) -> Option, + ) -> Result { + if self.api_key.is_some() && self.oidc_access_token_file.is_some() { + bail!("--api-key and --oidc-access-token-file are mutually exclusive"); + } + profile.validate_authentication()?; + + if let Some(api_key) = &self.api_key { + return Ok(Authentication::ApiKey(nonempty_secret(api_key, "API key")?)); + } + if let Some(path) = &self.oidc_access_token_file { + return Ok(Authentication::OidcAccessTokenFile(path.into())); + } + if let Some(api_key) = getenv(API_KEY_ENV) { + return Ok(Authentication::ApiKey(nonempty_os_secret( + api_key, + API_KEY_ENV, + )?)); + } + if let Some(token) = getenv(OIDC_ACCESS_TOKEN_ENV) { + return Ok(Authentication::OidcAccessToken(nonempty_os_secret( + token, + OIDC_ACCESS_TOKEN_ENV, + )?)); + } + if let Some(path) = getenv(OIDC_ACCESS_TOKEN_FILE_ENV) { + let path = path + .into_string() + .map_err(|_| anyhow!("{OIDC_ACCESS_TOKEN_FILE_ENV} is not valid UTF-8"))?; + return Ok(Authentication::OidcAccessTokenFile(path.into())); + } + if let Some(api_key) = &profile.api_key { + return Ok(Authentication::ApiKey(nonempty_secret(api_key, "API key")?)); + } + if let Some(path) = &profile.oidc_access_token_file { + return Ok(Authentication::OidcAccessTokenFile(path.into())); + } + if let Some(oidc) = &profile.oidc { + return Ok(Authentication::ManagedOidc(std::sync::Arc::new( + crate::auth::ManagedOidc::for_profile(profile_name, oidc.clone())?, + ))); + } + Ok(Authentication::ApiKey(DEFAULT_API_KEY.to_string())) + } +} + +fn nonempty_secret(value: &str, description: &str) -> Result { + if value.is_empty() { + bail!("{description} cannot be empty"); + } + Ok(value.to_string()) +} + +fn nonempty_os_secret(value: std::ffi::OsString, name: &str) -> Result { + let value = value + .into_string() + .map_err(|_| anyhow!("{name} is not valid UTF-8"))?; + nonempty_secret(&value, name) +} + +/// A connection profile for the LanceDB CLI +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct Profile { + /// SQL server URL (Flight SQL endpoint) + #[serde(skip_serializing_if = "Option::is_none")] + pub sql_server_url: Option, + /// HTTP server URL (REST endpoint) + #[serde(skip_serializing_if = "Option::is_none")] + pub http_server_url: Option, + /// API key for authentication + #[serde(skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Path to a file containing an OIDC access token. + #[serde(skip_serializing_if = "Option::is_none")] + pub oidc_access_token_file: Option, + /// Managed OAuth authentication using the LanceDB SDK. + #[serde(skip_serializing_if = "Option::is_none")] + pub oidc: Option, + /// Default database name + #[serde(skip_serializing_if = "Option::is_none")] + pub database: Option, + /// Azure storage account name for Azure-backed databases + #[serde(skip_serializing_if = "Option::is_none")] + pub azure_storage_account_name: Option, + /// Path to a PEM CA certificate trusted in addition to the platform roots + #[serde(skip_serializing_if = "Option::is_none")] + pub ca_cert: Option, + /// Path to a PEM client certificate presented for mTLS + #[serde(skip_serializing_if = "Option::is_none")] + pub client_cert: Option, + /// Path to the PKCS#8 PEM private key for `client_cert` + #[serde(skip_serializing_if = "Option::is_none")] + pub client_key: Option, +} + +impl Profile { + pub(crate) fn validate_authentication(&self) -> Result<()> { + if self.api_key.is_some() && self.oidc_access_token_file.is_some() { + bail!("profile cannot specify both api_key and oidc_access_token_file"); + } + if self.oidc.is_some() && (self.api_key.is_some() || self.oidc_access_token_file.is_some()) + { + bail!("profile cannot combine oidc with api_key or oidc_access_token_file"); + } + Ok(()) + } + + /// Create the built-in profile for a local SQL/HTTP deployment. + pub fn local_default() -> Self { + Self { + sql_server_url: Some("localhost:10025".to_string()), + http_server_url: Some("localhost:10024".to_string()), + api_key: None, + oidc_access_token_file: None, + oidc: None, + database: None, + azure_storage_account_name: None, + ca_cert: None, + client_cert: None, + client_key: None, + } + } +} + +/// Configuration file structure for ~/.lancedb/config.toml +#[derive(Debug, Serialize, Deserialize)] +pub struct Config { + /// Data directory for LanceDB server + #[serde(skip_serializing_if = "Option::is_none")] + pub data_dir: Option, + + /// Default profile name to use when none is specified + #[serde(skip_serializing_if = "Option::is_none")] + pub default_profile: Option, + + /// Named connection profiles + #[serde(default, skip_serializing_if = "HashMap::is_empty")] + pub profiles: HashMap, +} + +impl Default for Config { + fn default() -> Self { + Self { + data_dir: None, + default_profile: Some(DEFAULT_PROFILE.to_string()), + profiles: HashMap::new(), + } + } +} + +fn create_config_directory(path: &Path) -> Result<()> { + let mut builder = fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + builder.mode(0o700); + builder + .create(path) + .with_context(|| format!("Failed to create config directory: {:?}", path)) +} + +impl Config { + /// The database a client uses without `--database`: the default profile's, else the username. + pub fn default_database(&self) -> String { + self.get_profile(None) + .database + .unwrap_or_else(default_database_name) + } + + /// Get the default config file path (~/.lancedb/config.toml) + pub fn default_config_path() -> Result { + let user_dirs = + UserDirs::new().ok_or_else(|| anyhow::anyhow!("Could not determine home directory"))?; + + let config_dir = user_dirs.home_dir().join(".lancedb"); + Ok(config_dir.join("config.toml")) + } + + /// Get the default data directory path (~/.lancedb/databases) + pub fn default_data_dir() -> Result { + let user_dirs = + UserDirs::new().ok_or_else(|| anyhow::anyhow!("Could not determine home directory"))?; + + let data_dir = user_dirs.home_dir().join(".lancedb").join("databases"); + Ok(data_dir.to_string_lossy().to_string()) + } + + /// Load config from the default location, or return default config if not found + pub fn load_default() -> Result { + let config_path = Self::default_config_path()?; + + if !config_path.exists() { + return Ok(Self::default()); + } + + Self::load_from_path(&config_path) + } + + /// Load config from the default location, returning None if not found + pub fn load_default_optional() -> Result> { + let config_path = Self::default_config_path()?; + + if !config_path.exists() { + return Ok(None); + } + + Self::load_from_path(&config_path).map(Some) + } + + /// Load config from a specific path + pub fn load_from_path(path: &Path) -> Result { + let (config, unused) = Self::load_from_path_impl(path)?; + for unused_key in unused { + println!( + "While parsing {}, ignored unused configuration key: {}", + path.to_string_lossy(), + unused_key + ); + } + Ok(config) + } + + /// Load config and collect unused keys. Parse errors include a location + /// when available, without source text, values, or the original parser cause. + pub fn load_from_path_impl(path: &Path) -> Result<(Self, Vec)> { + let contents = fs::read_to_string(path) + .with_context(|| format!("Failed to read config file: {:?}", path))?; + + let mut unused = Vec::new(); + match serde_ignored::deserialize(toml::de::Deserializer::new(&contents), |path| { + unused.push(path.to_string()) + }) { + Err(err) => { + // Both Display and message() can contain credentials. Keep only + // the numeric location, and never attach the parser as a cause. + let location = err + .span() + .and_then(|span| contents.get(..span.start)) + .map(|prefix| { + let line = prefix.bytes().filter(|&b| b == b'\n').count() + 1; + let column = prefix.rsplit('\n').next().unwrap_or("").chars().count() + 1; + format!(" at line {line}, column {column}") + }) + .unwrap_or_default(); + bail!( + "Failed to parse config file: {path:?}{location}: invalid TOML or configuration value" + ) + } + Ok(config) => Ok((config, unused)), + } + } + + /// Save config to the default location. On Unix, restrict the app-owned + /// directory to mode 0700, including when it already exists. + pub fn save_default(&self) -> Result<()> { + let config_path = Self::default_config_path()?; + #[cfg(unix)] + { + let parent = config_path.parent().context("Config path has no parent")?; + create_config_directory(parent)?; + fs::set_permissions(parent, fs::Permissions::from_mode(0o700)) + .with_context(|| format!("Failed to restrict config directory: {:?}", parent))?; + } + self.save_to_path(&config_path) + } + + /// Atomically replace config at a specific path. On Unix, the new file is + /// mode 0600, even when replacing a permissive file. Newly created parent + /// directories are private; existing custom parent directories are unchanged. + pub fn save_to_path(&self, path: &Path) -> Result<()> { + let contents = toml::to_string_pretty(self).context("Failed to serialize config")?; + let parent = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + create_config_directory(parent)?; + + // tempfile creates Unix files with mode 0600 from the outset. Set it + // explicitly before writing secrets so an owner-masking umask also works. + let mut file = tempfile::NamedTempFile::new_in(parent) + .with_context(|| format!("Failed to create private config file in {:?}", parent))?; + #[cfg(unix)] + file.as_file() + .set_permissions(fs::Permissions::from_mode(0o600)) + .with_context(|| format!("Failed to restrict config file: {:?}", path))?; + file.write_all(contents.as_bytes()) + .with_context(|| format!("Failed to write config file: {:?}", path))?; + file.persist(path) + .map_err(|error| error.error) + .with_context(|| format!("Failed to replace config file: {:?}", path))?; + + Ok(()) + } + + /// Get a profile by name, falling back to built-in "local" profile + pub fn get_profile(&self, name: Option<&str>) -> Profile { + let profile_name = name + .map(|s| s.to_string()) + .or_else(|| self.default_profile.clone()) + .unwrap_or_else(|| DEFAULT_PROFILE.to_string()); + + self.profiles + .get(&profile_name) + .cloned() + .unwrap_or_else(|| { + if profile_name == DEFAULT_PROFILE { + Profile::local_default() + } else { + Profile::default() + } + }) + } + + /// Add or update a profile + pub fn set_profile(&mut self, name: &str, profile: Profile) { + self.profiles.insert(name.to_string(), profile); + } + + /// Remove a profile + pub fn remove_profile(&mut self, name: &str) -> Option { + self.profiles.remove(name) + } + + /// List all profile names + pub fn list_profiles(&self) -> Vec<&str> { + self.profiles.keys().map(|s| s.as_str()).collect() + } + + /// Set the default profile name + pub fn set_default_profile(&mut self, name: &str) { + self.default_profile = Some(name.to_string()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::tempdir; + + #[test] + fn sql_resolution_does_not_invent_an_endpoint() { + let args = ConnectionArgs { + api_key: Some("test-key".into()), + http_server_url: Some("http://api.example.com".into()), + ..Default::default() + }; + let mut config = Config::default(); + assert!(args.resolve_sql_with_config(&config).unwrap().is_none()); + config.set_profile("cloud", Profile::default()); + config.set_default_profile("cloud"); + assert!(args.resolve_sql_with_config(&config).unwrap().is_none()); + + let local = ConnectionArgs { + profile: Some("local".into()), + ..args + }; + assert_eq!( + local + .resolve_sql_with_config(&config) + .unwrap() + .unwrap() + .sql_server_url, + "localhost:10025" + ); + } + + #[test] + fn sql_resolution_uses_a_saved_endpoint_or_an_explicit_override() { + let args = ConnectionArgs { + api_key: Some("test-key".into()), + ..Default::default() + }; + let mut config = Config::default(); + config.set_profile( + "cloud", + Profile { + sql_server_url: Some("grpcs://sql.example.com:10025".into()), + ..Default::default() + }, + ); + config.set_default_profile("cloud"); + assert_eq!( + args.resolve_sql_with_config(&config) + .unwrap() + .unwrap() + .sql_server_url, + "grpcs://sql.example.com:10025" + ); + let override_args = ConnectionArgs { + sql_server_url: Some("localhost:12345".into()), + ..args + }; + assert_eq!( + override_args + .resolve_sql_with_config(&config) + .unwrap() + .unwrap() + .sql_server_url, + "localhost:12345" + ); + } + + #[test] + fn sql_resolution_rejects_an_empty_configured_endpoint() { + let args = ConnectionArgs { + sql_server_url: Some(" ".into()), + ..Default::default() + }; + let error = args + .resolve_sql_with_config(&Config::default()) + .unwrap_err(); + assert!(error + .to_string() + .contains("Flight SQL endpoint cannot be empty")); + } + + #[test] + fn test_parse_endpoint_defaults_to_plaintext() { + let endpoint = parse_endpoint("localhost:10024", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(endpoint.scheme, Scheme::Http); + assert_eq!(endpoint.url(), "http://localhost:10024"); + assert!(!endpoint.is_tls()); + } + + #[test] + fn test_parse_endpoint_applies_default_port_without_scheme() { + let endpoint = parse_endpoint("localhost", DEFAULT_SQL_PORT).unwrap(); + assert_eq!(endpoint.url(), "http://localhost:10025"); + } + + #[test] + fn test_parse_endpoint_preserves_https() { + let endpoint = parse_endpoint("https://db.example.com:8443", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(endpoint.scheme, Scheme::Https); + assert_eq!(endpoint.url(), "https://db.example.com:8443"); + assert!(endpoint.is_tls()); + } + + #[test] + fn test_parse_endpoint_scheme_implies_standard_port() { + assert_eq!( + parse_endpoint("https://db.example.com", DEFAULT_HTTP_PORT) + .unwrap() + .url(), + "https://db.example.com:443" + ); + assert_eq!( + parse_endpoint("http://db.example.com", DEFAULT_HTTP_PORT) + .unwrap() + .url(), + "http://db.example.com:80" + ); + } + + #[test] + fn test_parse_endpoint_ignores_trailing_path() { + let endpoint = parse_endpoint("https://db.example.com:8443/", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(endpoint.url(), "https://db.example.com:8443"); + } + + #[test] + fn test_parse_endpoint_ipv6() { + let bracketed = parse_endpoint("https://[fd00::1]:8443", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(bracketed.host, "fd00::1"); + assert_eq!(bracketed.url(), "https://[fd00::1]:8443"); + + // A bare IPv6 literal has no port; the default applies. + let bare = parse_endpoint("::1", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(bare.host, "::1"); + assert_eq!(bare.url(), "http://[::1]:10024"); + + let bracketed_no_port = parse_endpoint("[::1]", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(bracketed_no_port.url(), "http://[::1]:10024"); + } + + #[test] + fn test_parse_grpc_endpoint_maps_grpc_schemes() { + // grpc:// is plaintext HTTP/2; grpcs:// is the TLS form. + assert_eq!( + parse_grpc_endpoint("grpc://lancedb-query-node:10025", DEFAULT_SQL_PORT) + .unwrap() + .url(), + "http://lancedb-query-node:10025" + ); + let secure = + parse_grpc_endpoint("grpcs://sql.example.com:10025", DEFAULT_SQL_PORT).unwrap(); + assert!(secure.is_tls()); + assert_eq!(secure.url(), "https://sql.example.com:10025"); + } + + #[test] + fn test_parse_endpoint_rejects_invalid_addresses() { + // gRPC schemes belong to the Flight SQL address only. + assert!(parse_endpoint("grpc://localhost:10025", DEFAULT_SQL_PORT).is_err()); + assert!(parse_endpoint("ftp://localhost:10025", DEFAULT_SQL_PORT).is_err()); + assert!(parse_grpc_endpoint("ftp://localhost:10025", DEFAULT_SQL_PORT).is_err()); + assert!(parse_endpoint("localhost:notaport", DEFAULT_SQL_PORT).is_err()); + assert!(parse_endpoint("https://", DEFAULT_HTTP_PORT).is_err()); + assert!(parse_endpoint("[::1:10024", DEFAULT_HTTP_PORT).is_err()); + } + + #[test] + fn config_parse_errors_do_not_expose_credentials_or_parser_causes() { + let dir = tempdir().unwrap(); + let path = dir.path().join("config.toml"); + for (contents, secret, location) in [ + ( + "[profiles.cloud]\napi_key = \"sk_test_private\",\n", + "sk_test_private", + "line 2, column 28", + ), + ( + "[profiles.cloud]\r\napi_key = \"sk_test_prívate\",\r\n", + "sk_test_prívate", + "line 2, column 28", + ), + ( + "[profiles.cloud.oidc]\nflow = \"sk_test_private\"\n", + "sk_test_private", + "line 2, column 8", + ), + ] { + fs::write(&path, contents).unwrap(); + let err = Config::load_from_path_impl(&path).unwrap_err(); + for diagnostic in [ + format!("{err}"), + format!("{err:#}"), + format!("{err:?}"), + format!("{err:#?}"), + ] { + assert!(!diagnostic.contains(secret)); + assert!(!diagnostic.contains("api_key =")); + assert!(diagnostic.contains("Failed to parse config file")); + assert!(diagnostic.contains("invalid TOML or configuration value")); + assert!(diagnostic.contains(location), "{diagnostic}"); + assert!(diagnostic.contains("config.toml")); + } + assert_eq!(err.chain().count(), 1); + assert!(err.downcast_ref::().is_none()); + } + } + + #[test] + fn test_save_and_load_config() { + let dir = tempdir().unwrap(); + let config_path = dir.path().join("config.toml"); + + let mut config = Config { + data_dir: Some("/test/data".to_string()), + ..Config::default() + }; + config.set_profile( + "test", + Profile { + sql_server_url: Some("http://test.example.com".to_string()), + http_server_url: Some("http://test.example.com".to_string()), + api_key: Some("test-key".to_string()), + database: Some("testdb".to_string()), + azure_storage_account_name: Some("teststorageacct".to_string()), + ..Profile::default() + }, + ); + + // Save config + config.save_to_path(&config_path).unwrap(); + + // Load config + let loaded = Config::load_from_path(&config_path).unwrap(); + assert_eq!(loaded.data_dir, config.data_dir); + assert!(loaded.profiles.contains_key("test")); + assert_eq!( + loaded + .profiles + .get("test") + .unwrap() + .azure_storage_account_name, + Some("teststorageacct".to_string()) + ); + } + + #[cfg(unix)] + #[test] + fn config_saves_are_private_without_changing_custom_parent_modes() { + let dir = tempdir().unwrap(); + let parent = dir.path().join("custom"); + let path = parent.join("config.toml"); + let mut config = Config::default(); + config.set_profile( + "cloud", + Profile { + api_key: Some("initial-key".into()), + ..Profile::default() + }, + ); + config.save_to_path(&path).unwrap(); + assert_eq!( + fs::metadata(&parent).unwrap().permissions().mode() & 0o777, + 0o700 + ); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + + fs::set_permissions(&parent, fs::Permissions::from_mode(0o755)).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + config.profiles.get_mut("cloud").unwrap().api_key = Some("updated-key".into()); + config.save_to_path(&path).unwrap(); + + assert_eq!( + fs::metadata(&parent).unwrap().permissions().mode() & 0o777, + 0o755 + ); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert_eq!( + Config::load_from_path(&path) + .unwrap() + .get_profile(Some("cloud")) + .api_key + .as_deref(), + Some("updated-key") + ); + } + + #[test] + fn test_config_serialization() { + let config = Config { + data_dir: Some("/test/data".to_string()), + ..Config::default() + }; + + let serialized = toml::to_string_pretty(&config).unwrap(); + println!("Config TOML output:\n{}", serialized); + assert!(serialized.contains("data_dir = \"/test/data\"")); + + let deserialized: Config = toml::from_str(&serialized).unwrap(); + assert_eq!(deserialized.data_dir, config.data_dir); + } + + #[test] + fn test_profile_management() { + let mut config = Config::default(); + + // Test default profile (local) + let profile = config.get_profile(None); + assert_eq!(profile.sql_server_url, Some("localhost:10025".to_string())); + + // Add a custom profile + config.set_profile( + "production", + Profile { + sql_server_url: Some("http://sql.example.com".to_string()), + http_server_url: Some("http://api.example.com".to_string()), + api_key: Some("prod-key".to_string()), + database: Some("proddb".to_string()), + azure_storage_account_name: Some("prodstorageacct".to_string()), + ..Profile::default() + }, + ); + + // Get custom profile + let prod_profile = config.get_profile(Some("production")); + assert_eq!( + prod_profile.sql_server_url, + Some("http://sql.example.com".to_string()) + ); + assert_eq!(prod_profile.api_key, Some("prod-key".to_string())); + assert_eq!( + prod_profile.azure_storage_account_name, + Some("prodstorageacct".to_string()) + ); + + // Set as default + config.set_default_profile("production"); + let default_profile = config.get_profile(None); + assert_eq!( + default_profile.sql_server_url, + Some("http://sql.example.com".to_string()) + ); + + // List profiles + let profiles = config.list_profiles(); + assert!(profiles.contains(&"production")); + + // Remove profile + config.remove_profile("production"); + assert!(!config.profiles.contains_key("production")); + } + + #[test] + fn test_backward_compatible_config() { + // Test that old config format (just data_dir) still loads + let old_config = r#"data_dir = "/old/data/path""#; + let config: Config = toml::from_str(old_config).unwrap(); + assert_eq!(config.data_dir, Some("/old/data/path".to_string())); + assert!(config.profiles.is_empty()); + } + + #[test] + fn test_full_config_format() { + let full_config = r#" +data_dir = "/data/lancedb" +default_profile = "dev" + +[profiles.dev] +sql_server_url = "http://localhost:8080" +http_server_url = "http://localhost:8081" +database = "devdb" +unknown_config_key = "blah" + +[profiles.prod] +sql_server_url = "http://sql.prod.example.com" +http_server_url = "http://api.prod.example.com" +api_key = "secret-key" +database = "proddb" +azure_storage_account_name = "prodstorageacct" +"#; + let dir = tempdir().unwrap(); + let config_path = dir.path().join("config.toml"); + fs::write(&config_path, full_config).unwrap(); + let (config, unused) = Config::load_from_path_impl(&config_path).unwrap(); + assert_eq!(vec!["profiles.dev.unknown_config_key"], unused); + assert_eq!(config.data_dir, Some("/data/lancedb".to_string())); + assert_eq!(config.default_profile, Some("dev".to_string())); + assert_eq!(config.profiles.len(), 2); + + let dev = config.get_profile(Some("dev")); + assert_eq!( + dev.sql_server_url, + Some("http://localhost:8080".to_string()) + ); + assert_eq!(dev.api_key, None); + + let prod = config.get_profile(Some("prod")); + assert_eq!(prod.api_key, Some("secret-key".to_string())); + assert_eq!( + prod.azure_storage_account_name, + Some("prodstorageacct".to_string()) + ); + } + + #[test] + fn authentication_resolution_follows_flag_env_profile_order() { + let dir = tempdir().unwrap(); + let flag_token = dir.path().join("flag-token"); + let env_token = dir.path().join("env-token"); + fs::write(&flag_token, "flag-oidc\n").unwrap(); + fs::write(&env_token, "env-file-oidc\n").unwrap(); + + let profile = Profile { + api_key: Some("profile-api-key".to_string()), + ..Profile::default() + }; + let args = ConnectionArgs { + api_key: Some("flag-api-key".to_string()), + ..ConnectionArgs::default() + }; + let all_env = |name: &str| match name { + API_KEY_ENV => Some("env-api-key".into()), + OIDC_ACCESS_TOKEN_ENV => Some("env-oidc".into()), + OIDC_ACCESS_TOKEN_FILE_ENV => Some(env_token.as_os_str().to_owned()), + _ => None, + }; + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, all_env) + .unwrap(), + Authentication::ApiKey("flag-api-key".to_string()) + ); + + let args = ConnectionArgs { + oidc_access_token_file: Some(flag_token.to_string_lossy().into_owned()), + ..ConnectionArgs::default() + }; + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, all_env) + .unwrap(), + Authentication::OidcAccessTokenFile(flag_token.clone()) + ); + + let args = ConnectionArgs::default(); + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, all_env) + .unwrap(), + Authentication::ApiKey("env-api-key".to_string()) + ); + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, |name| match name { + OIDC_ACCESS_TOKEN_ENV => Some("env-oidc".into()), + OIDC_ACCESS_TOKEN_FILE_ENV => Some(env_token.as_os_str().to_owned()), + _ => None, + }) + .unwrap(), + Authentication::OidcAccessToken("env-oidc".to_string()) + ); + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, |name| match name { + OIDC_ACCESS_TOKEN_FILE_ENV => Some(env_token.as_os_str().to_owned()), + _ => None, + }) + .unwrap(), + Authentication::OidcAccessTokenFile(env_token.clone()) + ); + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, |_| None) + .unwrap(), + Authentication::ApiKey("profile-api-key".to_string()) + ); + assert_eq!( + args.resolve_authentication_with_env(&Profile::default(), DEFAULT_PROFILE, |_| None) + .unwrap(), + Authentication::ApiKey(DEFAULT_API_KEY.to_string()) + ); + } + + #[test] + fn profile_cannot_contain_two_authentication_methods() { + let profile = Profile { + api_key: Some("sk_test".to_string()), + oidc_access_token_file: Some("token-file".to_string()), + ..Profile::default() + }; + let err = ConnectionArgs::default() + .resolve_authentication_with_env(&profile, DEFAULT_PROFILE, |_| None) + .unwrap_err(); + assert_eq!( + err.to_string(), + "profile cannot specify both api_key and oidc_access_token_file" + ); + } + #[test] + fn native_oidc_profile_and_credential_overrides() { + let config: Config = toml::from_str( + r#" +[profiles.automation.oidc] +flow = "client_credentials" +issuer_url = "https://identity.example.com" +client_id = "automation-client" +scopes = ["lancedb"] +client_secret_file = "/run/secrets/lancedb" +"#, + ) + .unwrap(); + let profile = config.get_profile(Some("automation")); + let args = ConnectionArgs::default(); + assert!(matches!( + args.resolve_authentication_with_env(&profile, "automation", |_| None) + .unwrap(), + Authentication::ManagedOidc(_) + )); + let oidc = args + .resolve_authentication_with_env(&profile, "automation", |name| { + (name == OIDC_ACCESS_TOKEN_ENV).then(|| "external-token".into()) + }) + .unwrap(); + assert_eq!( + oidc, + Authentication::OidcAccessToken("external-token".into()) + ); + let key = args + .resolve_authentication_with_env(&profile, "automation", |name| match name { + API_KEY_ENV => Some("api-key".into()), + OIDC_ACCESS_TOKEN_ENV => Some("external-token".into()), + _ => None, + }) + .unwrap(); + assert_eq!(key, Authentication::ApiKey("api-key".into())); + let invalid = Profile { + api_key: Some("key".into()), + ..profile + }; + assert!(args + .resolve_authentication_with_env(&invalid, "automation", |_| None) + .is_err()); + } +} diff --git a/rust/lancedb/cli/src/sql_executor.rs b/rust/lancedb/cli/src/sql_executor.rs new file mode 100644 index 000000000..87559d88e --- /dev/null +++ b/rust/lancedb/cli/src/sql_executor.rs @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use crate::dml_result::DmlResult; +use anyhow::Result; +use arrow_array::RecordBatch; +use async_trait::async_trait; + +#[async_trait] +pub trait SqlQueryExecutor: Send + Sync { + /// Execute a SQL query and return a structured result. + async fn execute_query(&mut self, query: &str) -> Result; + + /// Check if the executor is connected and ready + async fn is_connected(&self) -> bool; + + /// Get the connection info for display purposes + fn connection_info(&self) -> Option; + + /// Connect to the server. `server_url` may carry an `http://` or `https://` + /// scheme; a bare `host:port` is treated as plaintext. + async fn connect(&mut self, server_url: &str) -> Result<()>; + + /// Set the current database + fn set_database(&mut self, database: String); +} + +/// Result of a SQL execution +#[derive(Debug)] +pub enum SqlResult { + /// Query returned data + Query(Vec), + /// DML result (INSERT, DELETE, UPDATE) + Dml(DmlResult), + /// DDL statement (CREATE, DROP, etc.) completed + Success, +} + +impl From> for SqlResult { + fn from(batches: Vec) -> Self { + match batches.first().and_then(DmlResult::try_from_batch) { + Some(dml) => Self::Dml(dml), + None => Self::Query(batches), + } + } +} + +/// SQL execution through the public SDK's asynchronous query lifecycle. +pub struct SdkSqlExecutor { + connection: Option, + server_url: String, + database: String, + authentication: crate::server_config::Authentication, + tls: crate::server_config::TlsOptions, +} + +impl SdkSqlExecutor { + pub fn new_with_authentication( + server_url: String, + authentication: crate::server_config::Authentication, + ) -> Self { + Self { + connection: None, + server_url, + database: "test".into(), + authentication, + tls: Default::default(), + } + } + + pub fn new_with_api_key(server_url: String, api_key: String) -> Self { + Self::new_with_authentication( + server_url, + crate::server_config::Authentication::ApiKey(api_key), + ) + } + + pub fn with_tls(mut self, tls: crate::server_config::TlsOptions) -> Self { + self.tls = tls; + self + } +} + +#[async_trait] +impl SqlQueryExecutor for SdkSqlExecutor { + async fn execute_query(&mut self, query: &str) -> Result { + use futures::TryStreamExt; + let connection = self + .connection + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Flight SQL client not connected"))?; + let mut builder = connection.execute_query_async(query); + if let Ok(namespace) = std::env::var("LANCEDB_NAMESPACE_PATH") { + builder = builder.default_namespace_path(namespace.split('$')); + } + let query = builder.execute().await?; + let batches: Vec = query.reader().await?.try_collect().await?; + Ok(batches.into()) + } + + async fn is_connected(&self) -> bool { + self.connection.is_some() + } + + fn connection_info(&self) -> Option { + self.connection + .as_ref() + .map(|_| format!("Connected to {}", self.server_url)) + } + + async fn connect(&mut self, server_url: &str) -> Result<()> { + use crate::server_config::{parse_grpc_endpoint, Authentication, DEFAULT_SQL_PORT}; + self.connection = None; + self.server_url = server_url.to_owned(); + let endpoint = parse_grpc_endpoint(server_url, DEFAULT_SQL_PORT)?.url(); + let mut builder = lancedb::connect(&format!("db://{}", self.database)) + .region("self-hosted") + .sql_host_override(&endpoint); + builder = match &self.authentication { + Authentication::ApiKey(key) => builder.api_key(key), + _ => builder.api_key(""), + }; + let mut config = + crate::lancedb_client_config(&self.tls, &self.authentication).unwrap_or_default(); + // Preserve the CLI's bounded startup probe, including the TLS handshake. + config.timeout_config.connect_timeout = Some(std::time::Duration::from_secs(5)); + builder = builder.client_config(config); + let connection = builder.execute().await?; + connection.check_sql_connection().await?; + self.connection = Some(connection); + Ok(()) + } + + fn set_database(&mut self, database: String) { + if self.database != database { + self.connection = None; + } + self.database = database; + } +} diff --git a/rust/lancedb/cli/src/table_writer.rs b/rust/lancedb/cli/src/table_writer.rs new file mode 100644 index 000000000..bcd146d1b --- /dev/null +++ b/rust/lancedb/cli/src/table_writer.rs @@ -0,0 +1,380 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/* +MIT License + +Copyright (c) Foxglove Technologies Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +// Ported from +// https://github.com/foxglove/foxglove-cli/blob/main/foxglove/util/tablewriter/tablewriter.go + +use std::io::{self, Write}; +use std::process::Command; +use unicode_width::UnicodeWidthStr; + +pub struct TableWriter; + +impl TableWriter { + pub fn print_table( + writer: &mut W, + headers: &[String], + data: &[Vec], + term_width: Option, + ) -> io::Result<()> { + let term_width = term_width.unwrap_or_else(get_terminal_width); + let table_width = compute_hotdog_table_width(headers, data); + + if term_width < table_width { + Self::print_hamburger(writer, term_width, headers, data) + } else { + Self::print_hotdog(writer, headers, data) + } + } + + pub fn print_table_with_title( + writer: &mut W, + title: &str, + headers: &[String], + data: &[Vec], + term_width: Option, + ) -> io::Result<()> { + let term_width = term_width.unwrap_or_else(get_terminal_width); + let table_width = compute_hotdog_table_width(headers, data); + + if term_width < table_width { + // For hamburger mode, just print the title normally + writeln!(writer, "{}", title)?; + Self::print_hamburger(writer, term_width, headers, data) + } else { + // For hotdog mode, center the title over the table + let title_padding = if table_width > title.width() { + (table_width - title.width()) / 2 + } else { + 0 + }; + writeln!(writer, "{}{}", " ".repeat(title_padding), title)?; + Self::print_hotdog(writer, headers, data) + } + } + + /// Prints table in horizontal "hotdog" format (PostgreSQL style) + fn print_hotdog( + writer: &mut W, + headers: &[String], + data: &[Vec], + ) -> io::Result<()> { + let cell_widths = compute_hotdog_cell_widths(headers, data); + let column_alignments = compute_column_alignments(data); + + // Write headers + write!(writer, " ")?; + for (i, header) in headers.iter().enumerate() { + if i > 0 { + write!(writer, " | ")?; + } + let padding = cell_widths[i] - header.width(); + write!(writer, "{}{}", header, " ".repeat(padding))?; + } + writeln!(writer)?; + + // Write separator with + at junctions + write!(writer, "-")?; // Leading edge + for (i, &width) in cell_widths.iter().enumerate() { + write!(writer, "{}", "-".repeat(width))?; + if i < cell_widths.len() - 1 { + write!(writer, "-+-")?; // Junction between columns + } + } + writeln!(writer, "-")?; // Trailing edge + + // Write data rows + for row in data { + write!(writer, " ")?; + for (i, col) in row.iter().enumerate() { + if i > 0 { + write!(writer, " | ")?; + } + let padding = cell_widths[i] - col.width(); + + // Right-align numeric columns, left-align others + if i < column_alignments.len() && column_alignments[i] { + write!(writer, "{}{}", " ".repeat(padding), col)?; + } else { + write!(writer, "{}{}", col, " ".repeat(padding))?; + } + } + writeln!(writer)?; + } + + Ok(()) + } + + /// Prints table in vertical "hamburger" format (psql expanded display style) + fn print_hamburger( + writer: &mut W, + term_width: usize, + headers: &[String], + data: &[Vec], + ) -> io::Result<()> { + let mut max_header_width = 0; + let mut max_record_width = 0; + + // Compute max header width + for header in headers { + if header.width() > max_header_width { + max_header_width = header.width(); + } + } + + // Compute max record width (cap at reasonable limit) + const MAX_VALUE_DISPLAY_WIDTH: usize = 80; // Reasonable max for value display + for row in data { + for col in row { + let col_width = col.width().min(MAX_VALUE_DISPLAY_WIDTH); + if col_width > max_record_width { + max_record_width = col_width; + } + } + } + + // Ensure sufficient room for record headers + let longest_record_header = format!("-[ RECORD {} ]", data.len()); + if longest_record_header.len() > max_header_width { + max_header_width = longest_record_header.len(); + } + + // Calculate right dash extent - aim for a reasonable width + let desired_dash_extent = 60; // Reasonable default width for dashes + let mut dashes_right_extent = desired_dash_extent.min(max_record_width + 15); + let max_allowed_extent = term_width.saturating_sub(max_header_width + 3); // +3 for "+-" and space + if dashes_right_extent > max_allowed_extent { + dashes_right_extent = max_allowed_extent; + } + let right_dashes = "-".repeat(dashes_right_extent); + + // Print records + for (i, row) in data.iter().enumerate() { + let record_header = format!("-[ RECORD {} ]", i + 1); + let header_line = format!( + "{}{}+{}", + record_header, + "-".repeat(max_header_width - record_header.len()), + right_dashes + ); + writeln!(writer, "{}", header_line)?; + + for (j, col) in row.iter().enumerate() { + writeln!( + writer, + "{}{}| {}", + headers[j], + " ".repeat(max_header_width - headers[j].width()), + col + )?; + } + } + + Ok(()) + } +} + +fn compute_hotdog_cell_widths(headers: &[String], data: &[Vec]) -> Vec { + let mut cell_widths = vec![0; headers.len()]; + + // Initialize with header widths + for (i, header) in headers.iter().enumerate() { + cell_widths[i] = header.width(); + } + + // Check data column widths + for row in data { + for (i, col) in row.iter().enumerate() { + if i < cell_widths.len() && cell_widths[i] < col.width() { + cell_widths[i] = col.width(); + } + } + } + + cell_widths +} + +fn compute_hotdog_table_width(headers: &[String], data: &[Vec]) -> usize { + let cell_widths = compute_hotdog_cell_widths(headers, data); + // Account for " | " separators between columns (3 chars each) + leading space + trailing space + let separator_width = if headers.len() > 1 { + (headers.len() - 1) * 3 + } else { + 0 + }; + 2 + cell_widths.iter().sum::() + separator_width +} + +fn compute_column_alignments(data: &[Vec]) -> Vec { + if data.is_empty() { + return vec![]; + } + + let num_cols = data[0].len(); + let mut is_numeric = vec![true; num_cols]; + + // Check each column to see if all non-empty values are numeric + for col_idx in 0..num_cols { + for row in data { + if col_idx < row.len() && !row[col_idx].is_empty() { + let value = &row[col_idx]; + // Check if the value is numeric (integer or float) + // Also handle NULL values + if value != "NULL" && !is_numeric_value(value) { + is_numeric[col_idx] = false; + break; + } + } + } + } + + is_numeric +} + +fn is_numeric_value(s: &str) -> bool { + // Try to parse as integer or float + s.parse::().is_ok() || s.parse::().is_ok() +} + +fn get_terminal_width() -> usize { + if let Ok(output) = Command::new("stty").arg("size").output() { + if let Ok(output_str) = String::from_utf8(output.stdout) { + let parts: Vec<&str> = output_str.split_whitespace().collect(); + if parts.len() >= 2 { + if let Ok(cols) = parts[1].parse::() { + return cols; + } + } + } + } + + // Fallback: try termsize crate + if let Some(size) = termsize::get() { + return size.cols as usize; + } + + // Final fallback + 80 +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn test_print_hotdog() { + let mut output = Cursor::new(Vec::new()); + let headers = vec!["ID".to_string(), "Name".to_string(), "Age".to_string()]; + let data = vec![ + vec!["1".to_string(), "Alice".to_string(), "30".to_string()], + vec!["2".to_string(), "Bob".to_string(), "25".to_string()], + vec!["3".to_string(), "Charlie".to_string(), "35".to_string()], + ]; + + TableWriter::print_hotdog(&mut output, &headers, &data).unwrap(); + let result = String::from_utf8(output.into_inner()).unwrap(); + assert_eq!(result, expected_output()); + } + + #[test] + fn test_unicode_table_padding_uses_terminal_columns() { + let headers = vec!["µ".to_string(), "Type".to_string()]; + let data = vec![ + vec!["µ".to_string(), "TEXT".to_string()], + vec!["漢".to_string(), "TEXT".to_string()], + vec!["e\u{301}".to_string(), "TEXT".to_string()], + ]; + let mut output = Vec::new(); + TableWriter::print_table(&mut output, &headers, &data, Some(11)).unwrap(); + assert_eq!( + String::from_utf8(output).unwrap(), + " µ | Type\n----+------\n µ | TEXT\n 漢 | TEXT\n e\u{301} | TEXT\n" + ); + } + + fn expected_output() -> String { + let mut output = String::new(); + output.push_str(" ID | Name | Age\n"); + output.push_str("----+---------+-----\n"); + output.push_str(" 1 | Alice | 30\n"); + output.push_str(" 2 | Bob | 25\n"); + output.push_str(" 3 | Charlie | 35\n"); + output + } + + #[test] + fn test_print_hamburger() { + let mut output = Cursor::new(Vec::new()); + let headers = vec!["ID".to_string(), "Name".to_string(), "Age".to_string()]; + let data = vec![ + vec!["1".to_string(), "Alice".to_string(), "30".to_string()], + vec!["2".to_string(), "Bob".to_string(), "25".to_string()], + vec!["3".to_string(), "Charlie".to_string(), "35".to_string()], + ]; + + // Test with a narrow terminal width + TableWriter::print_hamburger(&mut output, 80, &headers, &data).unwrap(); + let result = String::from_utf8(output.into_inner()).unwrap(); + assert_eq!(result, expected_hamburger_output()); + } + + fn expected_hamburger_output() -> String { + let mut output = String::new(); + output.push_str("-[ RECORD 1 ]+----------------------\n"); + output.push_str("ID | 1\n"); + output.push_str("Name | Alice\n"); + output.push_str("Age | 30\n"); + output.push_str("-[ RECORD 2 ]+----------------------\n"); + output.push_str("ID | 2\n"); + output.push_str("Name | Bob\n"); + output.push_str("Age | 25\n"); + output.push_str("-[ RECORD 3 ]+----------------------\n"); + output.push_str("ID | 3\n"); + output.push_str("Name | Charlie\n"); + output.push_str("Age | 35\n"); + output + } + + #[test] + fn test_print_table_with_title() { + let mut output = Cursor::new(Vec::new()); + let headers = vec!["ID".to_string(), "Name".to_string()]; + let data = vec![ + vec!["1".to_string(), "Alice".to_string()], + vec!["2".to_string(), "Bob".to_string()], + ]; + + TableWriter::print_table_with_title(&mut output, "User List", &headers, &data, Some(200)) + .unwrap(); + let result = String::from_utf8(output.into_inner()).unwrap(); + + // Should center the title and print hotdog format + let expected = " User List\n ID | Name \n----+-------\n 1 | Alice\n 2 | Bob \n"; + assert_eq!(result, expected); + } +} diff --git a/rust/lancedb/cli/tests/command_surface.rs b/rust/lancedb/cli/tests/command_surface.rs new file mode 100644 index 000000000..9d2f9c50e --- /dev/null +++ b/rust/lancedb/cli/tests/command_surface.rs @@ -0,0 +1,339 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::process::Command; + +#[test] +fn an_unconfigured_default_sql_invocation_prints_usage() { + use lancedb_cli::server_config::{Config, Profile}; + + for has_http_profile in [false, true] { + let home = tempfile::tempdir().unwrap(); + if has_http_profile { + let mut config = Config::default(); + config.set_profile( + "cloud", + Profile { + http_server_url: Some("http://api.example.com".into()), + ..Default::default() + }, + ); + config.set_default_profile("cloud"); + config + .save_to_path(&home.path().join(".lancedb/config.toml")) + .unwrap(); + } + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .env("HOME", home.path()) + .env("LANCEDB_API_KEY", "secret-that-must-not-appear") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("Usage:"), "{stdout}"); + assert!( + stdout.contains("No Flight SQL endpoint is configured"), + "{stdout}" + ); + assert!(!stdout.contains("secret-that-must-not-appear")); + assert!( + output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + if !has_http_profile { + assert!(!home.path().join(".lancedb").exists()); + } + } +} + +#[test] +fn invalid_config_diagnostics_do_not_print_credentials() { + for (contents, location) in [ + ( + "[profiles.cloud]\napi_key = \"sk_test_private\",\n", + "line 2, column 28", + ), + ( + "[profiles.cloud.oidc]\nflow = \"sk_test_private\"\n", + "line 2, column 8", + ), + ] { + let home = tempfile::tempdir().unwrap(); + let config_dir = home.path().join(".lancedb"); + std::fs::create_dir(&config_dir).unwrap(); + std::fs::write(config_dir.join("config.toml"), contents).unwrap(); + for args in [vec!["profile", "list"], vec!["sql"], vec![]] { + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(args) + .env("HOME", home.path()) + .output() + .unwrap(); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!stderr.contains("sk_test_private")); + assert!(!stderr.contains("api_key =")); + assert!(stderr.contains("Failed to parse config file"), "{stderr}"); + assert!(stderr.contains("invalid TOML or configuration value")); + assert!(stderr.contains(location), "{stderr}"); + assert!(stderr.contains("config.toml")); + assert!(output.stdout.is_empty()); + } + } +} + +#[test] +fn explicit_sql_requests_require_a_configured_endpoint() { + for args in [ + vec!["sql"], + vec!["--command", "SELECT 1"], + vec!["--file", "queries.sql"], + vec!["--profile", "missing"], + ] { + let home = tempfile::tempdir().unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(&args) + .env("HOME", home.path()) + .output() + .unwrap(); + assert!(!output.status.success(), "{args:?}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("No Flight SQL endpoint is configured"), + "{args:?}: {stderr}" + ); + assert!(stderr.contains("--sql-server-url"), "{stderr}"); + assert!(stderr.contains("--profile local"), "{stderr}"); + assert!(!home.path().join(".lancedb").exists()); + } +} + +#[test] +fn selecting_local_as_default_persists_its_endpoint() { + use lancedb_cli::server_config::{Config, Profile}; + + for existing_endpoint in [None, Some("localhost:12345")] { + let home = tempfile::tempdir().unwrap(); + let path = home.path().join(".lancedb/config.toml"); + if let Some(endpoint) = existing_endpoint { + let mut config = Config::default(); + config.set_profile( + "local", + Profile { + sql_server_url: Some(endpoint.into()), + ..Default::default() + }, + ); + config.save_to_path(&path).unwrap(); + } + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(["profile", "set", "local"]) + .env("HOME", home.path()) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let config = Config::load_from_path(&path).unwrap(); + assert_eq!(config.default_profile.as_deref(), Some("local")); + assert_eq!( + config + .profiles + .get("local") + .unwrap() + .sql_server_url + .as_deref(), + Some(existing_endpoint.unwrap_or("localhost:10025")) + ); + } +} + +#[test] +fn help_lists_commands_without_creating_configuration() { + let home = tempfile::tempdir().unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .arg("--help") + .env("HOME", home.path()) + .env("LANCEDB_API_KEY", "secret-that-must-not-appear") + .output() + .unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(stdout.contains("Usage:")); + for command in ["auth", "profile", "sql"] { + assert!(stdout.contains(command)); + } + for command in ["acl", "load", "job"] { + assert!(!stdout.contains(&format!(" {command} ")), "{stdout}"); + } + assert!(!stdout.contains("secret-that-must-not-appear")); + assert!(!home.path().join(".lancedb").exists()); +} + +#[test] +fn excluded_commands_and_mixed_sql_options_are_rejected() { + for args in [ + vec!["server"], + vec!["management"], + vec!["job", "--help"], + vec!["job", "list", "--help"], + vec!["job", "usage"], + vec!["acl"], + vec!["acl", "--help"], + vec!["acl", "list"], + vec!["acl", "add"], + vec!["acl", "delete"], + vec!["load"], + vec!["load", "--help"], + vec!["load", "--source", "lance", "--dataset", "data.lance"], + vec!["--command", "SELECT 1", "profile", "list"], + vec!["--file", "queries.sql", "profile", "list"], + vec!["profile", "list", "--command", "SELECT 1"], + vec!["profile", "list", "--file", "queries.sql"], + ] { + let home = tempfile::tempdir().unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(&args) + .env("HOME", home.path()) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(2), "{args:?}"); + assert!(output.stdout.is_empty(), "{args:?}"); + assert!(!home.path().join(".lancedb").exists(), "{args:?}"); + } +} + +#[test] +fn sql_options_do_not_appear_in_other_subcommand_help() { + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(["profile", "--help"]) + .output() + .unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8_lossy(&output.stdout); + for option in ["--command", "--file", "--format", "--sql-server-url"] { + assert!(!stdout.contains(option), "{stdout}"); + } +} + +#[test] +fn sql_environment_options_do_not_change_profile_commands() { + let home = tempfile::tempdir().unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(["profile", "list"]) + .env("HOME", home.path()) + .env("LANCEDB_CA_CERT", "/not-used-by-profile/ca.pem") + .env("LANCEDB_CLIENT_CERT", "/not-used-by-profile/client.pem") + .env("LANCEDB_CLIENT_KEY", "/not-used-by-profile/key.pem") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("Configured profiles:"), "{stdout}"); +} + +#[test] +fn profile_updates_preserve_enterprise_data_directory() { + use lancedb_cli::server_config::{Config, Profile}; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write( + &path, + "data_dir = '/enterprise/data'\ndefault_profile = 'local'\n", + ) + .unwrap(); + let mut config = Config::load_from_path(&path).unwrap(); + config.set_profile( + "cloud", + Profile { + database: Some("analytics".into()), + ..Default::default() + }, + ); + config.save_to_path(&path).unwrap(); + let saved = Config::load_from_path(&path).unwrap(); + assert_eq!(saved.data_dir.as_deref(), Some("/enterprise/data")); + assert_eq!( + saved.get_profile(Some("cloud")).database.as_deref(), + Some("analytics") + ); +} + +#[cfg(unix)] +#[test] +fn api_key_profiles_are_private_under_permissive_umasks_and_after_edits() { + use lancedb_cli::server_config::Config; + use std::fs; + use std::os::unix::fs::PermissionsExt; + + for mask in ["022", "000"] { + let home = tempfile::tempdir().unwrap(); + let config_dir = home.path().join(".lancedb"); + let path = config_dir.join("config.toml"); + let run = |command: &str, key: &str| { + // Set umask only in the child, leaving other test threads unaffected. + let output = Command::new("/bin/sh") + .args([ + "-c", + r#"umask "$1"; shift; exec "$@""#, + "profile-permissions", + mask, + env!("CARGO_BIN_EXE_lancedb"), + "profile", + command, + "cloud", + "--api-key", + key, + "--database", + "analytics", + ]) + .env("HOME", home.path()) + .output() + .unwrap(); + assert!( + output.status.success(), + "{command} under umask {mask}: {}", + String::from_utf8_lossy(&output.stderr) + ); + }; + let assert_private = || { + assert_eq!( + fs::metadata(&config_dir).unwrap().permissions().mode() & 0o777, + 0o700, + "config directory under umask {mask}" + ); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600, + "config file under umask {mask}" + ); + }; + + run("create", "initial-key"); + assert_private(); + + fs::set_permissions(&config_dir, fs::Permissions::from_mode(0o755)).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + run("edit", "replacement-key"); + assert_private(); + let saved = Config::load_from_path(&path).unwrap(); + assert_eq!( + saved.get_profile(Some("cloud")).api_key.as_deref(), + Some("replacement-key") + ); + assert_eq!( + saved.get_profile(Some("cloud")).database.as_deref(), + Some("analytics") + ); + } +} diff --git a/rust/lancedb/cli/tests/flight_sql_tls.rs b/rust/lancedb/cli/tests/flight_sql_tls.rs new file mode 100644 index 000000000..40c34409c --- /dev/null +++ b/rust/lancedb/cli/tests/flight_sql_tls.rs @@ -0,0 +1,643 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! End-to-end TLS and SQL file-execution coverage for the Flight SQL transport. +//! +//! A throwaway CA signs a server certificate for `127.0.0.1`, a real Flight +//! server serves it over TLS, and the CLI's executor connects with the CA +//! supplied through `--ca-cert`. The negative cases prove verification is +//! genuinely happening rather than being skipped. + +use std::net::SocketAddr; +use std::pin::Pin; + +use arrow_array::{Int32Array, RecordBatch}; +use arrow_flight::encode::FlightDataEncoderBuilder; +use arrow_flight::flight_service_server::{FlightService, FlightServiceServer}; +use arrow_flight::sql::{Any, CommandStatementQuery}; +use arrow_flight::{ + Action, ActionType, Criteria, Empty, FlightData, FlightDescriptor, FlightEndpoint, FlightInfo, + HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket, +}; +use arrow_schema::{DataType, Field, Schema}; +use futures::{Stream, TryStreamExt}; +use lancedb_cli::server_config::TlsOptions; +use lancedb_cli::sql_executor::SdkSqlExecutor as FlightSqlExecutor; +use lancedb_cli::sql_executor::{SqlQueryExecutor, SqlResult}; +use prost::Message; +use std::sync::{Arc, Mutex}; +use tokio::net::TcpListener; +use tokio_stream::wrappers::TcpListenerStream; +use tonic::transport::{Identity, Server, ServerTlsConfig}; +use tonic::{Request, Response, Status, Streaming}; + +/// The single column the stub server returns, asserted by the tests. +const ANSWER: i32 = 42; + +/// tonic's server-side TLS needs a process-level rustls crypto provider; unlike +/// the client path it has no built-in fallback. +fn init_crypto_provider() { + static INIT: std::sync::Once = std::sync::Once::new(); + INIT.call_once(|| { + let _ = rustls::crypto::ring::default_provider().install_default(); + }); +} + +type BoxStream = Pin> + Send + 'static>>; + +/// Minimal Flight service: enough for `execute_query` to complete a round trip. +/// Everything the CLI does not call is left unimplemented on purpose. +#[derive(Clone, Default)] +struct StubFlightService { + queries: Option>>>, +} + +/// The SDK wraps a Flight SQL command in a ticket's field 2. +#[derive(Clone, PartialEq, Message)] +struct CommandTicket { + #[prost(bytes = "vec", tag = "2")] + command: Vec, +} + +impl StubFlightService { + fn batch() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![Field::new( + "answer", + DataType::Int32, + false, + )])); + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![ANSWER]))]).unwrap() + } +} + +#[tonic::async_trait] +impl FlightService for StubFlightService { + type HandshakeStream = BoxStream; + type ListFlightsStream = BoxStream; + type DoGetStream = BoxStream; + type DoPutStream = BoxStream; + type DoExchangeStream = BoxStream; + type DoActionStream = BoxStream; + type ListActionsStream = BoxStream; + + async fn get_flight_info( + &self, + _request: Request, + ) -> Result, Status> { + let endpoint = FlightEndpoint::new().with_ticket(Ticket::new("stub")); + Ok(Response::new(FlightInfo::new().with_endpoint(endpoint))) + } + + async fn do_get( + &self, + request: Request, + ) -> Result, Status> { + if let Some(queries) = &self.queries { + let ticket = CommandTicket::decode(request.into_inner().ticket).unwrap(); + let command = Any::decode(ticket.command.as_slice()) + .unwrap() + .unpack::() + .unwrap() + .unwrap(); + queries.lock().unwrap().push(command.query); + } + let batch = Self::batch(); + let stream = FlightDataEncoderBuilder::new() + .build(futures::stream::once(async move { Ok(batch) })) + .map_err(|err| Status::internal(err.to_string())); + Ok(Response::new(Box::pin(stream))) + } + + async fn handshake( + &self, + _request: Request>, + ) -> Result, Status> { + Err(Status::unimplemented("handshake")) + } + + async fn list_flights( + &self, + _request: Request, + ) -> Result, Status> { + Err(Status::unimplemented("list_flights")) + } + + async fn poll_flight_info( + &self, + _request: Request, + ) -> Result, Status> { + let endpoint = FlightEndpoint::new().with_ticket(Ticket::new("stub")); + let info = FlightInfo::new() + .with_endpoint(endpoint) + .try_with_schema(&Self::batch().schema()) + .unwrap(); + Ok(Response::new(PollInfo { + info: Some(info), + flight_descriptor: None, + progress: Some(1.0), + expiration_time: None, + })) + } + + async fn get_schema( + &self, + _request: Request, + ) -> Result, Status> { + Err(Status::unimplemented("get_schema")) + } + + async fn do_put( + &self, + _request: Request>, + ) -> Result, Status> { + Err(Status::unimplemented("do_put")) + } + + async fn do_exchange( + &self, + _request: Request>, + ) -> Result, Status> { + Err(Status::unimplemented("do_exchange")) + } + + async fn do_action( + &self, + _request: Request, + ) -> Result, Status> { + Err(Status::unimplemented("do_action")) + } + + async fn list_actions( + &self, + _request: Request, + ) -> Result, Status> { + Err(Status::unimplemented("list_actions")) + } +} + +/// A CA plus the server and client certificates it signed. The server +/// certificate is valid for `127.0.0.1`. +struct TestCerts { + ca_pem: String, + server_cert_pem: String, + server_key_pem: String, + client_cert_pem: String, + client_key_pem: String, +} + +fn generate_certs() -> TestCerts { + use rcgen::{BasicConstraints, CertificateParams, IsCa, KeyPair, PKCS_ECDSA_P256_SHA256}; + + let mut ca_params = CertificateParams::new(vec!["Test CA".to_string()]); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + ca_params.key_pair = Some(KeyPair::generate(&PKCS_ECDSA_P256_SHA256).unwrap()); + let ca_cert = rcgen::Certificate::from_params(ca_params).unwrap(); + + // The SANs must cover the address the client dials, or the handshake fails + // hostname verification even with the right CA. + let mut server_params = + CertificateParams::new(vec!["localhost".to_string(), "127.0.0.1".to_string()]); + server_params.key_pair = Some(KeyPair::generate(&PKCS_ECDSA_P256_SHA256).unwrap()); + let server_cert = rcgen::Certificate::from_params(server_params).unwrap(); + + let mut client_params = CertificateParams::new(vec!["test-client".to_string()]); + client_params.key_pair = Some(KeyPair::generate(&PKCS_ECDSA_P256_SHA256).unwrap()); + let client_cert = rcgen::Certificate::from_params(client_params).unwrap(); + + TestCerts { + ca_pem: ca_cert.serialize_pem().unwrap(), + server_cert_pem: server_cert.serialize_pem_with_signer(&ca_cert).unwrap(), + server_key_pem: server_cert.serialize_private_key_pem(), + client_cert_pem: client_cert.serialize_pem_with_signer(&ca_cert).unwrap(), + client_key_pem: client_cert.serialize_private_key_pem(), + } +} + +/// Start the stub Flight server over TLS on an ephemeral port. The server stops +/// when the returned shutdown sender is dropped. +async fn start_tls_server(certs: &TestCerts) -> (SocketAddr, tokio::sync::oneshot::Sender<()>) { + start_server(certs, false).await +} + +/// Same, but the server demands a client certificate signed by the test CA. +async fn start_mtls_server(certs: &TestCerts) -> (SocketAddr, tokio::sync::oneshot::Sender<()>) { + start_server(certs, true).await +} + +async fn start_server( + certs: &TestCerts, + require_client_cert: bool, +) -> (SocketAddr, tokio::sync::oneshot::Sender<()>) { + init_crypto_provider(); + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let addr = listener.local_addr().unwrap(); + + let identity = Identity::from_pem(&certs.server_cert_pem, &certs.server_key_pem); + let mut tls = ServerTlsConfig::new().identity(identity); + if require_client_cert { + tls = tls.client_ca_root(tonic::transport::Certificate::from_pem(&certs.ca_pem)); + } + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + + tokio::spawn(async move { + Server::builder() + .tls_config(tls) + .unwrap() + .add_service(FlightServiceServer::new(StubFlightService::default())) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }) + .await + .unwrap(); + }); + + (addr, shutdown_tx) +} + +fn write_pem(dir: &tempfile::TempDir, name: &str, contents: &str) -> String { + let path = dir.path().join(name); + std::fs::write(&path, contents).unwrap(); + path.to_str().unwrap().to_string() +} + +/// Exercise argument parsing, file reading, script execution, and SQL transport. +/// The stub records SQL without executing it against a database. +async fn run_sql_cli(args: &[&str], script: Option<&str>) -> (std::process::Output, Vec) { + let queries = Arc::new(Mutex::new(Vec::new())); + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let sql_endpoint = format!("http://{}", listener.local_addr().unwrap()); + let service = StubFlightService { + queries: Some(queries.clone()), + }; + let sql_server = tokio::spawn(async move { + Server::builder() + .add_service(FlightServiceServer::new(service)) + .serve_with_incoming(TcpListenerStream::new(listener)) + .await + .unwrap(); + }); + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let http_endpoint = format!("http://{}", listener.local_addr().unwrap()); + let app = + axum::Router::new().fallback(|| async { axum::Json(serde_json::json!({"tables": []})) }); + let http_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("script.sql"); + if let Some(script) = script { + std::fs::write(&path, script).unwrap(); + } + let mut config = lancedb_cli::server_config::Config::default(); + config.set_profile( + "test", + lancedb_cli::server_config::Profile { + sql_server_url: Some(sql_endpoint), + http_server_url: Some(http_endpoint), + database: Some("test".into()), + api_key: Some("test-key".into()), + ..Default::default() + }, + ); + config.set_default_profile("test"); + config + .save_to_path(&dir.path().join(".lancedb/config.toml")) + .unwrap(); + let output = tokio::process::Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(args) + .current_dir(dir.path()) + .stdin(std::process::Stdio::null()) + .env("HOME", dir.path()) + .env("XDG_DATA_HOME", dir.path().join("data")) + .env("XDG_CONFIG_HOME", dir.path().join("config")) + .env_remove("LANCEDB_API_KEY") + .env_remove("LANCEDB_OIDC_ACCESS_TOKEN") + .env_remove("LANCEDB_OIDC_ACCESS_TOKEN_FILE") + .env_remove("LANCEDB_CA_CERT") + .env_remove("LANCEDB_CLIENT_CERT") + .env_remove("LANCEDB_CLIENT_KEY") + .output() + .await + .unwrap(); + sql_server.abort(); + http_server.abort(); + let recorded = queries.lock().unwrap().clone(); + (output, recorded) +} + +async fn run_sql_file(script: &str) -> (std::process::Output, Vec) { + run_sql_cli( + &["sql", "--file", "script.sql", "--format", "json"], + Some(script), + ) + .await +} + +#[tokio::test] +async fn no_subcommand_opens_the_sql_shell() { + for args in [vec![], vec!["sql"]] { + let (output, queries) = run_sql_cli(&args, None).await; + assert!( + output.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("LanceDB CLI v"), "{stdout}"); + assert!( + stdout.contains("Type \\? for help or \\q to quit"), + "{stdout}" + ); + assert!(queries.is_empty()); + } +} + +#[tokio::test] +async fn sql_options_work_with_and_without_the_subcommand() { + for prefix in [vec![], vec!["sql"]] { + let mut args = prefix.clone(); + args.extend(["--command", "SELECT 42", "--format", "json"]); + let (output, queries) = run_sql_cli(&args, None).await; + assert!( + output.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(queries, ["SELECT 42"]); + let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(value, serde_json::json!([{"answer": ANSWER}])); + + let mut args = prefix; + args.extend(["--file", "script.sql", "--format", "json"]); + let (output, queries) = run_sql_cli(&args, Some("SELECT 'semi;colon';")).await; + assert!( + output.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(queries, ["SELECT 'semi;colon'"]); + } +} + +#[tokio::test] +async fn sql_files_preserve_comments_and_quoted_semicolons() { + for (script, expected) in [ + ( + "SHOW JOBS; CANCEL JOB 'job-123';", + vec!["SHOW JOBS", "CANCEL JOB 'job-123'"], + ), + ( + "SELECT 1 -- documentation; DELETE FROM customers\n;", + vec!["SELECT 1 -- documentation; DELETE FROM customers"], + ), + ( + "SELECT 1 /* documentation; DELETE FROM customers */; SELECT 2;", + vec![ + "SELECT 1 /* documentation; DELETE FROM customers */", + "SELECT 2", + ], + ), + ( + "/* outer; /* nested; DELETE FROM customers */ still a comment; */ SELECT 3;", + vec!["/* outer; /* nested; DELETE FROM customers */ still a comment; */ SELECT 3"], + ), + ( + "SELECT 1 /*! ; DELETE FROM customers */;", + vec!["SELECT 1 /*! ; DELETE FROM customers */"], + ), + ( + r#"SELECT 'it''s; unchanged', "col;""name", `back;``tick`; SELECT 'next'"#, + vec![ + r#"SELECT 'it''s; unchanged', "col;""name", `back;``tick`"#, + "SELECT 'next'", + ], + ), + ( + "SELECT $$text; -- still text$$, $tag$more; /* text */$tag$; SELECT 3;", + vec![ + "SELECT $$text; -- still text$$, $tag$more; /* text */$tag$", + "SELECT 3", + ], + ), + ( + r"SELECT E'it\'s; unchanged'; SELECT 2;", + vec![r"SELECT E'it\'s; unchanged'", "SELECT 2"], + ), + ( + "SELECT 'text; -- still a string /* not a comment */'; SELECT 2;", + vec![ + "SELECT 'text; -- still a string /* not a comment */'", + "SELECT 2", + ], + ), + ( + "SELECT 'café; 🦀';\r\n-- comment; DELETE FROM customers\r\nSELECT 2; ;", + vec![ + "SELECT 'café; 🦀'", + "-- comment; DELETE FROM customers\r\nSELECT 2", + ], + ), + ( + "; -- documentation; DELETE FROM customers\n; /* comment; SELECT 2 */; ;", + vec![], + ), + ] { + let (output, queries) = run_sql_file(script).await; + assert!( + output.status.success(), + "script {script:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(queries, expected, "script: {script:?}"); + } +} + +#[tokio::test] +async fn sql_files_with_unterminated_tokens_submit_no_statements() { + for script in [ + "SELECT 1; SELECT 'unterminated; DELETE FROM customers", + "SELECT 1; SELECT \"unterminated; DELETE FROM customers", + "SELECT 1; SELECT `unterminated; DELETE FROM customers", + "SELECT 1; SELECT $tag$unterminated; DELETE FROM customers", + "SELECT 1; /* unterminated; DELETE FROM customers", + ] { + let (output, queries) = run_sql_file(script).await; + assert!(!output.status.success(), "script: {script:?}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("Failed to tokenize SQL script"), + "unexpected error: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + queries.is_empty(), + "submitted SQL for {script:?}: {queries:?}" + ); + } +} + +#[tokio::test] +async fn ca_cert_enables_a_tls_flight_sql_query() { + let certs = generate_certs(); + let dir = tempfile::tempdir().unwrap(); + let ca_path = write_pem(&dir, "ca.pem", &certs.ca_pem); + let (addr, _shutdown) = start_tls_server(&certs).await; + + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()) + .with_tls(TlsOptions { + ca_cert: Some(ca_path), + ..TlsOptions::default() + }); + + executor + .connect(&format!("https://{addr}")) + .await + .expect("TLS connect with the signing CA should succeed"); + assert!(executor.is_connected().await); + + let result = executor + .execute_query("SELECT 1") + .await + .expect("query over TLS should succeed"); + match result { + SqlResult::Query(batches) => { + let rows: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect(); + assert_eq!(rows, vec![ANSWER]); + } + other => panic!("expected a query result, got {other:?}"), + } +} + +#[tokio::test] +async fn tls_connect_fails_without_the_signing_ca() { + let certs = generate_certs(); + let (addr, _shutdown) = start_tls_server(&certs).await; + + // No CA configured: the server's certificate chains to a CA that is not in + // the platform trust store, so verification must reject it. + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()); + + assert!( + executor.connect(&format!("https://{addr}")).await.is_err(), + "an untrusted server certificate must not be accepted" + ); + assert!(!executor.is_connected().await); +} + +#[tokio::test] +async fn tls_connect_fails_with_an_unrelated_ca() { + let certs = generate_certs(); + // A second, unrelated CA: right file shape, wrong signer. + let other = generate_certs(); + let dir = tempfile::tempdir().unwrap(); + let unrelated_ca = write_pem(&dir, "other-ca.pem", &other.ca_pem); + let (addr, _shutdown) = start_tls_server(&certs).await; + + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()) + .with_tls(TlsOptions { + ca_cert: Some(unrelated_ca), + ..TlsOptions::default() + }); + + assert!( + executor.connect(&format!("https://{addr}")).await.is_err(), + "a certificate signed by a different CA must not be accepted" + ); +} + +#[tokio::test] +async fn a_missing_ca_cert_file_is_reported() { + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()) + .with_tls(TlsOptions { + ca_cert: Some("/nonexistent/ca.pem".to_string()), + ..TlsOptions::default() + }); + + let err = executor + .connect("https://127.0.0.1:1") + .await + .expect_err("a missing CA file must fail loudly"); + assert!( + err.to_string().contains("/nonexistent/ca.pem"), + "error should name the missing file, got: {err}" + ); +} + +#[tokio::test] +async fn a_client_certificate_satisfies_an_mtls_server() { + let certs = generate_certs(); + let dir = tempfile::tempdir().unwrap(); + let ca_path = write_pem(&dir, "ca.pem", &certs.ca_pem); + let cert_path = write_pem(&dir, "client.pem", &certs.client_cert_pem); + let key_path = write_pem(&dir, "client-key.pem", &certs.client_key_pem); + let (addr, _shutdown) = start_mtls_server(&certs).await; + + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()) + .with_tls(TlsOptions { + ca_cert: Some(ca_path), + client_cert: Some(cert_path), + client_key: Some(key_path), + }); + + executor + .connect(&format!("https://{addr}")) + .await + .expect("mTLS connect with a CA-signed client certificate should succeed"); + executor + .execute_query("SELECT 1") + .await + .expect("query over mTLS should succeed"); +} + +#[tokio::test] +async fn an_mtls_server_rejects_a_client_with_no_certificate() { + let certs = generate_certs(); + let dir = tempfile::tempdir().unwrap(); + let ca_path = write_pem(&dir, "ca.pem", &certs.ca_pem); + let (addr, _shutdown) = start_mtls_server(&certs).await; + + // Trusts the server, but presents no identity of its own. + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()) + .with_tls(TlsOptions { + ca_cert: Some(ca_path), + ..TlsOptions::default() + }); + + // TLS 1.3 sends the client certificate after the client considers the + // handshake done, so the rejection can surface at connect or at the first + // request. Either way the exchange must not succeed. + let rejected = match executor.connect(&format!("https://{addr}")).await { + Err(_) => true, + Ok(()) => executor.execute_query("SELECT 1").await.is_err(), + }; + assert!( + rejected, + "an mTLS server must reject a client with no certificate" + ); +} + +#[tokio::test] +async fn a_client_certificate_without_its_key_is_rejected_at_resolve() { + use lancedb_cli::server_config::ConnectionArgs; + + let args = ConnectionArgs { + client_cert: Some("/tmp/client.pem".to_string()), + ..ConnectionArgs::default() + }; + let err = args + .resolve(None) + .expect_err("a client certificate without a key must be rejected"); + assert!( + err.to_string().contains("--client-key"), + "error should name the missing flag, got: {err}" + ); +} diff --git a/rust/lancedb/examples/simple.rs b/rust/lancedb/examples/simple.rs index 14846e037..d4887224d 100644 --- a/rust/lancedb/examples/simple.rs +++ b/rust/lancedb/examples/simple.rs @@ -7,10 +7,10 @@ use std::sync::Arc; -use arrow_array::types::Float32Type; -use arrow_array::{FixedSizeListArray, Int32Array, RecordBatch}; -use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; +use lancedb::arrow::arrow_array::types::Float32Type; +use lancedb::arrow::arrow_array::{FixedSizeListArray, Int32Array, RecordBatch}; +use lancedb::arrow::arrow_schema::{DataType, Field, Schema}; use lancedb::connection::Connection; use lancedb::index::Index; use lancedb::query::{ExecutableQuery, QueryBase}; diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index 05650d7c2..409edcc2a 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -1,13 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! Lance blob v2 columns store large binary payloads out of line. +//! Lance blob columns store large binary payloads out of line. //! -//! Declare a column with [`blob`]. On write, [`crate::table::Table::add`] coerces +//! The read APIs support both legacy blob v1 and blob v2 columns. +//! +//! Declare a blob v2 column with [`blob`]. On write, [`crate::table::Table::add`] coerces //! raw `Binary` / `LargeBinary` into the blob struct layout. Queries return //! small descriptors, not bytes. //! -//! Blob tables require Lance file format >= 2.2. `_rowid` values stay valid +//! Blob v2 tables require Lance file format >= 2.2. `_rowid` values stay valid //! after compaction when the table has stable row ids. Overwrite is a new //! create and does not keep the previous table's stable row id setting. @@ -20,11 +22,120 @@ use arrow_schema::{DataType, Field, Schema}; use lance::dataset::{BlobRangeRequest as LanceBlobRangeRequest, Dataset, WriteParams}; use lance_arrow::FieldExt; use lance_file::version::{ConcreteFileVersion, LanceFileVersion}; -use lance_io::object_store::ObjectStore; +use lance_io::object_store::{ObjectStore, uri_to_url}; use object_store::path::Path; +use serde::{Deserialize, Serialize}; use crate::error::{Error, Result}; +/// A stored Blob V2 descriptor with the source needed to reopen its snapshot. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BlobDescriptor { + /// Canonical Blob V2 storage kind (0 through 5). + pub kind: u8, + /// Stored offset within the backing object. + pub position: u64, + /// Stored length; zero on an external blob can mean unspecified. + pub size: u64, + /// Stored sidecar or base identifier. + pub blob_id: u32, + /// Stored external URI or managed path. + pub blob_uri: String, + /// Source identity captured by the query. + pub source: BlobDescriptorSource, +} + +/// The pinned source of a descriptor returned by SQL. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BlobDescriptorSource { + /// URI of the dataset on the source branch. + pub uri: String, + /// Exact table version read by the query. + pub version: u64, + /// Commit timestamp in microseconds, distinguishing recreated tables. + pub committed_at_micros: u64, + /// Source branch; `None` identifies main. + pub branch: Option, + /// Blob column path in the source table. + pub column: String, + /// Row ID or row address, as specified by `row_is_address`. + pub row_reference: u64, + /// Whether the row reference is a physical address. + pub row_is_address: bool, +} + +impl BlobDescriptor { + pub(crate) fn validate(&self) -> Result<()> { + if self.kind > 5 + || self.source.version == 0 + || self.source.uri.is_empty() + || self.source.column.is_empty() + { + return Err(Error::InvalidInput { + message: "invalid stored blob descriptor or missing pinned source".into(), + }); + } + Ok(()) + } +} + +pub(crate) async fn open_native_blob_file( + dataset: &Dataset, + descriptor: &BlobDescriptor, +) -> Result { + descriptor.validate()?; + let source = &descriptor.source; + let expected_uri = dataset + .branch_location() + .find_branch(source.branch.as_deref())? + .uri; + if uri_to_url(&expected_uri)? != uri_to_url(&source.uri)? { + return Err(Error::InvalidInput { + message: "blob descriptor belongs to a different table".into(), + }); + } + let dataset = Arc::new( + dataset + .checkout_version(lance::dataset::refs::Ref::Version( + source.branch.clone(), + Some(source.version), + )) + .await?, + ); + if uri_to_url(dataset.uri())? != uri_to_url(&source.uri)? { + return Err(Error::InvalidInput { + message: "blob descriptor belongs to a different table".into(), + }); + } + if dataset.manifest().timestamp_nanos / 1_000 != u128::from(source.committed_at_micros) { + return Err(Error::InvalidInput { + message: "blob descriptor source snapshot has been replaced".into(), + }); + } + ensure_blob_v2_column(dataset.schema(), &source.column)?; + let mut files = if source.row_is_address { + dataset + .take_blobs_by_addresses(&[source.row_reference], &source.column) + .await? + } else { + dataset + .take_blobs(&[source.row_reference], &source.column) + .await? + }; + if files.len() != 1 { + return Err(Error::InvalidInput { + message: "blob descriptor does not resolve to one stored value".into(), + }); + } + files + .pop() + .flatten() + .map(Into::into) + .ok_or_else(|| Error::InvalidInput { + message: "non-null blob descriptor resolved to a null value".into(), + }) +} + /// Seekable handle for one blob value, backed by local storage or a remote /// HTTP byte-range endpoint. #[derive(Debug)] @@ -177,8 +288,8 @@ impl BlobFile { } } - /// Physical byte offset in the data file. `None` on remote handles. The - /// Cloud byte-range route does not expose storage layout. + /// Physical byte offset in the data file. `None` on LanceDB Distributed handles. The + /// server's byte-range route does not expose storage layout. pub fn position(&self) -> Option { match &self.inner { BlobFileInner::Native(file) => Some(file.position()), @@ -187,8 +298,8 @@ impl BlobFile { } } - /// Path of the data file holding the blob. `None` on remote handles. The - /// Cloud byte-range route does not expose storage layout. + /// Path of the data file holding the blob. `None` on LanceDB Distributed handles. The + /// server's byte-range route does not expose storage layout. pub fn data_path(&self) -> Option<&Path> { match &self.inner { BlobFileInner::Native(file) => Some(file.data_path()), @@ -197,8 +308,8 @@ impl BlobFile { } } - /// Native storage layout. `None` on remote handles. The Cloud byte-range - /// route does not expose layout. + /// Native storage layout. `None` on LanceDB Distributed handles. The server's + /// byte-range route does not expose layout. pub fn kind(&self) -> Option { match &self.inner { BlobFileInner::Native(file) => Some(file.kind()), @@ -207,7 +318,7 @@ impl BlobFile { } } - /// External URI for native handles. Remote handles do not expose storage URIs. + /// External URI for native handles. LanceDB Distributed handles do not expose storage URIs. pub fn uri(&self) -> Option<&str> { match &self.inner { BlobFileInner::Native(file) => file.uri(), @@ -358,14 +469,27 @@ pub(crate) fn field_tree_has_blob_v2(field: &Field) -> bool { } } -/// Collects the dotted paths of row-addressable blob v2 columns under `field`. +fn field_tree_has_blob(field: &Field) -> bool { + if field.is_blob() { + return true; + } + match field.data_type() { + DataType::Struct(children) => children.iter().any(|c| field_tree_has_blob(c)), + DataType::List(child) | DataType::LargeList(child) | DataType::FixedSizeList(child, _) => { + field_tree_has_blob(child) + } + _ => false, + } +} + +/// Collects the dotted paths of row-addressable blob columns under `field`. fn collect_blob_paths(field: &Field, prefix: &str, paths: &mut Vec) { let path = if prefix.is_empty() { field.name().clone() } else { format!("{prefix}.{}", field.name()) }; - if field.is_blob_v2() { + if field.is_blob() { paths.push(path); return; } @@ -382,7 +506,7 @@ fn is_list_blob_path(field: &Field, prefix: &str, column: &str, inside_list: boo } else { format!("{prefix}.{}", field.name()) }; - if field.is_blob_v2() { + if field.is_blob() { return inside_list && column == path; } match field.data_type() { @@ -390,7 +514,7 @@ fn is_list_blob_path(field: &Field, prefix: &str, column: &str, inside_list: boo .iter() .any(|child| is_list_blob_path(child, &path, column, inside_list)), DataType::List(child) | DataType::LargeList(child) | DataType::FixedSizeList(child, _) => { - (column == path && field_tree_has_blob_v2(child)) + (column == path && field_tree_has_blob(child)) || is_list_blob_path(child, &path, column, true) } _ => false, @@ -418,7 +542,7 @@ pub(crate) fn has_blob_columns(schema: &Schema) -> bool { schema.fields().iter().any(|f| field_tree_has_blob_v2(f)) } -/// Row-addressable blob v2 column paths in `schema`, in declaration order. +/// Row-addressable blob v1 and v2 column paths in `schema`, in declaration order. /// Struct-nested blobs use dotted paths (e.g. `info.blob`); list-nested blobs /// are omitted because a row id cannot identify an individual list element. pub(crate) fn blob_column_names(schema: &Schema) -> Vec { @@ -448,15 +572,37 @@ pub(crate) fn ensure_blob_storage_version(schema: &Schema, params: &mut WritePar } } -/// Validate that `column` exists and is a blob v2 column. -/// -/// Legacy v1 columns (`lance-encoding:blob`) error with a migration hint. -pub(crate) fn ensure_blob_v2_column( +/// Validate that `column` exists and is a row-addressable blob v1 or v2 column. +pub(crate) fn ensure_blob_column( schema: &lance_core::datatypes::Schema, column: &str, ) -> Result<()> { // A top-level blob cannot have a list ancestor. Keep the common read path // from converting the entire schema just to validate that condition. + if column.contains('.') + || schema + .field(column) + .is_none_or(|field| !field.is_blob() && !field.is_blob_v2()) + { + reject_list_blob_column(&Schema::from(schema), column)?; + } + match schema.field(column) { + Some(field) if field.is_blob() || field.is_blob_v2() => Ok(()), + Some(_) => Err(Error::InvalidInput { + message: format!("column '{column}' is not a blob column"), + }), + None => Err(Error::InvalidInput { + message: format!("no column named '{column}' in this table"), + }), + } +} + +/// Validate a blob v2 descriptor source column. +/// +/// Stored SQL descriptors only describe blob v2 layouts. Keep legacy v1 +/// support on the row-id fetch APIs instead of broadening descriptor +/// reopening to a storage format it cannot encode. +fn ensure_blob_v2_column(schema: &lance_core::datatypes::Schema, column: &str) -> Result<()> { if column.contains('.') || schema.field(column).is_none_or(|field| !field.is_blob_v2()) { reject_list_blob_column(&Schema::from(schema), column)?; } @@ -578,6 +724,8 @@ async fn map_blob_take_error( let message = err.to_string(); let missing_row_id = message.contains("must not target deleted rows") || message.contains("belongs to non-existent fragment") + || (message.contains("Unknown fragment id ") + && message.contains("in fragment filter; not part of the current dataset version")) || (message.contains("Invalid read params ") && message.contains("addressable rows")) || message.contains("Could not resolve all requested row IDs"); @@ -597,7 +745,7 @@ pub(crate) async fn take_blob_ranges_aligned( column: &str, requests: &[BlobRangeRequest], ) -> Result { - ensure_blob_v2_column(dataset.schema(), column)?; + ensure_blob_column(dataset.schema(), column)?; if requests.is_empty() { return Ok(LargeBinaryBuilder::new().finish()); } @@ -638,7 +786,7 @@ pub(crate) async fn take_blobs_aligned( column: &str, row_ids: &[u64], ) -> Result { - ensure_blob_v2_column(dataset.schema(), column)?; + ensure_blob_column(dataset.schema(), column)?; if row_ids.is_empty() { return Ok(LargeBinaryBuilder::new().finish()); } @@ -671,7 +819,7 @@ pub(crate) async fn take_blob_files_aligned( column: &str, row_ids: &[u64], ) -> Result>> { - ensure_blob_v2_column(dataset.schema(), column)?; + ensure_blob_column(dataset.schema(), column)?; if row_ids.is_empty() { return Ok(Vec::new()); } @@ -819,20 +967,35 @@ mod tests { } #[test] - fn legacy_v1_blob_column_is_rejected_with_migration_hint() { + fn legacy_v1_blob_columns_are_row_addressable() { let legacy = Field::new("image", DataType::LargeBinary, true).with_metadata( std::collections::HashMap::from([( "lance-encoding:blob".to_string(), "true".to_string(), )]), ); - let arrow_schema = Schema::new(vec![legacy]); + let arrow_schema = Schema::new(vec![ + legacy.clone(), + Field::new("info", DataType::Struct(vec![legacy.clone()].into()), true), + Field::new("images", DataType::List(Arc::new(legacy)), true), + ]); let lance_schema = lance_core::datatypes::Schema::try_from(&arrow_schema).unwrap(); - let err = ensure_blob_v2_column(&lance_schema, "image").unwrap_err(); - assert!(matches!(err, Error::InvalidInput { .. })); - assert!(err.to_string().contains("legacy blob column")); - assert!(err.to_string().contains("lance.blob.v2")); + ensure_blob_column(&lance_schema, "image").unwrap(); + ensure_blob_column(&lance_schema, "info.image").unwrap(); + assert_eq!( + blob_column_names(&arrow_schema), + vec!["image", "info.image"] + ); + for path in ["images", "images.image"] { + let err = ensure_blob_column(&lance_schema, path).unwrap_err(); + assert!( + err.to_string() + .contains("blobs inside lists cannot be fetched") + ); + } + // Legacy columns do not require the blob v2 write format. + assert!(!has_blob_columns(&arrow_schema)); } #[test] @@ -840,10 +1003,10 @@ mod tests { let arrow_schema = Schema::new(vec![Field::new("id", DataType::Int64, false)]); let lance_schema = lance_core::datatypes::Schema::try_from(&arrow_schema).unwrap(); - let err = ensure_blob_v2_column(&lance_schema, "id").unwrap_err(); + let err = ensure_blob_column(&lance_schema, "id").unwrap_err(); assert!(err.to_string().contains("'id' is not a blob column")); - let err = ensure_blob_v2_column(&lance_schema, "missing").unwrap_err(); + let err = ensure_blob_column(&lance_schema, "missing").unwrap_err(); assert!(err.to_string().contains("no column named 'missing'")); } diff --git a/rust/lancedb/src/catalog.rs b/rust/lancedb/src/catalog.rs index ad8674b77..18373ed5a 100644 --- a/rust/lancedb/src/catalog.rs +++ b/rust/lancedb/src/catalog.rs @@ -59,7 +59,7 @@ impl> From for CreateDatabaseRequest { } } -/// Options for restricted database deletion. Tables must be removed first. +/// Options for database deletion. The database must be empty unless `cascade` is set. #[derive(Clone, Debug)] #[non_exhaustive] pub struct DropDatabaseRequest { @@ -67,6 +67,8 @@ pub struct DropDatabaseRequest { pub name: String, /// Succeed if the database is absent. pub ignore_missing: bool, + /// Drop everything in the database first. + pub cascade: bool, } impl DropDatabaseRequest { @@ -75,6 +77,7 @@ impl DropDatabaseRequest { Self { name: name.into(), ignore_missing: false, + cascade: false, } } @@ -83,6 +86,13 @@ impl DropDatabaseRequest { self.ignore_missing = value; self } + + /// Drop every table, view, function, secret and namespace in the database first. The + /// server cleans up their storage in the background, and the name stays taken until then. + pub fn cascade(mut self, value: bool) -> Self { + self.cascade = value; + self + } } impl> From for DropDatabaseRequest { @@ -204,7 +214,7 @@ pub trait Catalog: Send + Sync + std::fmt::Debug + 'static { fn uri(&self) -> &str; /// Create a database, or open it when `exist_ok` permits. async fn create_database(&self, request: CreateDatabaseRequest) -> Result>; - /// Drop an empty database. This must not cascade to tables. + /// Drop a database, which must be empty unless the request cascades. async fn drop_database(&self, request: DropDatabaseRequest) -> Result<()>; /// List a page of database names. async fn list_databases(&self, request: ListDatabasesRequest) -> Result; @@ -267,7 +277,7 @@ impl CatalogConnection { )) } - /// Drop an empty database; pass a name or [`DropDatabaseRequest`] for additional options. + /// Drop a database; pass a name or [`DropDatabaseRequest`] for options such as `cascade`. pub async fn drop_database(&self, request: impl Into) -> Result<()> { self.catalog.drop_database(request.into()).await } diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 6e9fd01af..147be8c32 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -13,7 +13,7 @@ use lance::dataset::refs::MAIN_BRANCH; use lance_namespace::models::{ CreateNamespaceRequest, CreateNamespaceResponse, DescribeNamespaceRequest, DescribeNamespaceResponse, DropNamespaceRequest, DropNamespaceResponse, ListNamespacesRequest, - ListNamespacesResponse, ListTablesRequest, ListTablesResponse, + ListTablesRequest, }; #[cfg(feature = "aws")] use object_store::aws::AwsCredential; @@ -28,7 +28,7 @@ use crate::database::{ }; use crate::embeddings::{EmbeddingRegistry, MemoryRegistry}; use crate::error::{Error, Result}; -use crate::listing::{Listing, ListingOptions}; +use crate::listing::{Listing, ListingOptions, ListingPage}; #[cfg(feature = "remote")] use crate::remote::{ client::ClientConfig, @@ -176,6 +176,8 @@ impl OpenTableBuilder { /// Advanced parameters that can be used to customize table reads /// + /// LanceDB Distributed 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 { self.request.lance_read_params = Some(params); @@ -336,7 +338,7 @@ pub struct CloneTableBuilder { request: CloneTableRequest, } -/// Builder for asynchronously executing a SQL statement on a remote database. +/// Builder for asynchronously executing a SQL statement on a LanceDB Distributed database. pub struct ExecuteQueryAsyncBuilder { parent: Arc, request: ExecuteQueryRequest, @@ -377,12 +379,10 @@ impl ExecuteQueryAsyncBuilder { /// Do not follow a named placeholder directly with `$`: `$a$` starts a /// dollar-quoted string. /// - /// A parameterized statement runs on the call that returns its rows rather - /// than detached from it: cancelling the query, or dropping its handle - /// before reading it, stops the statement on the server. Its status follows - /// that stream too -- it reports `Running` until the reader has received - /// every row -- so open the reader directly rather than waiting for - /// `Finished`. + /// With or without parameters, the server may stream rows on the initial + /// call or return a polling continuation. The reader follows either path + /// transparently. Open it directly instead of waiting for `Finished`: + /// directly streamed queries need their reader to make progress. /// /// # Example /// @@ -504,13 +504,13 @@ impl Connection { &self.internal } - /// Start executing SQL on a remote LanceDB database. + /// Start executing SQL on a LanceDB Distributed database. /// /// The query can reference tables in other databases with SQL dot notation. /// Use [`ExecuteQueryAsyncBuilder::default_namespace_path`] to avoid qualifying /// tables in the default namespace, and [`ExecuteQueryAsyncBuilder::parameters`] /// to bind Arrow values to `$1` / `$name` placeholders instead of writing them - /// into the SQL text. Local connections return [`Error::NotSupported`]. + /// into the SQL text. LanceDB Embedded connections return [`Error::NotSupported`]. /// /// # Example /// @@ -535,14 +535,20 @@ impl Connection { ExecuteQueryAsyncBuilder::new(self.internal.clone(), query.into()) } + /// Establish the remote SQL transport without executing a statement. + /// This checks connectivity and TLS; authentication is checked by subsequent requests. + pub async fn check_sql_connection(&self) -> Result<()> { + self.internal.check_sql_connection().await + } + /// Describe a submitted SQL query by its connection-scoped id. /// /// This performs one bounded status poll using state retained by this /// connection. Running state with a live query handle is not evicted; /// abandoned state has bounded retention, and server expiration is /// honored. Terminal state is retained briefly. - /// Query ids are not portable to another connection. Local connections - /// return [`Error::NotSupported`]. + /// Query ids are not portable to another connection. LanceDB Embedded + /// connections return [`Error::NotSupported`]. pub async fn describe_query( &self, query_id: uuid::Uuid, @@ -654,8 +660,8 @@ impl Connection { /// /// 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 remote-only. - /// Local databases return [`Error::NotSupported`]. + /// [`crate::function::FunctionVersion`]. Creation is supported only in LanceDB Distributed. + /// LanceDB Embedded databases return [`Error::NotSupported`]. /// pub async fn create_function_async( &self, @@ -671,7 +677,7 @@ impl Connection { /// /// Both the logical name and server-assigned version id are required; /// mutable aliases and latest-version lookup are intentionally absent. - /// Local databases return [`Error::NotSupported`]. + /// LanceDB Embedded databases return [`Error::NotSupported`]. pub async fn get_function( &self, name: impl AsRef, @@ -686,7 +692,7 @@ 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. Local databases return + /// Results are ordered by Function name then version. LanceDB Embedded databases return /// [`Error::NotSupported`]. /// /// # Example @@ -724,7 +730,7 @@ impl Connection { /// Remove the current Function name binding, retaining the object history. /// /// Returns `true` when the server appended a Dropped transition and - /// `false` for an idempotent replay. Local databases return + /// `false` for an idempotent replay. LanceDB Embedded databases return /// [`Error::NotSupported`]. pub async fn drop_function( &self, @@ -742,7 +748,7 @@ impl Connection { /// 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. Local databases return [`Error::NotSupported`]. + /// finished and has no id. LanceDB Embedded databases return [`Error::NotSupported`]. pub async fn drop_function_async( &self, name: impl AsRef, @@ -758,7 +764,7 @@ impl Connection { /// /// Fails if the name is taken, so a create can never silently become a /// rotation. There is no API that reads a stored credential back; the only - /// consumer is a Function that binds the Secret by name. Local databases + /// consumer is a Function that binds the Secret by name. LanceDB Embedded databases /// return [`Error::NotSupported`]. pub async fn create_secret( &self, @@ -777,7 +783,7 @@ impl Connection { /// Fails if it does not exist. Every Function bound to the Secret resolves /// the new value from its next execution, and no new Function version is /// minted -- which is what lets a rotation reach columns pinned to a - /// version registered before it. Local databases return + /// version registered before it. LanceDB Embedded databases return /// [`Error::NotSupported`]. pub async fn alter_secret( &self, @@ -794,7 +800,7 @@ impl Connection { /// The names of every Secret in this database. /// /// Names only. No path in this API returns a stored credential, by - /// construction rather than by policy. Local databases return + /// construction rather than by policy. LanceDB Embedded databases return /// [`Error::NotSupported`]. /// /// Results are fetched lazily, one page at a time. See [`Listing`] @@ -832,7 +838,7 @@ impl Connection { /// Functions bound to it fail at their next job, naming the Secret; that /// is the revocation path. The name becomes free to reuse, and a new /// Secret under it is picked up by everything still bound to that name. - /// Local databases return [`Error::NotSupported`]. + /// LanceDB Embedded databases return [`Error::NotSupported`]. pub async fn drop_secret( &self, name: impl AsRef, @@ -848,7 +854,7 @@ impl Connection { /// /// Never the value. The type it returns has no field for one, so this is a /// property of the API rather than of what the caller chooses to read. - /// Local databases return [`Error::NotSupported`]. + /// LanceDB Embedded databases return [`Error::NotSupported`]. pub async fn describe_secret( &self, name: impl AsRef, @@ -868,7 +874,7 @@ impl Connection { /// /// There is no replace: a name already taken is an error, and changing a /// view is a drop followed by a create, each authorized against what it - /// actually touches. Local databases return [`Error::NotSupported`]. + /// actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// # Example /// @@ -917,7 +923,7 @@ impl Connection { /// schema that query resolved to. /// /// The schema is the one recorded at creation. A source altered since then - /// shows up when the view is read, not here. Local databases return + /// shows up when the view is read, not here. LanceDB Embedded databases return /// [`Error::NotSupported`]. pub async fn describe_view( &self, @@ -934,7 +940,7 @@ impl Connection { /// /// 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. Local databases return [`Error::NotSupported`]. + /// waiting on it. 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 @@ -945,7 +951,7 @@ impl Connection { /// 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. Local databases return [`Error::NotSupported`]. + /// finished and has no id. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// ```no_run /// # use lancedb::Connection; @@ -969,7 +975,7 @@ impl Connection { /// The names of the views in one namespace. /// /// Names only; a definition is query metadata and comes from - /// [`Self::describe_view`]. Local databases return [`Error::NotSupported`]. + /// [`Self::describe_view`]. LanceDB Embedded 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. @@ -1003,7 +1009,7 @@ impl Connection { /// Rename a table in the database. /// - /// This is only supported in LanceDB Cloud. + /// This is only supported in LanceDB Distributed. pub async fn rename_table( &self, old_name: impl AsRef, @@ -1139,12 +1145,43 @@ impl Connection { self.internal.drop_all_tables(namespace_path).await } - /// List immediate child namespace names in the given namespace - pub async fn list_namespaces( + /// Lazily list immediate child namespace names. Each request asks for at + /// most 100 names unless `options.page_limit` is set. + /// + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// use futures::TryStreamExt; + /// let names: Vec = connection.list_namespaces(&[], Default::default()) + /// .try_collect().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn list_namespaces( &self, - request: ListNamespacesRequest, - ) -> Result { - self.internal.list_namespaces(request).await + 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)?; + let response = database + .list_namespaces(ListNamespacesRequest { + id: Some(namespace_path), + page_token: options.page_token, + limit: Some(options.page_limit.unwrap_or(100) as i32), + ..Default::default() + }) + .await?; + Ok(ListingPage { + items: response.namespaces, + page_token: response.page_token, + }) + } + }) } /// Create a new namespace @@ -1176,7 +1213,7 @@ impl Connection { /// For ListingDatabase, it is the equivalent DirectoryNamespace. /// For RemoteDatabase, it is the equivalent RestNamespace. /// - /// Remote connections using dynamic headers forward them through the + /// LanceDB Distributed 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 @@ -1187,7 +1224,7 @@ impl Connection { /// - impl_type: "dir" for DirectoryNamespace, "rest" for RestNamespace /// - properties: configuration properties for the namespace /// - /// Remote connections using dynamic headers cannot be exported because the + /// LanceDB Distributed connections using dynamic headers cannot be exported because the /// namespace client config only carries static headers. pub async fn namespace_client_config( &self, @@ -1195,23 +1232,43 @@ impl Connection { self.internal.namespace_client_config().await } - /// List tables with pagination support + /// Lazily list tables. Each request asks for at most 100 names unless + /// `options.page_limit` is set. /// - /// The default limit is 100 tables per page for both local and remote connections, - /// including namespaces. Zero returns an empty page without a continuation token. - /// Follow the response's opaque `page_token` until it is absent to retrieve every table; - /// a page can contain fewer than the limit even when more tables remain. - pub async fn list_tables(&self, mut request: ListTablesRequest) -> Result { - // Apply the SDK's page size here so every backend receives the same request. - let limit = request.limit.get_or_insert(100); - if *limit <= 0 { - return Ok(ListTablesResponse { - context: None, - tables: Vec::new(), - page_token: None, - }); - } - self.internal.list_tables(request).await + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// use futures::TryStreamExt; + /// let names: Vec = connection.list_tables(&[], Default::default()) + /// .try_collect().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn list_tables( + &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)?; + let response = database + .list_tables(ListTablesRequest { + id: Some(namespace_path), + page_token: options.page_token, + limit: Some(options.page_limit.unwrap_or(100) as i32), + ..Default::default() + }) + .await?; + Ok(ListingPage { + items: response.tables, + page_token: response.page_token, + }) + } + }) } /// Get the in-memory embedding registry. @@ -1229,9 +1286,10 @@ pub struct ConnectRequest { /// /// ### Accepted URI formats /// - /// - `/path/to/database` - local database on file system. + /// - `/path/to/database` - database on the local file system. /// - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud object store - /// - `db://dbname` - LanceDB Cloud + /// - `db://dbname` - LanceDB Enterprise or LanceDB Cloud (legacy) + /// - `db://` with a host override - LanceDB Enterprise tables in the storage root pub uri: String, #[cfg(feature = "remote")] @@ -1310,9 +1368,9 @@ impl ConnectBuilder { } } - /// Set the LanceDB Cloud API key. + /// Set the API key for LanceDB Enterprise or LanceDB Cloud (legacy). /// - /// This option is only used when connecting to LanceDB Cloud (db:// URIs) + /// This option is only used for `db://` URIs /// and will be ignored for other URIs. /// /// # Arguments @@ -1326,9 +1384,9 @@ impl ConnectBuilder { self } - /// Set the LanceDB Cloud region. + /// Set the LanceDB Cloud (legacy) region. /// - /// This option is only used when connecting to LanceDB Cloud (db:// URIs) + /// This option is only used when connecting to LanceDB Cloud (`db://` URIs) /// and will be ignored for other URIs. /// /// # Arguments @@ -1342,10 +1400,12 @@ impl ConnectBuilder { self } - /// Set the LanceDB Cloud host override. + /// Set the host override, used to connect to LanceDB Enterprise. /// - /// This option is only used when connecting to LanceDB Cloud (db:// URIs) + /// This option is only used for `db://` URIs /// and will be ignored for other URIs. + /// Use the URI `db://` together with a host override to connect to + /// LanceDB Enterprise tables stored directly in the storage root. /// /// # Arguments /// @@ -1359,7 +1419,7 @@ impl ConnectBuilder { self } - /// Set the SQL service host override for a remote connection. + /// Set the SQL service host override for a LanceDB Enterprise connection. /// /// The SQL client is initialized lazily when the connection first executes /// SQL and is retained for the connection's lifetime. @@ -1378,13 +1438,13 @@ impl ConnectBuilder { /// native LanceDB databases. /// /// See [crate::remote::db::RemoteDatabaseOptions] for the options available for - /// LanceDB Cloud and LanceDB Enterprise. + /// LanceDB Enterprise and LanceDB Cloud (legacy). pub fn database_options(mut self, database_options: &dyn DatabaseOptions) -> Self { database_options.serialize_into_map(&mut self.request.options); self } - /// Set the LanceDB Cloud client configuration. + /// Set the HTTP client configuration for LanceDB Enterprise or LanceDB Cloud (legacy). /// /// ```no_run /// # use lancedb::connect; @@ -1408,7 +1468,7 @@ impl ConnectBuilder { self } - /// Configure OAuth authentication for LanceDB Cloud/Enterprise. + /// Configure OAuth authentication for LanceDB Enterprise. /// /// This creates an [`OAuthHeaderProvider`](crate::remote::OAuthHeaderProvider) /// from the given config and sets it as the header provider. OAuth cannot @@ -1502,6 +1562,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`]. /// /// When enabled, the connection uses the directory namespace database /// directly for all table operations and forces @@ -1537,6 +1598,7 @@ impl ConnectBuilder { } /// Set a custom session for object stores and caching. + /// LanceDB Distributed 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 @@ -1568,20 +1630,37 @@ impl ConnectBuilder { fn execute_remote(self) -> Result { use crate::remote::db::RemoteDatabaseOptions; + for (option, provided) in [ + ("session", self.request.session.is_some()), + ("manifest_enabled", self.request.manifest_enabled), + ( + "namespace_client_properties", + !self.request.namespace_client_properties.is_empty(), + ), + ] { + if provided { + return Err(Error::NotSupported { + message: format!( + "{option} is not supported for LanceDB Distributed connections" + ), + }); + } + } + let mut merged_options = self.request.options.clone(); Self::apply_env_defaults(&ENV_VARS_TO_STORAGE_OPTS, &mut merged_options); let sql_host_override = merged_options.get(OPT_REMOTE_SQL_HOST_OVERRIDE).cloned(); let options = RemoteDatabaseOptions::parse_from_map(&merged_options)?; let region = options.region.ok_or_else(|| Error::InvalidInput { - message: "A region is required when connecting to LanceDb Cloud".to_string(), + message: "A region is required when connecting to LanceDB Cloud".to_string(), })?; let api_key = match (&self.oauth_config, &options.api_key) { (Some(_), None) => String::new(), (Some(_), Some(_)) => { return Err(Error::InvalidInput { message: - "api_key and oauth_config cannot both be set when connecting to LanceDb Cloud" + "api_key and oauth_config cannot both be set when connecting to LanceDB Enterprise or LanceDB Cloud" .to_string(), }); } @@ -1589,7 +1668,7 @@ impl ConnectBuilder { (None, None) => { return Err(Error::InvalidInput { message: - "An api_key or oauth_config is required when connecting to LanceDb Cloud" + "An api_key or oauth_config is required when connecting to LanceDB Enterprise or LanceDB Cloud" .to_string(), }); } @@ -1598,7 +1677,7 @@ impl ConnectBuilder { if self.oauth_config.is_some() && self.request.client_config.header_provider.is_some() { return Err(Error::InvalidInput { message: - "oauth_config and client_config.header_provider cannot both be set when connecting to LanceDb Cloud" + "oauth_config and client_config.header_provider cannot both be set when connecting to LanceDB Enterprise or LanceDB Cloud" .to_string(), }); } @@ -1638,7 +1717,7 @@ impl ConnectBuilder { #[cfg(not(feature = "remote"))] fn execute_remote(self) -> Result { Err(Error::Runtime { - message: "cannot connect to LanceDb Cloud unless the 'remote' feature is enabled" + message: "cannot connect to LanceDB Enterprise or LanceDB Cloud unless the 'remote' feature is enabled" .to_string(), }) } @@ -1678,7 +1757,7 @@ impl ConnectBuilder { /// # Arguments /// /// * `uri` - URI where the database is located, can be a local directory, supported remote cloud storage, -/// or a LanceDB Cloud database. See [ConnectOptions::uri] for a list of accepted formats +/// or a LanceDB Enterprise or LanceDB Cloud (legacy) database. See [ConnectOptions::uri] for a list of accepted formats pub fn connect(uri: &str) -> ConnectBuilder { ConnectBuilder::new(uri) } @@ -1994,13 +2073,44 @@ mod tests { match result { Err(Error::InvalidInput { message }) if message - == "api_key and oauth_config cannot both be set when connecting to LanceDb Cloud" => + == "api_key and oauth_config cannot both be set when connecting to LanceDB Enterprise or LanceDB Cloud" => {} Err(err) => panic!("expected InvalidInput, got {err:?}"), Ok(_) => panic!("expected api_key and oauth_config to be rejected"), } } + #[cfg(feature = "remote")] + #[tokio::test] + async fn test_connect_remote_storage_root() { + let conn = ConnectBuilder::new("db://") + .region("us-east-1") + .api_key("my-api-key") + .host_override("https://example.com") + .execute() + .await + .unwrap(); + + let (impl_name, properties) = conn.namespace_client_config().await.unwrap(); + assert_eq!(impl_name, "rest"); + assert_eq!(properties["uri"], "https://example.com"); + assert!( + !properties.contains_key("header.x-lancedb-database"), + "storage-root connections must not send the x-lancedb-database header" + ); + + let result = ConnectBuilder::new("db://") + .region("us-east-1") + .api_key("my-api-key") + .execute() + .await; + assert!(matches!( + result, + Err(Error::InvalidInput { message }) + if message.contains("A host override is required") + )); + } + #[cfg(feature = "remote")] #[tokio::test] async fn test_connect_rejects_header_provider_with_oauth_config() { @@ -2046,7 +2156,7 @@ mod tests { match result { Err(Error::InvalidInput { message }) if message - == "oauth_config and client_config.header_provider cannot both be set when connecting to LanceDb Cloud" => + == "oauth_config and client_config.header_provider cannot both be set when connecting to LanceDB Enterprise or LanceDB Cloud" => {} Err(err) => panic!("expected InvalidInput, got {err:?}"), Ok(_) => panic!("expected header_provider and oauth_config to be rejected"), @@ -2305,26 +2415,11 @@ mod tests { } names.sort(); - // Walking in pages has to reach every table exactly once, with nothing lost at a - // page boundary. - let mut seen = Vec::with_capacity(names.len()); - let mut page_token = None; - loop { - let page = db - .list_tables(ListTablesRequest { - id: Some(Vec::new()), - limit: Some(2), - page_token, - ..Default::default() - }) - .await - .unwrap(); - seen.extend(page.tables); - page_token = page.page_token.filter(|token| !token.is_empty()); - if page_token.is_none() { - break; - } - } + let seen = futures::TryStreamExt::try_collect::>( + db.list_tables(&[], ListingOptions::default().page_limit(2)), + ) + .await + .unwrap(); assert_eq!(seen, names); } @@ -2350,37 +2445,20 @@ mod tests { .is_empty() ); - let first = db.list_tables(ListTablesRequest::default()).await.unwrap(); - assert_eq!(first.tables, names[..100]); + let mut listing = db.list_tables(&[], ListingOptions::default()); + assert_eq!(listing.num_page_results(), 0); + let first = listing.next_page().await.unwrap().unwrap(); + assert_eq!(first.items, names[..100]); assert!(first.page_token.is_some()); - let second = db - .list_tables(ListTablesRequest { - page_token: first.page_token, - ..Default::default() - }) - .await - .unwrap(); - assert_eq!(second.tables, names[100..]); + let second = listing.next_page().await.unwrap().unwrap(); + assert_eq!(second.items, names[100..]); assert!(second.page_token.is_none()); + assert!(listing.next_page().await.unwrap().is_none()); - let all = db - .list_tables(ListTablesRequest { - limit: Some(200), - ..Default::default() - }) - .await - .unwrap(); - assert_eq!(all.tables, names); - assert!(all.page_token.is_none()); - let empty = db - .list_tables(ListTablesRequest { - limit: Some(0), - ..Default::default() - }) - .await - .unwrap(); - assert!(empty.tables.is_empty()); - assert!(empty.page_token.is_none()); + let mut all = db.list_tables(&[], ListingOptions::default().page_limit(200)); + assert_eq!(all.next_page().await.unwrap().unwrap().items, names); + let mut invalid = db.list_tables(&[], ListingOptions::default().page_limit(0)); + assert!(invalid.next_page().await.is_err()); } #[tokio::test] diff --git a/rust/lancedb/src/connection/create_table.rs b/rust/lancedb/src/connection/create_table.rs index 1f28a42be..0eb11711c 100644 --- a/rust/lancedb/src/connection/create_table.rs +++ b/rust/lancedb/src/connection/create_table.rs @@ -55,6 +55,9 @@ impl CreateTableBuilder { } /// Apply the given write options when writing the initial data + /// + /// LanceDB Distributed 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; self @@ -80,6 +83,8 @@ impl CreateTableBuilder { /// Set multiple options for the storage layer. /// + /// Table-level storage options are not supported by LanceDB Distributed 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 05386e0b7..54d51c24f 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -192,7 +192,7 @@ impl CloneTableRequest { } } -/// A request to start a SQL statement on a remote database. +/// A request to start a SQL statement on a LanceDB Distributed database. #[derive(Clone, Debug)] pub struct ExecuteQueryRequest { /// The SQL text. @@ -579,7 +579,13 @@ pub trait Database: async fn resume_job(&self, _job_id: &str) -> Result { job_op_not_supported("resume_job") } - /// Start executing a SQL statement on a remote 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(), + }) + } + /// Start executing a SQL statement on a LanceDB Distributed database. async fn execute_query_async( &self, _request: ExecuteQueryRequest, diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 71e9f0ef1..d5749f974 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -750,26 +750,39 @@ impl ListingDatabase { uri.push_str(&format!("?{}", query_string)); } let commit_handler = commit_handler_from_url(&uri, &Some(object_store_params)).await?; + // One name that cannot be dropped must not strand the names after it: a caller + // dropping every table would otherwise be left with a partly dropped database that + // the same call cannot finish. Every name is attempted and the first failure is + // still what the call reports, so a caller matching on the error sees what it saw + // before. + let mut first_error = None; for name in names { let dir_name = format!("{}.{}", name, LANCE_EXTENSION); let full_path = self.base_path.clone().join(dir_name.clone()); - commit_handler.delete(&full_path).await?; + let dropped: Result<()> = async { + commit_handler.delete(&full_path).await?; - self.object_store - .remove_dir_all(full_path.clone()) - .await - .map_err(|err| match err { - // this error is not lance::Error::DatasetNotFound, as the method - // `remove_dir_all` may be used to remove something not be a dataset - lance::Error::NotFound { .. } => Error::TableNotFound { - name: name.clone(), - source: Box::new(err), - }, - _ => Error::from(err), - })?; + self.object_store + .remove_dir_all(full_path.clone()) + .await + .map_err(|err| match err { + // this error is not lance::Error::DatasetNotFound, as the method + // `remove_dir_all` may be used to remove something not be a dataset + lance::Error::NotFound { .. } => Error::TableNotFound { + name: name.clone(), + source: Box::new(err), + }, + _ => Error::from(err), + }) + } + .await; + + if let Err(err) = dropped { + first_error.get_or_insert(err); + } } - Ok(()) + first_error.map_or(Ok(()), Err) } /// Inherit storage options from the connection into the target map @@ -930,20 +943,18 @@ impl Database for ListingDatabase { if !request.namespace_path.is_empty() { return self.namespace_database().table_names(request).await; } - let mut f = self + // Only child directories can be tables, the same rule `list_tables` lists by: a + // loose object named like a table is not one, and a name handed back for it is a + // name the caller can neither open nor drop. + let dir_suffix = format!(".{LANCE_EXTENSION}"); + let listing = self .object_store - .read_dir(self.base_path.clone()) - .await? + .list_with_delimiter(Some(&self.base_path)) + .await?; + let mut f = listing + .common_prefixes .iter() - .map(Path::new) - .filter(|path| { - let is_lance = path - .extension() - .and_then(|e| e.to_str()) - .map(|e| e == LANCE_EXTENSION); - is_lance.unwrap_or(false) - }) - .filter_map(|p| p.file_stem().and_then(|s| s.to_str().map(String::from))) + .filter_map(|location| table_name(location, &dir_suffix)) .collect::>(); f.sort(); if let Some(start_after) = request.start_after { @@ -1250,7 +1261,7 @@ impl Database for ListingDatabase { }); } Err(Error::NotSupported { - message: "rename_table is not supported in LanceDB OSS".into(), + message: "rename_table is not supported in LanceDB Embedded".into(), }) } @@ -1697,6 +1708,63 @@ mod tests { .unwrap(); assert_eq!(page.tables, vec!["real"]); + + // The deprecated name listing answers the same question and so follows the same + // rule: a name it hands back has to be one a caller can open and drop. + #[allow(deprecated)] + let names = db.table_names(TableNamesRequest::default()).await.unwrap(); + assert_eq!(names, vec!["real"]); + } + + /// Dropping the database drops its tables and leaves everything else alone. A loose + /// `*.lance` object under the database prefix is not a table, so it is neither dropped + /// nor allowed to strand the tables that are. + #[tokio::test] + async fn test_drop_all_tables_leaves_loose_lance_files() { + let (tempdir, db) = setup_database().await; + create_tables(&db, &["a", "b"]).await; + // Sorts between the two tables, so a drop that stops at the first failure would + // leave `b` behind. + let loose = tempdir.path().join("aaa-loose.lance"); + std::fs::write(&loose, b"not a table").unwrap(); + + db.drop_all_tables(&[]).await.unwrap(); + + #[allow(deprecated)] + let names = db.table_names(TableNamesRequest::default()).await.unwrap(); + assert!(names.is_empty(), "a table survived the drop: {names:?}"); + assert!(!tempdir.path().join("a.lance").exists()); + assert!(!tempdir.path().join("b.lance").exists()); + assert!( + loose.exists(), + "a loose object was dropped as if it were a table" + ); + } + + /// A name that cannot be dropped does not strand the names after it: every name is + /// attempted, and the failure is still what the call reports. + #[tokio::test] + async fn test_drop_tables_attempts_every_name() { + let (tempdir, db) = setup_database().await; + create_tables(&db, &["a", "b"]).await; + + let result = db + .drop_tables(vec![ + "a".to_string(), + "missing".to_string(), + "b".to_string(), + ]) + .await; + + assert!( + matches!(result, Err(Error::TableNotFound { .. })), + "dropping a table that is not there did not report it: {result:?}" + ); + assert!(!tempdir.path().join("a.lance").exists()); + assert!( + !tempdir.path().join("b.lance").exists(), + "the table after the failing name was left behind" + ); } #[tokio::test] diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 32e7063a3..15f8c3cd3 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -316,6 +316,10 @@ impl PermutationBuilder { } else { self.sort_by_column(rows, ROW_ID).await? }; + // Bootstrap's output row count (num_samples) differs from its input row count + // (num_rows); every other strategy's output matches its input. The shuffler + // must be told the former, not assume it always equals the latter. + let output_rows = splitter.output_row_count(num_rows); let split_data = splitter.apply(rows, num_rows).await?; // Shuffle data if requested @@ -328,7 +332,7 @@ impl PermutationBuilder { temp_dir: self.config.temp_dir.clone(), max_rows_per_file: 10 * 1024 * 1024, }); - shuffler.shuffle(split_data, num_rows).await? + shuffler.shuffle(split_data, output_rows).await? } }; diff --git a/rust/lancedb/src/dataloader/permutation/split.rs b/rust/lancedb/src/dataloader/permutation/split.rs index cfa8e5235..b4e5deac1 100644 --- a/rust/lancedb/src/dataloader/permutation/split.rs +++ b/rust/lancedb/src/dataloader/permutation/split.rs @@ -11,6 +11,7 @@ use arrow_schema::{DataType, Field, Schema}; use datafusion_common::hash_utils::{RandomState, create_hashes}; use futures::{StreamExt, TryStreamExt}; use lance_arrow::SchemaExt; +use rand::Rng; use lance_core::ROW_ID; @@ -19,7 +20,7 @@ use crate::{ arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}, dataloader::{ permutation::shuffle::{Shuffler, ShufflerConfig}, - permutation::util::TemporaryDirectory, + permutation::util::{TemporaryDirectory, non_crypto_rng}, }, query::{Query, QueryBase, Select}, }; @@ -76,6 +77,59 @@ pub enum SplitStrategy { /// /// If this strategy is used then the counts/percentages in the SplitSizes are ignored. Calculated { calculation: String }, + /// Rows are sampled uniformly **with replacement** from the base table (combine with + /// [`PermutationBuilder::with_filter`] to restrict the eligible population), independently + /// per split. Named after "the bootstrap" -- the statistical technique of estimating a + /// dataset's properties by resampling it with replacement -- the same sense `bootstrap=True` + /// has in scikit-learn's bagging classifiers. + /// + /// Every other strategy partitions the table: each row goes to exactly one split, exactly + /// once. `Bootstrap` does not partition -- it resamples. The number of output rows is + /// `num_samples`, not the number of input rows: the same row can appear zero, one, or many + /// times, and `num_samples` may be larger or smaller than the (filtered) input row count. + /// Typical uses: + /// + /// - **Bagging / ensemble training** (e.g. random forests): each split is an independent + /// bootstrap resample of the training set. + /// - **Oversampling a rare class**: filter to the minority class, then sample it up to + /// whatever count balances it against the majority, instead of exhausting its small set + /// once per epoch. + /// - **Fixed-size training steps independent of dataset size**: `num_samples` is set + /// directly rather than being implicitly `len(dataset)`. + /// - **Weighted sampling without a weight column**: filter to "eligible" rows (e.g. a + /// windowed-sampling workload filtering to valid window-start positions), then bootstrap + /// the filtered set -- an item with more eligible rows is naturally drawn proportionally + /// more often, with no explicit per-row weight needed. + /// + /// `sizes` divides `num_samples` across splits (reusing [`SplitSizes`], so `Fixed(n)` means + /// "n splits, each getting `num_samples / n` samples", the same convention `Random` and + /// `Sequential` use). Each split draws its own sample using a seed derived independently + /// from `(seed, split_index)`, so a given split's content does not change if `num_samples` + /// is redistributed across a different number of splits -- the same elastic-determinism + /// property documented for the data loader's other strategies. + /// + /// Example: a 5-row base table (`row_id` 0..4), `Bootstrap { num_samples: 8, sizes: + /// Fixed(2), seed: Some(42) }` produced (an actual run, not a hypothetical one): + /// + /// ```text + /// row_id split_id + /// 0 0 + /// 2 0 + /// 4 0 + /// 4 0 <- row 4 repeated within split 0 + /// 4 1 <- row 4 also drawn in split 1 (independent draw) + /// 4 1 + /// 1 1 + /// 2 1 + /// ``` + /// + /// 8 output rows from a 5-row table, row 4 drawn 4 times total, row 3 never drawn -- + /// exactly the with-replacement behavior the name promises, not an even round-robin. + Bootstrap { + num_samples: u64, + sizes: SplitSizes, + seed: Option, + }, } impl SplitStrategy { @@ -107,6 +161,25 @@ impl SplitStrategy { } Self::Sequential { sizes } => sizes.validate(num_rows), Self::Calculated { .. } => Ok(()), + Self::Bootstrap { + num_samples, sizes, .. + } => { + if num_rows == 0 { + return Err(Error::InvalidInput { + message: "Bootstrap strategy requires at least one eligible row to \ + sample from (check the filter, if one is set)" + .to_string(), + }); + } + if *num_samples == 0 { + return Err(Error::InvalidInput { + message: "Bootstrap strategy requires num_samples > 0".to_string(), + }); + } + // Validated against num_samples, not num_rows: sampling is with replacement, + // so num_samples may exceed the number of eligible rows. + sizes.validate(*num_samples) + } } } } @@ -314,6 +387,95 @@ impl Splitter { ))) } + /// Materializes the full (filtered) row id stream -- random access is required since + /// with-replacement sampling can draw any position, including ones already drawn -- then + /// independently samples each split's share with its own derived RNG seed. + async fn apply_bootstrap( + &self, + source: SendableRecordBatchStream, + num_samples: u64, + sizes: &SplitSizes, + seed: Option, + ) -> Result { + let schema = source.schema(); + let row_id_field = schema.field(0).clone(); + let batches: Vec = source.try_collect().await?; + let row_id_arrays = batches + .iter() + .map(|b| b.column(0).as_ref()) + .collect::>(); + let row_ids = arrow::compute::concat(&row_id_arrays)?; + // Sample against however many rows this scan actually returned, not the + // separately computed `num_rows` count checked by `validate` -- that count and + // this scan are two different queries, not pinned to one snapshot, so a + // concurrent append or delete between them could otherwise push + // `random_range` out of `row_ids`'s real bounds. + let num_eligible_rows = row_ids.len() as u64; + if num_eligible_rows == 0 { + return Err(Error::InvalidInput { + message: "Bootstrap strategy found no eligible rows to sample from in \ + this scan (the table or its filter may have changed since \ + validation)" + .to_string(), + }); + } + + let split_sample_counts = sizes.to_counts(num_samples); + + // `try_reserve_exact` (fallible) rather than `with_capacity` (infallible -- + // aborts the whole process via `handle_alloc_error` on failure, which no + // caller can catch) so an unreasonably large `num_samples` becomes a normal, + // catchable error instead of a crash. This bounds the failure mode, not peak + // memory itself: the output is still one fully materialized RecordBatch, not + // streamed in chunks. + let too_large = || Error::InvalidInput { + message: format!( + "Bootstrap strategy's num_samples ({num_samples}) is too large to \ + allocate in memory" + ), + }; + let mut position_indices = Vec::::new(); + position_indices + .try_reserve_exact(num_samples as usize) + .map_err(|_| too_large())?; + let mut split_ids = Vec::::new(); + split_ids + .try_reserve_exact(num_samples as usize) + .map_err(|_| too_large())?; + for (split_idx, &count) in split_sample_counts.iter().enumerate() { + // Derive an independent seed per split (rather than one RNG shared across all + // splits) so a split's sample doesn't depend on how many other splits there are. + let split_seed = seed.map(|s| { + s.wrapping_add( + (split_idx as u64) + .wrapping_mul(0x9E37_79B9_7F4A_7C15) + .wrapping_add(1), + ) + }); + let mut rng = non_crypto_rng(&split_seed); + for _ in 0..count { + position_indices.push(rng.random_range(0..num_eligible_rows)); + split_ids.push(split_idx as u64); + } + } + + let indices = UInt64Array::from(position_indices); + let sampled_row_ids = arrow::compute::take(row_ids.as_ref(), &indices, None)?; + let split_id_array: Arc = Arc::new(UInt64Array::from(split_ids)); + + let new_schema = Arc::new(Schema::new(vec![ + row_id_field, + Field::new(SPLIT_ID_COLUMN, DataType::UInt64, false), + ])); + let result_batch = + RecordBatch::try_new(new_schema.clone(), vec![sampled_row_ids, split_id_array])?; + + Ok(Box::pin(SimpleRecordBatchStream::new( + futures::stream::once(std::future::ready(Ok(result_batch))), + new_schema, + ))) + } + pub async fn apply( &self, source: SendableRecordBatchStream, @@ -357,6 +519,14 @@ impl Splitter { self.apply_hash(source, split_weights, *discard_weight) .await } + SplitStrategy::Bootstrap { + num_samples, + sizes, + seed, + } => { + self.apply_bootstrap(source, *num_samples, sizes, *seed) + .await + } } } @@ -377,7 +547,13 @@ impl Splitter { pub fn orders_by_split_id(&self) -> bool { match &self.strategy { - SplitStrategy::Hash { .. } | SplitStrategy::Calculated { .. } => true, + // Bootstrap emits samples grouped split-by-split already (see apply_bootstrap), + // rather than relying on the shared pipeline's sort-by-split-id step: within-split + // draw order is meaningful to callers (e.g. a warmup/measured split within one + // split's stream), and sort stability for ties isn't documented behavior to lean on. + SplitStrategy::Hash { .. } + | SplitStrategy::Calculated { .. } + | SplitStrategy::Bootstrap { .. } => true, SplitStrategy::NoSplit | SplitStrategy::Sequential { .. } // It may be strange but for random we shuffle and then assign splits so the result is @@ -385,6 +561,26 @@ impl Splitter { | SplitStrategy::Random { .. } => false, } } + + /// The row count `apply` produces from `num_rows` input rows. Equal to `num_rows` + /// for every strategy except `Bootstrap`, whose output size is `num_samples` + /// regardless of how many (filtered) input rows it draws from. Callers that need + /// to validate or pre-size `apply`'s output (e.g. the shuffler) must use this + /// instead of assuming the input and output row counts match. + /// + /// For `Bootstrap`, this is `sizes.to_counts(num_samples)`'s sum, not + /// `num_samples` itself: `to_counts` can emit less than its input (e.g. + /// `Fixed(n)` when `n` does not divide `num_samples` evenly, or explicit + /// `counts`/`ratios` that do not use every sample) and `apply_bootstrap` only + /// ever emits exactly what `to_counts` returns. + pub fn output_row_count(&self, num_rows: u64) -> u64 { + match &self.strategy { + SplitStrategy::Bootstrap { + num_samples, sizes, .. + } => sizes.to_counts(*num_samples).iter().sum(), + _ => num_rows, + } + } } /// Split configuration - either percentages or absolute counts @@ -807,4 +1003,169 @@ mod tests { assert_eq!(num_in_split_0, 12); // 24% assert_eq!(num_in_split_1, 30); // 60% } + + #[tokio::test] + async fn test_bootstrap_split_schema_and_counts() { + let splitter = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 1000, + sizes: SplitSizes::Fixed(4), + seed: Some(42), + }, + ); + + let split_batches = splitter + .apply(test_data(), 50) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let schema = split_batches[0].schema(); + let split_batch = concat_batches(&schema, &split_batches).unwrap(); + + // Schema stays exactly [row_id, split_id], same as every other strategy. + let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect(); + assert_eq!(field_names, vec!["id", SPLIT_ID_COLUMN]); + + // Output row count is num_samples, not num_rows (50) -- sampling is with replacement. + assert_eq!(split_batch.num_rows(), 1000); + + let split_ids = split_batch.column(1).as_primitive::().values(); + for split_id in [0u64, 1, 2, 3] { + assert_eq!(split_ids.iter().filter(|v| **v == split_id).count(), 250); + } + + // With 1000 draws from only 50 distinct rows, some row id must repeat. + let row_ids = split_batch.column(0).as_primitive::().values(); + let mut seen = std::collections::HashSet::new(); + assert!(!row_ids.iter().all(|v| seen.insert(*v))); + } + + #[tokio::test] + async fn test_bootstrap_split_seed_is_reproducible() { + let make_splitter = || { + Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 200, + sizes: SplitSizes::Fixed(2), + seed: Some(7), + }, + ) + }; + + let first = make_splitter() + .apply(test_data(), 50) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let second = make_splitter() + .apply(test_data(), 50) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + let schema = first[0].schema(); + let first = concat_batches(&schema, &first).unwrap(); + let second = concat_batches(&schema, &second).unwrap(); + assert_eq!(first.column(0), second.column(0)); + assert_eq!(first.column(1), second.column(1)); + } + + #[tokio::test] + async fn test_bootstrap_split_respects_filter() { + // Bootstrap is driven through a filter the same way every other strategy is -- the + // base table rows reaching Splitter::apply are already filtered by the time they get + // here, so this exercises the same num_rows=0 guard a fully-filtered-out population + // would hit. + let splitter = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 10, + sizes: SplitSizes::Fixed(1), + seed: Some(1), + }, + ); + let Err(err) = splitter.apply(test_data(), 0).await else { + panic!("expected Bootstrap over zero eligible rows to fail"); + }; + assert!(err.to_string().contains("at least one eligible row")); + } + + fn empty_data() -> SendableRecordBatchStream { + lance_datagen::gen_batch() + .with_seed(Seed::from(42)) + .col(ID_COLUMN, lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(0), BatchCount::from(1)) + } + + #[test] + fn test_output_row_count() { + // Bootstrap's output row count is independent of the input size -- every + // other strategy's output matches its input. The shuffler relies on this + // (see builder.rs) instead of assuming input and output row counts match. + let bootstrap = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 1000, + sizes: SplitSizes::Fixed(4), + seed: Some(42), + }, + ); + assert_eq!(bootstrap.output_row_count(50), 1000); + + // Not num_samples itself: `Fixed(3)` doesn't divide 1000 evenly, so + // `to_counts` emits 333 * 3 = 999, one short of num_samples -- + // `apply_bootstrap` only ever emits exactly what `to_counts` returns. + let bootstrap_uneven = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 1000, + sizes: SplitSizes::Fixed(3), + seed: Some(42), + }, + ); + assert_eq!(bootstrap_uneven.output_row_count(50), 999); + + let sequential = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Sequential { + sizes: SplitSizes::Fixed(2), + }, + ); + assert_eq!(sequential.output_row_count(50), 50); + } + + #[tokio::test] + async fn test_bootstrap_rejects_empty_scan_cleanly() { + // The eligibility count `validate` checks and this scan are two separate + // queries against the table, not pinned to one snapshot -- a concurrent + // delete could shrink the real scan to zero rows after `validate` already + // passed on a nonzero count. Calling `apply_bootstrap` directly (bypassing + // `apply`'s `validate`) reproduces exactly that: a scan that returns zero + // rows regardless of what count was validated upstream. It must return a + // clean `Err`, not panic on an out-of-range `take` or an empty-range + // `random_range`. + let splitter = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 10, + sizes: SplitSizes::Fixed(1), + seed: Some(1), + }, + ); + let Err(err) = splitter + .apply_bootstrap(empty_data(), 10, &SplitSizes::Fixed(1), Some(1)) + .await + else { + panic!("expected Bootstrap over an empty scan to fail cleanly, not panic"); + }; + assert!(err.to_string().contains("no eligible rows")); + } } diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 6052b67d8..1b1f5b0a5 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -10,6 +10,25 @@ use snafu::Snafu; pub(crate) type BoxError = Box; +// 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")] +fn http_timeout_hint(source: &(dyn std::error::Error + 'static)) -> &'static str { + match source.downcast_ref::() { + Some(error) if error.is_timeout() && error.is_connect() => { + "; connection timed out. Check client_config.timeout_config.connect_timeout \ + (LANCE_CLIENT_CONNECT_TIMEOUT) and client_config.timeout_config.timeout \ + (LANCE_CLIENT_TIMEOUT) if configured" + } + Some(error) if error.is_timeout() => { + "; request timed out. For slow uploads or responses, check \ + client_config.timeout_config.read_timeout (LANCE_CLIENT_READ_TIMEOUT) \ + and client_config.timeout_config.timeout (LANCE_CLIENT_TIMEOUT) if configured" + } + _ => "", + } +} + /// 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`]. @@ -111,7 +130,10 @@ pub enum Error { #[snafu(display("lance error: {source}"))] Lance { source: lance::Error }, #[cfg(feature = "remote")] - #[snafu(display("Http error: (request_id={request_id}) {source}"))] + #[snafu(display( + "Http error: (request_id={request_id}) {source}{}", + http_timeout_hint(source.as_ref()) + ))] Http { #[snafu(source(from(reqwest::Error, Box::new)))] source: Box, @@ -127,7 +149,8 @@ pub enum Error { "Hit retry limit for request_id={request_id} (\ request_failures={request_failures}/{max_request_failures}, \ connect_failures={connect_failures}/{max_connect_failures}, \ - read_failures={read_failures}/{max_read_failures}): {source}" + read_failures={read_failures}/{max_read_failures}): {source}{}", + http_timeout_hint(source.as_ref()) ))] Retry { request_id: String, @@ -314,6 +337,20 @@ impl From for Error { mod tests { use super::*; + #[cfg(feature = "remote")] + #[test] + fn non_timeout_http_error_message_is_unchanged() { + let error = Error::Http { + source: "server error".into(), + request_id: "test".into(), + status_code: Some(reqwest::StatusCode::INTERNAL_SERVER_ERROR), + }; + assert_eq!( + error.to_string(), + "Http error: (request_id=test) server error" + ); + } + #[test] fn unsupported_filesystem_operations_have_actionable_error() { let object_store_error = object_store::Error::Generic { diff --git a/rust/lancedb/src/expr.rs b/rust/lancedb/src/expr.rs index 1625d9632..04d1b0e9e 100644 --- a/rust/lancedb/src/expr.rs +++ b/rust/lancedb/src/expr.rs @@ -295,6 +295,49 @@ mod tests { ); } + #[test] + fn test_string_placeholder_does_not_rewrite_user_string() { + let marker = "__lancedb_string_placeholder_0__"; + let expr = col("value") + .eq(lit(marker)) + .and(col("other").eq(lit("ordinary"))); + assert_eq!( + expr_to_sql_string(&expr).unwrap(), + "((`value` = '__lancedb_string_placeholder_0__') AND (`other` = 'ordinary'))" + ); + } + + #[test] + fn test_string_literals_use_standard_quote_escaping() { + use datafusion_sql::sqlparser::{ + dialect::GenericDialect, tokenizer::Token, tokenizer::Tokenizer, + }; + + for value in [ + r"\", + "'", + r"\') OR true --", + "tenant -- 'not a comment", + "tenant /* 'not a comment */", + ] { + let expr = col("tenant").eq(lit(value)); + let sql = expr_to_sql_string(&expr).unwrap(); + assert_eq!(canonicalize_sql_predicate(&sql).unwrap(), sql); + + let string_literals = Tokenizer::new(&GenericDialect {}, &sql) + .with_unescape(false) + .tokenize() + .unwrap() + .into_iter() + .filter_map(|token| match token { + Token::SingleQuotedString(value) => Some(value), + _ => None, + }) + .collect::>(); + assert_eq!(string_literals, vec![value.replace('\'', "''")]); + } + } + #[test] fn test_binary_binding_skips_quoted_identifiers() { use datafusion_common::ScalarValue; diff --git a/rust/lancedb/src/expr/sql.rs b/rust/lancedb/src/expr/sql.rs index 2a1ca201d..96bb5b60c 100644 --- a/rust/lancedb/src/expr/sql.rs +++ b/rust/lancedb/src/expr/sql.rs @@ -104,9 +104,15 @@ pub fn canonicalize_sql_predicate(predicate: &str) -> crate::Result { .collect()) } -/// Prefix for placeholder strings inserted in place of binary literals. Chosen -/// to be extremely unlikely to occur in user data. +/// Prefixes for placeholder strings inserted in place of literals. Chosen to +/// be extremely unlikely to occur in user data. const BINARY_PLACEHOLDER_PREFIX: &str = "__lancedb_binary_placeholder_"; +const STRING_PLACEHOLDER_PREFIX: &str = "__lancedb_string_placeholder_"; + +enum LiteralBinding { + String(String), + Binary(Vec), +} fn bytes_to_hex_sql(bytes: &[u8]) -> String { let hex: String = bytes.iter().map(|b| format!("{b:02X}")).collect(); @@ -137,19 +143,28 @@ fn typed_string_literal(value: String, data_type: DataType) -> Expr { ) } -fn next_binary_placeholder(user_strings: &HashSet, next_id: &mut usize) -> String { +fn next_placeholder( + prefix: &str, + user_strings: &HashSet, + bindings: &HashMap, + next_id: &mut usize, +) -> String { loop { - let placeholder = format!("{BINARY_PLACEHOLDER_PREFIX}{}__", *next_id); + let placeholder = format!("{prefix}{}__", *next_id); *next_id += 1; - if !user_strings.contains(&placeholder) { + if !user_strings.contains(&placeholder) && !bindings.contains_key(&placeholder) { return placeholder; } } } -fn bind_binary_literals( +fn escape_string_literal(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} + +fn bind_literals( sql: &str, - mut bindings: HashMap>, + mut bindings: HashMap, ) -> crate::Result { let bytes = sql.as_bytes(); let mut output = Vec::with_capacity(bytes.len()); @@ -179,7 +194,7 @@ fn bind_binary_literals( let Some(identifier_end) = identifier_end else { return Err(crate::Error::InvalidInput { - message: "unterminated identifier while binding binary literal".to_string(), + message: "unterminated identifier while binding literals".to_string(), }); }; output.extend_from_slice(&bytes[identifier_start..identifier_end]); @@ -214,13 +229,17 @@ fn bind_binary_literals( let Some(content_end) = content_end else { return Err(crate::Error::InvalidInput { - message: "unterminated string while binding binary literal".to_string(), + message: "unterminated string while binding literals".to_string(), }); }; let placeholder = &sql[content_start..content_end]; if !escaped && let Some(value) = bindings.remove(placeholder) { - output.extend_from_slice(bytes_to_hex_sql(&value).as_bytes()); + let rendered = match value { + LiteralBinding::String(value) => escape_string_literal(&value), + LiteralBinding::Binary(value) => bytes_to_hex_sql(&value), + }; + output.extend_from_slice(rendered.as_bytes()); } else { output.extend_from_slice(&bytes[literal_start..index]); } @@ -228,12 +247,12 @@ fn bind_binary_literals( if !bindings.is_empty() { return Err(crate::Error::InvalidInput { - message: "failed to bind binary literal while serializing expression".to_string(), + message: "failed to bind literals while serializing expression".to_string(), }); } String::from_utf8(output).map_err(|e| crate::Error::InvalidInput { - message: format!("failed to bind binary literal: {e}"), + message: format!("failed to bind literals: {e}"), }) } @@ -253,7 +272,7 @@ pub fn expr_to_sql_string(expr: &Expr) -> crate::Result { // * decimal literals need an explicit cast to preserve precision and scale; // * casts need exact Arrow type names rather than SQL type aliases; // * an empty IN list is valid in DataFusion but invalid SQL; - // * binary literals are unsupported by the unparser and need placeholders. + // * literals are replaced with placeholders and restored after unparsing. // Eliminate empty membership expressions before visiting their children. // Otherwise a discarded binary child could leave behind a stale binding. let rewritten = expr @@ -270,14 +289,19 @@ pub fn expr_to_sql_string(expr: &Expr) -> crate::Result { .data; let user_strings = string_literals(&rewritten); - let mut next_placeholder_id = 0; - let mut binary_bindings = HashMap::new(); + let mut next_binary_placeholder_id = 0; + let mut bindings = HashMap::new(); let rewritten = rewritten .transform(|e: Expr| match e { Expr::Literal(ScalarValue::Binary(Some(bytes)), m) | Expr::Literal(ScalarValue::LargeBinary(Some(bytes)), m) => { - let placeholder = next_binary_placeholder(&user_strings, &mut next_placeholder_id); - binary_bindings.insert(placeholder.clone(), bytes); + let placeholder = next_placeholder( + BINARY_PLACEHOLDER_PREFIX, + &user_strings, + &bindings, + &mut next_binary_placeholder_id, + ); + bindings.insert(placeholder.clone(), LiteralBinding::Binary(bytes)); Ok(Transformed::yes(Expr::Literal( ScalarValue::Utf8(Some(placeholder)), m, @@ -345,11 +369,44 @@ pub fn expr_to_sql_string(expr: &Expr) -> crate::Result { })? .data; + // DataFusion's SQLParser serializer treats a quote after a backslash as + // already escaped, but Lance's dialect does not support backslash escapes. + // Replace every string with an inert placeholder so the serializer cannot + // misinterpret its contents, then restore each value with standard SQL + // single-quote doubling below. + let mut next_string_placeholder_id = 0; + let rewritten = rewritten + .transform(|e: Expr| match e { + Expr::Literal( + ScalarValue::Utf8(Some(value)) + | ScalarValue::LargeUtf8(Some(value)) + | ScalarValue::Utf8View(Some(value)), + m, + ) if !bindings.contains_key(&value) => { + let placeholder = next_placeholder( + STRING_PLACEHOLDER_PREFIX, + &user_strings, + &bindings, + &mut next_string_placeholder_id, + ); + bindings.insert(placeholder.clone(), LiteralBinding::String(value)); + Ok(Transformed::yes(Expr::Literal( + ScalarValue::Utf8(Some(placeholder)), + m, + ))) + } + other => Ok(Transformed::no(other)), + }) + .map_err(|e| crate::Error::InvalidInput { + message: format!("failed to rewrite string literals: {}", e), + })? + .data; + let sql = run_unparser(&rewritten)?; - if binary_bindings.is_empty() { + if bindings.is_empty() { Ok(sql) } else { - bind_binary_literals(&sql, binary_bindings) + bind_literals(&sql, bindings) } } diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 98d915118..128a7efdf 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -156,11 +156,20 @@ pub struct FunctionArtifact { } /// One ordered Arrow input parameter. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BlobAccess { + Bytes, + Reader, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionParameter { pub name: String, pub arrow_type: String, pub nullable: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub blob_access: Option, } /// One field of an ordered named-struct result. @@ -215,6 +224,10 @@ pub struct PythonEnvironmentSpec { pub modules: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub image: Option, + /// Debian packages (`name` or `name=version`) added to the Function's + /// image before its Python environment is installed. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub system_packages: Vec, } /// Reproducible Python runtime definition understood by Sophon. @@ -244,6 +257,7 @@ pub enum PythonRuntimeSpec { /// path: None, /// modules: Vec::new(), /// image: None, + /// system_packages: Vec::new(), /// }, /// env: BTreeMap::new(), /// }; @@ -450,6 +464,8 @@ pub struct FunctionVersion { #[serde(deserialize_with = "deserialize_object_version")] version: String, image: FunctionImage, + #[serde(default, skip_serializing_if = "Option::is_none")] + source_digest: Option, signature: FunctionSignature, #[serde(default, skip_serializing_if = "Vec::is_empty")] secret_bindings: Vec, @@ -494,6 +510,23 @@ impl FunctionVersion { pub fn image(&self) -> &FunctionImage { &self.image } + + /// Digest of the registered source artifact, when provided by the server. + /// + /// Compare this with [`FunctionArtifactRequest::digest`] to identify matching + /// source, independently of the built image's manifest digest. + /// + /// ``` + /// use lancedb::function::{FunctionArtifactRequest, FunctionVersion}; + /// + /// fn has_same_source(version: &FunctionVersion, artifact: &FunctionArtifactRequest) -> bool { + /// version.source_digest() == Some(artifact.digest.as_str()) + /// } + /// ``` + pub fn source_digest(&self) -> Option<&str> { + self.source_digest.as_deref() + } + pub fn signature(&self) -> &FunctionSignature { &self.signature } @@ -762,8 +795,8 @@ impl_json!(FunctionBinding); /// Stable terminal result of an expression-backed or Function-backed column /// refresh [`crate::Job`]. /// -/// Local refresh jobs produce this value in process. LanceDB Cloud and -/// Enterprise decode the same value from the durable job's terminal payload. +/// LanceDB Embedded refresh jobs produce this value in process. LanceDB +/// Distributed 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. @@ -910,6 +943,27 @@ mod conda_environment_tests { assert!(!serde_json::to_string(&pip).unwrap().contains("channels")); } + #[test] + fn system_packages_round_trip_and_stay_absent_when_empty() { + let apt: PythonEnvironmentSpec = serde_json::from_str( + r#"{"kind":"pip","packages":["torchcodec"],"system_packages":["libavutil58"]}"#, + ) + .unwrap(); + assert_eq!(apt.system_packages, ["libavutil58"]); + assert!( + serde_json::to_string(&apt) + .unwrap() + .contains(r#""system_packages":["libavutil58"]"#) + ); + let pip: PythonEnvironmentSpec = + serde_json::from_str(r#"{"kind":"pip","packages":["numpy"]}"#).unwrap(); + assert!( + !serde_json::to_string(&pip) + .unwrap() + .contains("system_packages") + ); + } + #[test] fn gpu_python_runtime_marker_round_trips_and_validates() { let runtime: PythonRuntimeSpec = serde_json::from_str( @@ -956,6 +1010,46 @@ mod conda_environment_tests { mod tests { use super::*; + #[test] + fn function_version_preserves_source_digest() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + let legacy = FunctionVersion::from_json(VERSION).unwrap(); + assert_eq!(legacy.source_digest(), None); + assert_eq!(legacy.to_canonical_json().unwrap(), VERSION.trim_end()); + + for digest in [Value::Null, serde_json::json!("sha256:source-artifact")] { + document["source_digest"] = digest.clone(); + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.source_digest(), digest.as_str()); + assert_eq!(version.image(), legacy.image()); + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + if digest.is_null() { + assert!(encoded_value.get("source_digest").is_none()); + } else { + assert_eq!(encoded_value["source_digest"], digest); + } + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + } + } + + #[test] + fn blob_reader_access_survives_signature_round_trip() { + let parameter: FunctionParameter = serde_json::from_value(serde_json::json!({ + "name": "video", "arrow_type": "blob_v2", "nullable": false, + "blob_access": "reader" + })) + .unwrap(); + assert_eq!(parameter.blob_access, Some(BlobAccess::Reader)); + assert_eq!( + serde_json::to_value(parameter).unwrap()["blob_access"], + "reader" + ); + } + /// Canonical form is what the FunctionVersion hash is taken over, so key /// order must come from the keys and not from however serde happened to /// emit them. Nesting is included because the sort is recursive. diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index 82f8ad845..e9056863a 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use chrono::{DateTime, Utc}; +use lance::index::scalar::IndexDetails; use scalar::FtsIndexBuilder; use serde::Deserialize; use serde_with::skip_serializing_none; @@ -382,10 +383,38 @@ pub enum IndexType { // FTS #[serde(alias = "INVERTED", alias = "Inverted")] FTS, + /// A registered scalar index plugin's display name, preserved verbatim. + /// + /// For example, `Custom("Sketch".into()).to_string()` returns `"Sketch"`. + Custom(String), /// Catch-all for index types not recognized by this version of LanceDB. Unknown, } +impl IndexType { + pub(crate) fn from_description( + description: &dyn lance_index::traits::IndexDescription, + ) -> Self { + let index_type = description.index_type().parse().unwrap_or(Self::Unknown); + if index_type != Self::Unknown { + return index_type; + } + let Some(metadata) = description.segments().first() else { + return Self::Unknown; + }; + if lance_index::is_system_index(metadata) { + return Self::Unknown; + } + let Some(details) = metadata.index_details.as_ref() else { + return Self::Unknown; + }; + IndexDetails(details.clone()) + .get_plugin() + .map(|plugin| Self::Custom(plugin.name().to_string())) + .unwrap_or(Self::Unknown) + } +} + impl std::fmt::Display for IndexType { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { @@ -405,6 +434,7 @@ impl std::fmt::Display for IndexType { Self::BloomFilter => write!(f, "BLOOM_FILTER"), Self::RTree => write!(f, "RTREE"), Self::FTS => write!(f, "FTS"), + Self::Custom(name) => f.write_str(name), Self::Unknown => write!(f, "UNKNOWN"), } } @@ -452,46 +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. for remote tables, which do not yet surface this). + /// determined (e.g. in LanceDB Distributed, 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. for remote tables). + /// `None` if unavailable (e.g. in LanceDB Distributed). 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 for remote tables. + /// timestamps were tracked, or in LanceDB Distributed. 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. for remote tables). + /// `None` if unavailable (e.g. in LanceDB Distributed 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. for remote tables). + /// (e.g. in LanceDB Distributed 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 for remote tables. + /// before file sizes were tracked, or in LanceDB Distributed. pub size_bytes: Option, /// The number of segments that make up the index. /// - /// `None` if unavailable (e.g. for remote tables). + /// `None` if unavailable (e.g. in LanceDB Distributed). pub num_segments: Option, /// The on-disk index format version, taken from the first segment. /// - /// `None` if unavailable (e.g. for remote tables). + /// `None` if unavailable (e.g. in LanceDB Distributed). 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 for remote tables. + /// could not be produced (e.g. no plugin available) or in LanceDB Distributed. pub index_details: Option, } diff --git a/rust/lancedb/src/index/scalar.rs b/rust/lancedb/src/index/scalar.rs index 5bfc2b4e6..5d2256381 100644 --- a/rust/lancedb/src/index/scalar.rs +++ b/rust/lancedb/src/index/scalar.rs @@ -65,6 +65,17 @@ pub struct FmIndexBuilder {} /// A ZoneMap index stores min/max summaries for ranges of rows and can /// accelerate range predicates by pruning zones that cannot match. /// +/// ZoneMap indexes use per-fragment write seeds by default for strings, binary +/// data, and supported types wider than eight bytes. Creating a seed-enabled +/// index activates a table capability immediately, before any version 1 seed +/// is written. A mutation retaining a legacy seed-enabled index also activates +/// it. Older clients cannot read or write the resulting snapshots, so upgrade +/// all readers and writers before creating such an index or mutating a table +/// that already has one. The capability +/// remains set in subsequent snapshots, including after dropping the index or +/// restoring an older version; dropping the index does not restore access for +/// older clients. Opening a table alone does not activate the capability. +/// /// ``` /// use lancedb::{ /// index::{scalar::ZoneMapIndexBuilder, Index}, diff --git a/rust/lancedb/src/index/vector.rs b/rust/lancedb/src/index/vector.rs index bce77a610..3e6794b54 100644 --- a/rust/lancedb/src/index/vector.rs +++ b/rust/lancedb/src/index/vector.rs @@ -362,6 +362,9 @@ impl IvfRqIndexBuilder { impl_distance_type_setter!(); impl_ivf_params_setter!(); + /// Set the number of bits used to encode each vector dimension. + /// + /// If unset, uses Lance's default (currently 5). Set to 1 for maximum compression. pub fn num_bits(mut self, num_bits: u32) -> Self { self.num_bits = Some(num_bits); self diff --git a/rust/lancedb/src/index/waiter.rs b/rust/lancedb/src/index/waiter.rs index f201ed6c3..eeef22c98 100644 --- a/rust/lancedb/src/index/waiter.rs +++ b/rust/lancedb/src/index/waiter.rs @@ -9,7 +9,7 @@ use std::time::{Duration, Instant}; use tokio::time::sleep; const DEFAULT_SLEEP_MS: u64 = 1000; -const MAX_WAIT: Duration = Duration::from_secs(2 * 60 * 60); +pub(crate) const MAX_WAIT: Duration = Duration::from_secs(2 * 60 * 60); /// Poll the table using list_indices() and index_stats() until all of the indices have 0 un-indexed rows. /// Will return Error::Timeout if the columns are not fully indexed within the timeout. diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 711a73033..0e88a7432 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -13,6 +13,7 @@ use serde::{Serialize, de::DeserializeOwned}; use serde_json::Value; use tokio::sync::watch; use tokio::task::{AbortHandle, JoinHandle}; +use uuid::Uuid; use crate::database::JobDescription; use crate::error::{Error, JobFailure, Result}; @@ -55,10 +56,13 @@ fn job_detail_not_supported(what: &str) -> Result { /// Backend-specific tracking for an asynchronous operation. #[async_trait] pub(crate) trait JobHandle: Send + Sync { - /// Server-assigned id, when the backend has one. + /// Backend-specific id, when the operation has one. fn id(&self) -> Option<&str> { None } + fn job_type(&self) -> Option<&str> { + None + } async fn status(&self) -> Result; async fn wait(&self) -> Result; async fn cancel(&self) -> Result<()>; @@ -88,6 +92,7 @@ impl TerminalResult { } } + #[cfg(feature = "remote")] pub(crate) fn remote(value: Option, request_id: String) -> Self { Self { value, @@ -101,21 +106,19 @@ impl TerminalResult { fn decode(self) -> Result { let value = self.value.ok_or_else(|| match &self.request_id { - Some(request_id) => Error::Http { - source: "successful typed job response did not contain a result".into(), - request_id: request_id.clone(), - status_code: None, - }, + Some(request_id) => remote_job_error( + request_id.clone(), + "successful typed job response did not contain a result".to_string(), + ), None => Error::Runtime { message: "successful typed job did not contain a result".to_string(), }, })?; serde_json::from_value(value).map_err(|error| match self.request_id { - Some(request_id) => Error::Http { - source: format!("failed to parse typed job result: {error}").into(), + Some(request_id) => remote_job_error( request_id, - status_code: None, - }, + format!("failed to parse typed job result: {error}"), + ), None => Error::Runtime { message: format!("failed to parse typed job result: {error}"), }, @@ -123,6 +126,28 @@ impl TerminalResult { } } +/// Build the error for a failed remote typed-job result. +/// +/// The `Error::Http` variant is gated behind the `remote` feature, so without +/// it we fall back to `Error::Runtime`. A `request_id` is only ever `Some` +/// for remote jobs, making the fallback unreachable in practice without the +/// feature. +#[cfg(feature = "remote")] +fn remote_job_error(request_id: String, source: String) -> Error { + Error::Http { + source: source.into(), + request_id, + status_code: None, + } +} + +#[cfg(not(feature = "remote"))] +fn remote_job_error(request_id: String, source: String) -> Error { + Error::Runtime { + message: format!("{source} (request_id={request_id})"), + } +} + type ResultDecoder = Arc Result + Send + Sync>; enum JobInner { @@ -147,14 +172,15 @@ struct JobCache { /// the endpoint's successful terminal result; unit-result operations use the /// default `Job<()>`. /// -/// The detail accessors ([`Job::state`], [`Job::job_type`], ...) read what the +/// Registry detail accessors ([`Job::state`], [`Job::job_type`], ...) read what the /// handle last observed. Submitting an operation returns only a job id, so /// populating them eagerly would cost an extra round trip on every call: /// /// - [`Job::refresh`] and [`Job::status`] fetch the whole record. /// - [`Job::wait`] records the terminal state it establishes, but not the rest /// of the record; call [`Job::refresh`] for that. -/// - Everything is `None` until one of those runs. +/// - Registry details are `None` until one of those runs. Query-backed handles +/// report [`Job::job_type`] as `"query"` immediately. pub struct Job where T: Clone + Send + Sync + 'static, @@ -217,6 +243,7 @@ impl Job<()> { /// A handle whose record the caller has already fetched, so the detail /// accessors answer without a second round trip. + #[cfg(feature = "remote")] pub(crate) fn opened(handle: Box, description: JobDescription) -> Self { let job = Self::new(handle); { @@ -253,13 +280,18 @@ where Self::new_typed(Box::new(SpawnedJob::new(task))) } - pub(crate) fn spawned_with_cancellation(task: JoinHandle>, cancel: F) -> Self + pub(crate) fn from_query_task( + query_id: Uuid, + task: JoinHandle>, + cancel: F, + ) -> Self where F: Fn() -> Fut + Send + Sync + 'static, Fut: Future> + Send + 'static, { let cancellation: Cancellation = Arc::new(move || Box::pin(cancel())); Self::new_typed(Box::new(SpawnedJob::new_with_cancellation( + query_id, task, cancellation, ))) @@ -270,12 +302,10 @@ impl Job where T: Clone + Send + Sync + 'static, { - /// Identifies the operation on the server that is running it. - /// - /// Returned for correlating with server logs or the jobs API. Operations - /// that run in this process have no server id and return `None`. The - /// value is opaque: parsing it or storing it to resume the job later is - /// not supported. + /// The operation's opaque identity, interpreted according to [`Job::job_type`]. + /// Registry handles expose a registry job ID; query handles expose the + /// connection-scoped SQL query UUID as a string. Local handles return None. + /// A query ID cannot be used with registry APIs or to resume after restart. pub fn id(&self) -> Option<&str> { match &self.inner { JobInner::Handle { handle, .. } => handle.id(), @@ -349,8 +379,14 @@ where self.cache_read().description.clone() } - /// The job's type, as the server names it. `None` for an in-process job. + /// The job's type: `"query"` for SQL-backed handles, otherwise the cached + /// server-reported kind of work. `None` for an in-process job. pub fn job_type(&self) -> Option { + if let JobInner::Handle { handle, .. } = &self.inner + && let Some(job_type) = handle.job_type() + { + return Some(job_type.to_string()); + } self.with_description(|description| description.job_type.clone()) } @@ -516,6 +552,7 @@ struct SpawnedJob { outcome: watch::Receiver>, abort: AbortHandle, cancellation: Option, + id: Option, } type CancellationFuture = Pin> + Send>>; @@ -529,11 +566,17 @@ impl SpawnedJob { Self::new_inner(task, None) } - fn new_with_cancellation(task: JoinHandle>, cancellation: Cancellation) -> Self + fn new_with_cancellation( + query_id: Uuid, + task: JoinHandle>, + cancellation: Cancellation, + ) -> Self where T: Serialize + Send + 'static, { - Self::new_inner(task, Some(cancellation)) + let mut handle = Self::new_inner(task, Some(cancellation)); + handle.id = Some(query_id.to_string()); + handle } fn new_inner(task: JoinHandle>, cancellation: Option) -> Self @@ -562,12 +605,21 @@ impl SpawnedJob { outcome, abort, cancellation, + id: None, } } } #[async_trait] impl JobHandle for SpawnedJob { + fn id(&self) -> Option<&str> { + self.id.as_deref() + } + + fn job_type(&self) -> Option<&str> { + self.id.as_ref().map(|_| "query") + } + async fn status(&self) -> Result { let label = match &*self.outcome.borrow() { None => "running", @@ -616,15 +668,43 @@ mod tests { use super::*; + #[test] + fn local_typed_result_decode_errors_are_runtime_errors() { + assert!(matches!( + TerminalResult::local(Value::Null).decode::(), + Err(Error::Runtime { .. }) + )); + } + #[tokio::test] async fn mapped_spawned_job_reuses_outcome() { let job = Job::spawned(tokio::spawn(async { Ok(41_u64) })).map(|value| value + 1); + assert_eq!(job.job_type(), None); + assert_eq!(job.id(), None); assert_eq!(job.wait().await.unwrap(), 42); assert_eq!(job.wait().await.unwrap(), 42); assert_eq!(job.status().await.unwrap(), "finished"); } + #[tokio::test] + async fn mapped_query_job_preserves_identity_and_type() { + let query_id = Uuid::new_v4(); + let job = Job::from_query_task(query_id, tokio::spawn(async { Ok(41_u64) }), || async { + Ok(()) + }) + .map(|value| value + 1); + assert_eq!(job.job_type().as_deref(), Some("query")); + assert_eq!(job.id(), Some(query_id.to_string().as_str())); + assert_eq!(job.wait().await.unwrap(), 42); + assert_eq!(job.wait().await.unwrap(), 42); + assert_eq!(job.job_type().as_deref(), Some("query")); + assert_eq!(job.id(), Some(query_id.to_string().as_str())); + let completed = Job::new_done(); + assert_eq!(completed.job_type(), None); + assert_eq!(completed.id(), None); + } + #[tokio::test] async fn mapped_spawned_job_preserves_cancellation() { let job = Job::spawned(tokio::spawn(async { pending::>().await })) @@ -634,4 +714,46 @@ mod tests { assert!(matches!(job.wait().await, Err(Error::JobCancelled { .. }))); assert_eq!(job.status().await.unwrap(), "cancelled"); } + + #[test] + fn decode_missing_result_uses_feature_appropriate_error() { + // A `request_id` is only `Some` for remote jobs. The error for a + // missing result must use `Error::Http` with the `remote` feature and + // fall back to `Error::Runtime` without it (where `Error::Http` + // does not exist). See https://github.com/lancedb/lancedb/issues/4142. + let result = TerminalResult { + value: None, + request_id: Some("req-1".to_string()), + }; + let err = result.decode::().unwrap_err(); + #[cfg(feature = "remote")] + assert!( + matches!(err, Error::Http { .. }), + "expected Error::Http, got {err:?}" + ); + #[cfg(not(feature = "remote"))] + assert!( + matches!(err, Error::Runtime { .. }), + "expected Error::Runtime, got {err:?}" + ); + } + + #[test] + fn decode_unparsable_result_uses_feature_appropriate_error() { + let result = TerminalResult { + value: Some(Value::String("not a u64".to_string())), + request_id: Some("req-1".to_string()), + }; + let err = result.decode::().unwrap_err(); + #[cfg(feature = "remote")] + assert!( + matches!(err, Error::Http { .. }), + "expected Error::Http, got {err:?}" + ); + #[cfg(not(feature = "remote"))] + assert!( + matches!(err, Error::Runtime { .. }), + "expected Error::Runtime, got {err:?}" + ); + } } diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index e15017e7f..fa6850f14 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -23,6 +23,11 @@ //! cargo add lancedb //! ``` //! +//! Use the Arrow crates re-exported from [`arrow`] when building schemas, arrays, and +//! record batches for LanceDB. Arrow types from different crate versions are distinct +//! Rust types, so declaring independent `arrow-array` or `arrow-schema` dependencies +//! can cause type errors if their versions do not match LanceDB's dependencies. +//! //! ## Crate Features //! //! - `aws` - Enable AWS S3 object store support. @@ -30,7 +35,12 @@ //! - `azure` - Enable Azure Blob Storage object store support. //! - `gcs` - Enable Google Cloud Storage object store support. //! - `oss` - Enable Alibaba Cloud OSS object store support. -//! - `remote` - Enable remote client to connect to LanceDB cloud. +//! - `remote` - Enable the client for connecting to LanceDB Enterprise or LanceDB Cloud (legacy). +//! - `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, +//! 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. //! - `metrics` - Publish LanceDB's internal metrics through the @@ -51,9 +61,10 @@ //! //! LanceDB accepts the different form of database path: //! -//! - `/path/to/database` - local database on file system. +//! - `/path/to/database` - database on the local file system. //! - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud object store -//! - `db://dbname` - Lance Cloud +//! - `db://dbname` - LanceDB Enterprise or LanceDB Cloud (legacy) +//! - `db://` with a host override - LanceDB Enterprise tables in the storage root //! //! You can also use [`ConnectBuilder`] to configure the connection to the database. //! @@ -85,9 +96,11 @@ //! //! ```rust //! # use std::sync::Arc; -//! use arrow_array::{RecordBatch, RecordBatchIterator}; -//! use arrow_schema::{DataType, Field, Schema}; -//! # use arrow_array::{FixedSizeListArray, Float32Array, Int32Array, types::Float32Type}; +//! use lancedb::arrow::arrow_array::{RecordBatch, RecordBatchIterator}; +//! use lancedb::arrow::arrow_schema::{DataType, Field, Schema}; +//! # use lancedb::arrow::arrow_array::{ +//! # FixedSizeListArray, Float32Array, Int32Array, types::Float32Type, +//! # }; //! //! # tokio::runtime::Runtime::new().unwrap().block_on(async { //! # let tmpdir = tempfile::tempdir().unwrap(); @@ -132,9 +145,11 @@ //! //! ```no_run //! # use std::sync::Arc; -//! # use arrow_array::{FixedSizeListArray, types::Float32Type, RecordBatch, -//! # RecordBatchIterator, Int32Array}; -//! # use arrow_schema::{Schema, Field, DataType}; +//! # use lancedb::arrow::arrow_array::{ +//! # FixedSizeListArray, Int32Array, RecordBatch, RecordBatchIterator, +//! # types::Float32Type, +//! # }; +//! # use lancedb::arrow::arrow_schema::{DataType, Field, Schema}; //! use lancedb::index::Index; //! # tokio::runtime::Runtime::new().unwrap().block_on(async { //! # let tmpdir = tempfile::tempdir().unwrap(); @@ -228,6 +243,19 @@ pub use materialized_view::{ pub use metrics; pub use table::{FtsToken, Table}; +/// Gate local execution without hiding client types or metadata protections. +pub(crate) fn require_experimental_functions() -> Result<()> { + if !cfg!(feature = "experimental-functions") { + return Err(Error::NotSupported { + message: "local computed columns and materialized-view creation/refresh require \ + building LanceDB with the 'experimental-functions' Cargo feature; \ + official Python and TypeScript packages do not enable it" + .into(), + }); + } + Ok(()) +} + /// Tokenize a full-text search query using an explicit FTS tokenizer configuration. /// /// This does not require a table or FTS index. The tokenizer options are the diff --git a/rust/lancedb/src/listing.rs b/rust/lancedb/src/listing.rs index 710202d9d..a0f6e5d5e 100644 --- a/rust/lancedb/src/listing.rs +++ b/rust/lancedb/src/listing.rs @@ -51,8 +51,9 @@ type FetchPage = /// A lazy stream of resources with inspectable pagination state. /// -/// No requests are made until the stream is polled. Empty pages with continuation -/// tokens are skipped. Errors terminate the stream and retain the failed request's +/// No requests are made until the stream is polled or [`Self::next_page`] is called. +/// Item iteration skips empty pages with continuation tokens; `next_page` returns +/// them. Errors terminate the listing and retain the failed request's /// token, allowing a new stream to retry it. Repeated tokens are rejected. /// /// A token advances when its page is fetched. Drain [`Self::num_page_results`] @@ -100,6 +101,64 @@ impl Listing { pub fn page_token(&self) -> Option<&str> { self.options.page_token.as_deref() } + + /// Return exactly one page without consuming a following page. + /// + /// If item iteration has started, this returns the remaining items in its + /// cached page. An empty page with a continuation token is returned as is. + pub async fn next_page(&mut self) -> Result>> { + if self.items.len() == 0 { + if self.done { + return Ok(None); + } + futures::future::poll_fn(|cx| self.poll_fetch_page(cx)).await?; + } + let items = std::mem::replace(&mut self.items, Vec::new().into_iter()).collect(); + Ok(Some(ListingPage { + items, + page_token: self.options.page_token.clone(), + })) + } + + fn poll_fetch_page(&mut self, cx: &mut Context<'_>) -> Poll> { + if self + .options + .page_limit + .is_some_and(|limit| limit == 0 || limit > i32::MAX as u32) + { + self.done = true; + return Poll::Ready(Err(Error::InvalidInput { + message: "Listing page limit must be between 1 and 2147483647".into(), + })); + } + let pending = self + .pending + .get_or_insert_with(|| (self.fetch)(self.options.clone())); + let response = futures::ready!(pending.as_mut().poll(cx)); + self.pending = None; + match response { + Ok(response) => { + let token = response.page_token.filter(|token| !token.is_empty()); + if token + .as_ref() + .is_some_and(|token| !self.seen_tokens.insert(token.clone())) + { + self.done = true; + return Poll::Ready(Err(Error::Runtime { + message: "Listing response repeated a page_token".into(), + })); + } + self.done = token.is_none(); + self.options.page_token = token; + self.items = response.items.into_iter(); + Poll::Ready(Ok(())) + } + Err(error) => { + self.done = true; + Poll::Ready(Err(error)) + } + } + } } impl Stream for Listing { @@ -114,41 +173,8 @@ impl Stream for Listing { if this.done { return Poll::Ready(None); } - if this - .options - .page_limit - .is_some_and(|limit| limit == 0 || limit > i32::MAX as u32) - { - this.done = true; - return Poll::Ready(Some(Err(Error::InvalidInput { - message: "Listing page limit must be between 1 and 2147483647".into(), - }))); - } - let pending = this - .pending - .get_or_insert_with(|| (this.fetch)(this.options.clone())); - let response = futures::ready!(pending.as_mut().poll(cx)); - this.pending = None; - match response { - Ok(response) => { - let token = response.page_token.filter(|token| !token.is_empty()); - if token - .as_ref() - .is_some_and(|token| !this.seen_tokens.insert(token.clone())) - { - this.done = true; - return Poll::Ready(Some(Err(Error::Runtime { - message: "Listing response repeated a page_token".into(), - }))); - } - this.done = token.is_none(); - this.options.page_token = token; - this.items = response.items.into_iter(); - } - Err(error) => { - this.done = true; - return Poll::Ready(Some(Err(error))); - } + if let Err(error) = futures::ready!(this.poll_fetch_page(cx)) { + return Poll::Ready(Some(Err(error))); } } } @@ -224,6 +250,36 @@ mod tests { assert!(listing.next().await.is_none()); } + #[tokio::test] + async fn next_page_preserves_empty_pages_and_remaining_items() { + let requests = Arc::new(Mutex::new(0)); + let count = requests.clone(); + let mut listing = Listing::new(ListingOptions::default(), move |options| { + *count.lock().unwrap() += 1; + async move { + let (items, page_token) = match options.page_token.as_deref() { + None => (vec![], Some("second".to_string())), + Some("second") => (vec!["a", "b"], Some("last".to_string())), + Some("last") => (vec!["c"], None), + _ => unreachable!(), + }; + Ok(ListingPage { items, page_token }) + } + }); + assert_eq!(*requests.lock().unwrap(), 0); + assert!(listing.next_page().await.unwrap().unwrap().items.is_empty()); + assert_eq!(*requests.lock().unwrap(), 1); + assert_eq!(listing.try_next().await.unwrap(), Some("a")); + assert_eq!(*requests.lock().unwrap(), 2); + let remaining = listing.next_page().await.unwrap().unwrap(); + assert_eq!(remaining.items, vec!["b"]); + assert_eq!(remaining.page_token.as_deref(), Some("last")); + assert_eq!(*requests.lock().unwrap(), 2); + assert_eq!(listing.next_page().await.unwrap().unwrap().items, vec!["c"]); + assert!(listing.next_page().await.unwrap().is_none()); + assert_eq!(*requests.lock().unwrap(), 3); + } + #[tokio::test] async fn invalid_limits_do_not_fetch() { for limit in [0, u32::MAX] { diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 95e3baac7..fa51cbf25 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -9,6 +9,11 @@ //! query this version cannot maintain reads back as unrefreshable, not as a //! plain table. Queries, indexes and search work on the view unchanged; //! writes to its rows or stored columns are refused. +//! +//! Local creation and refresh require the `experimental-functions` Cargo +//! feature. Opening, reading, listing and dropping existing views, remote +//! client operations, and shared server commit primitives remain available +//! without it. mod grouped; pub use grouped::IVF_PARTITION; @@ -166,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 on LanceDB Cloud and Enterprise" + supported only in LanceDB Distributed" ), }); } @@ -280,7 +285,7 @@ pub struct MaterializedViewInfo { /// The backend-independent request used to create a remote materialized view. #[doc(hidden)] -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq)] pub struct CreateMaterializedViewRequest { /// Name of the new view. pub name: String, @@ -290,6 +295,10 @@ pub struct CreateMaterializedViewRequest { pub query: String, /// Whether to skip the initial population job. pub with_no_data: bool, + /// Whether the server should refresh the view automatically. + pub auto_refresh_enabled: Option, + /// Refresh interval in seconds. When absent, the server determines when to refresh. + pub auto_refresh_interval_seconds: Option, } /// Prefix of the internal columns holding source columns a computed column @@ -1241,6 +1250,7 @@ impl PreparedDeclaration { namespace_path: &[String], name: &str, ) -> Result { + crate::require_experimental_functions()?; ensure_no_source_cycle(&self.database, namespace_path, name, &self.definition).await?; let empty: Vec> = vec![]; @@ -1454,7 +1464,7 @@ async fn prepare_with( ) -> Result { let Some(caller_native) = source.as_native() else { return Err(Error::NotSupported { - message: "materialized views are supported only on local databases".into(), + message: "this operation is only supported on LanceDB Embedded".into(), }); }; let source_namespace = source.namespace().to_vec(); @@ -1482,7 +1492,7 @@ async fn prepare_with( let resolved = Table::new(resolved, database.clone()); let Some(native) = resolved.as_native() else { return Err(Error::NotSupported { - message: "materialized views are supported only on local databases".into(), + message: "this operation is only supported on LanceDB Embedded".into(), }); }; let caller_uri = caller_native.dataset.get().await?.uri().to_string(); @@ -1570,6 +1580,8 @@ pub struct CreateMaterializedViewBuilder { filter: Option, limit: Option, with_no_data: bool, + auto_refresh_enabled: Option, + auto_refresh_interval_seconds: Option, } fn source_sql_identifier( @@ -1603,6 +1615,8 @@ impl CreateMaterializedViewBuilder { filter: None, limit: None, with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, } } @@ -1651,6 +1665,32 @@ impl CreateMaterializedViewBuilder { self } + /// Enable or disable automatic refresh in LanceDB Distributed. + /// 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 { + self.auto_refresh_enabled = Some(enabled); + self + } + + /// Set a positive, finite refresh interval in seconds in LanceDB Distributed. + /// When omitted, the server determines when to refresh. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// db.create_materialized_view("recent_orders", "orders") + /// .auto_refresh_enabled(true) + /// .auto_refresh_interval_seconds(300.0) + /// .execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn auto_refresh_interval_seconds(mut self, seconds: f64) -> Self { + self.auto_refresh_interval_seconds = Some(seconds); + self + } + fn query(&self) -> Result { fn quote(name: &str) -> String { format!("\"{}\"", name.replace('"', "\"\"")) @@ -1682,7 +1722,8 @@ impl CreateMaterializedViewBuilder { } /// Submit creation and initial population, returning a [`Job`] that - /// settles when the view is ready. + /// settles when the view is ready. Remote creation submits SQL; the handle's + /// [`Job::job_type`] is `"query"` and its ID identifies that query. pub async fn execute_async(self) -> Result { if self.connection.uri().starts_with("db://") { return self @@ -1693,9 +1734,12 @@ impl CreateMaterializedViewBuilder { namespace_path: self.namespace.clone(), query: self.query()?, with_no_data: self.with_no_data, + auto_refresh_enabled: self.auto_refresh_enabled, + auto_refresh_interval_seconds: self.auto_refresh_interval_seconds, }) .await; } + crate::require_experimental_functions()?; Ok(Job::spawned(tokio::spawn(async move { self.execute_native().await.map(|_| ()) }))) @@ -1719,6 +1763,13 @@ impl CreateMaterializedViewBuilder { } async fn execute_native(self) -> Result { + crate::require_experimental_functions()?; + if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { + return Err(Error::NotSupported { + message: "automatic materialized-view refresh requires LanceDB Distributed" + .to_string(), + }); + } let source = self .connection .open_table(&self.source) @@ -1774,7 +1825,7 @@ impl MaterializedView { /// The query parsed into the local refresh grammar. /// - /// Sophon may store SQL broader than the local grammar; use + /// LanceDB Enterprise may store SQL broader than the local grammar; use /// [`Self::definition_sql`] when the original SQL is sufficient. pub fn definition(&self) -> Result<&MaterializedViewDefinition> { self.parsed_definition @@ -1793,14 +1844,17 @@ impl MaterializedView { /// Recompute the view from its source. /// - /// Every refresh rebuilds the view from the selected source version. + /// Local refreshes rebuild the view from the selected source version. + /// Remote refreshes let the server select a mode unless + /// [`RefreshMaterializedViewBuilder::full`] requests a rebuild. Their + /// result leaves unavailable refresh metrics as `None`. /// /// ```no_run /// # #![recursion_limit = "256"] /// # use lancedb::materialized_view::MaterializedView; /// # async fn refresh(view: &MaterializedView) -> Result<(), Box> { /// let result = view.refresh().execute().await?; - /// println!("{:?}: {} rows", result.mode, result.rows_written); + /// println!("{:?}: {:?} rows", result.mode, result.rows_written); /// # Ok(()) /// # } /// ``` @@ -1808,6 +1862,7 @@ impl MaterializedView { RefreshMaterializedViewBuilder { view: self.clone(), source_version: None, + full: false, } } } @@ -1816,9 +1871,26 @@ impl MaterializedView { pub struct RefreshMaterializedViewBuilder { view: MaterializedView, source_version: Option, + full: bool, } impl RefreshMaterializedViewBuilder { + /// Force a complete rebuild instead of letting the server choose + /// the refresh mode. Defaults to `false`. LanceDB Embedded views always rebuild. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # use lancedb::materialized_view::MaterializedView; + /// # async fn refresh(view: &MaterializedView) -> lancedb::Result<()> { + /// view.refresh().full(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn full(mut self, full: bool) -> Self { + self.full = full; + self + } + /// Refresh a local view to this source table version instead of the latest. /// Remote SQL refreshes do not support source-version pinning. pub fn source_version(mut self, version: u64) -> Self { @@ -1833,9 +1905,10 @@ impl RefreshMaterializedViewBuilder { .view .table .base_table() - .refresh_materialized_view_async(self.source_version) + .refresh_materialized_view_async(self.source_version, self.full) .await; } + crate::require_experimental_functions()?; Ok(Job::spawned(tokio::spawn(async move { refresh::execute_refresh(&self.view.table, self.source_version).await }))) @@ -1914,8 +1987,8 @@ impl Connection { /// Drop a materialized view. /// /// The view may become unavailable before its physical data is removed. - /// Use [`Connection::drop_materialized_view_async`] to retain the cleanup - /// job and wait for it explicitly. + /// Remote drops wait for the SQL command to remove the catalog binding; + /// physical cleanup proceeds in the background. pub async fn drop_materialized_view( &self, name: impl AsRef, @@ -1926,8 +1999,9 @@ impl Connection { return self .database() .drop_materialized_view_async(name, namespace_path) - .await - .map(|_| ()); + .await? + .wait() + .await; } let table = self .open_table(name) @@ -1938,12 +2012,12 @@ impl Connection { self.drop_table(name, namespace_path).await } - /// Start dropping a materialized view and return its cleanup job. + /// Start dropping a materialized view and return its job. /// /// This validates that the named resource is a materialized view rather - /// than an ordinary table. Call [`Job::wait`] before assuming physical - /// cleanup has finished. When the backend performs cleanup inline, the - /// returned job is already finished and has no job ID. + /// than an ordinary table. In LanceDB Distributed 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. /// /// ```no_run /// # use lancedb::Connection; @@ -2018,6 +2092,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn refresh_always_rebuilds_without_source_row_ids() { let conn = connect("memory://").execute().await.unwrap(); let source = conn @@ -2046,19 +2124,23 @@ mod tests { .execute() .await .unwrap(); - let refreshed = view.refresh().execute().await.unwrap(); - assert_eq!(refreshed.mode, RefreshMode::Rebuild); - assert_eq!(refreshed.rows_written, 3); + let refreshed = view.refresh().full(true).execute().await.unwrap(); + assert_eq!(refreshed.mode, Some(RefreshMode::Rebuild)); + assert_eq!(refreshed.rows_written, Some(3)); + assert_eq!( + refreshed.source_version, + Some(source.version().await.unwrap()) + ); assert_eq!(view.table().count_rows(None).await.unwrap(), 3); let unchanged = view.refresh().execute().await.unwrap(); - assert_eq!(unchanged.mode, RefreshMode::Rebuild); - assert_eq!(unchanged.rows_written, 3); + assert_eq!(unchanged.mode, Some(RefreshMode::Rebuild)); + assert_eq!(unchanged.rows_written, Some(3)); source.delete("true").await.unwrap(); let emptied = view.refresh().execute().await.unwrap(); - assert_eq!(emptied.mode, RefreshMode::Rebuild); - assert_eq!(emptied.rows_written, 0); + assert_eq!(emptied.mode, Some(RefreshMode::Rebuild)); + assert_eq!(emptied.rows_written, Some(0)); assert_eq!(view.table().count_rows(None).await.unwrap(), 0); } @@ -2081,6 +2163,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn a_view_cannot_lead_back_to_itself() { let conn = connect("memory://").execute().await.unwrap(); let rows = || record_batch!(("x", Int32, [1, 2])).unwrap(); @@ -2116,6 +2202,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn direct_writes_to_a_view_are_refused() { use arrow_schema::Schema; use datafusion::prelude::SessionContext; @@ -2210,10 +2300,13 @@ mod tests { // Refresh, chained, is the writer. source.add(row()).execute().await.unwrap(); - assert_eq!(view.refresh().execute().await.unwrap().rows_written, 3); + assert_eq!( + view.refresh().execute().await.unwrap().rows_written, + Some(3) + ); assert_eq!( downstream.refresh().execute().await.unwrap().rows_written, - 3 + Some(3) ); assert_eq!( downstream @@ -2248,10 +2341,17 @@ mod tests { .await .unwrap(); source.drop_columns(&["y"]).await.unwrap(); - assert_eq!(view.refresh().execute().await.unwrap().rows_written, 3); + assert_eq!( + view.refresh().execute().await.unwrap().rows_written, + Some(3) + ); } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn indexes_and_optimize_still_apply_to_a_view() { use crate::index::Index; use crate::table::{CompactionOptions, OptimizeAction}; @@ -2287,7 +2387,10 @@ mod tests { .execute() .await .unwrap(); - assert_eq!(view.refresh().execute().await.unwrap().rows_written, 4); + assert_eq!( + view.refresh().execute().await.unwrap().rows_written, + Some(4) + ); view.table().optimize(OptimizeAction::All).await.unwrap(); assert_eq!( view.table().count_rows(Some("x > 2".into())).await.unwrap(), @@ -2296,6 +2399,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn computed_columns_of_a_view_are_still_filled_and_dropped() { use crate::table::computed_columns::{ COMPUTED_COLUMN_META_KEY, EXPRESSION_META_KEY, INPUTS_META_KEY, KIND_META_KEY, SQL_KIND, diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 6b4bb6d8a..1072b7684 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -45,13 +45,16 @@ pub enum RefreshMode { /// The result of refreshing a materialized view. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RefreshMaterializedViewResult { - /// How the view was brought up to date. - pub mode: RefreshMode, - /// Rows written to the replacement view. - pub rows_written: u64, - /// The source table version the view reflects. - pub source_version: u64, - /// The view table version after the refresh. + /// How the view was brought up to date, or `None` when unavailable. + /// Remote SQL refreshes currently do not expose this metric. + pub mode: Option, + /// Rows written by this refresh, or `None` when unavailable. + /// Remote SQL refreshes currently do not expose this metric. + pub rows_written: Option, + /// The source table version the view reflects, or `None` when unavailable. + /// Remote SQL refreshes currently do not expose this metric. + pub source_version: Option, + /// The view table version observed after the refresh. pub version: u64, } @@ -72,8 +75,9 @@ pub(crate) async fn execute_refresh( view: &Table, pinned: Option, ) -> Result { + crate::require_experimental_functions()?; let native = view.as_native().ok_or_else(|| Error::NotSupported { - message: "materialized views are supported only on local tables".into(), + message: "this operation is only supported on LanceDB Embedded".into(), })?; native.dataset.ensure_mutable()?; let lock = refresh_lock(native.dataset.get().await?.uri()); @@ -181,9 +185,9 @@ pub(crate) async fn execute_refresh( let version = committed.version().version; native.dataset.update(committed); Ok(RefreshMaterializedViewResult { - mode: RefreshMode::Rebuild, - rows_written: rows_written.load(Ordering::Relaxed), - source_version, + mode: Some(RefreshMode::Rebuild), + rows_written: Some(rows_written.load(Ordering::Relaxed)), + source_version: Some(source_version), version, }) } @@ -195,7 +199,7 @@ pub async fn replace_materialized_view_fragments( stream: SendableRecordBatchStream, ) -> Result { let native = view.as_native().ok_or_else(|| Error::NotSupported { - message: "materialized views are supported only on local tables".into(), + message: "this operation is only supported on LanceDB Embedded".into(), })?; native.dataset.ensure_mutable()?; let lock = refresh_lock(native.dataset.get().await?.uri()); @@ -250,6 +254,7 @@ async fn replace_fragments(dataset: Dataset, stream: SendableRecordBatchStream) update_mode: None, inserted_rows_filter: Some(inserted_rows_filter), updated_fragment_offsets: None, + mem_wal_dir_id: None, }, None, )) @@ -316,7 +321,7 @@ async fn open_source(view: &Table, definition: &MaterializedViewDefinition) -> R }) .await?; let native = source.as_native().ok_or_else(|| Error::NotSupported { - message: "materialized views are supported only on local tables".into(), + message: "this operation is only supported on LanceDB Embedded".into(), })?; Ok(native.dataset.get().await?.as_ref().clone()) } @@ -576,6 +581,10 @@ mod tests { use crate::connect; #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn raced_first_full_refresh_lands_one_result() { let directory = tempfile::tempdir().unwrap(); let connection = connect(directory.path().to_str().unwrap()) @@ -655,6 +664,7 @@ mod tests { update_mode: None, inserted_rows_filter: Some(filter), updated_fragment_offsets: None, + mem_wal_dir_id: None, }, None, )) diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index d47566442..2cff72fc5 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -444,8 +444,8 @@ pub trait QueryBase { /// # } /// ``` /// - /// Note: Expression filters are not supported for remote/server-side queries. - /// Use [`QueryBase::only_if`] with SQL strings for remote tables. + /// Note: Expression filters are not supported for LanceDB Distributed queries. + /// Use [`QueryBase::only_if`] with SQL strings in LanceDB Distributed. /// /// Calling this multiple times combines the expressions with a logical AND /// rather than replacing the previous filter. @@ -1025,7 +1025,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, for both local and remote tables. + /// after conversion to Float32, in both LanceDB Embedded and LanceDB Distributed. /// /// 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 +1269,7 @@ impl VectorQuery { /// result. /// /// NaN and infinite components are rejected with [`Error::InvalidInput`] - /// after conversion to Float32, for both local and remote tables. + /// after conversion to Float32, in both LanceDB Embedded and LanceDB Distributed. pub fn add_query_vector(mut self, vector: impl IntoQueryVector) -> Result { self.request.add_query_vector(vector)?; Ok(self) @@ -1862,6 +1862,16 @@ impl DisplayAs for TakeRestoreExec { } impl ExecutionPlan for TakeRestoreExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "TakeRestoreExec" } @@ -2714,6 +2724,159 @@ mod tests { } } + #[tokio::test] + async fn test_limit_usize_max() { + let conn = connect("memory://foo").execute().await.unwrap(); + let table = conn + .create_table("my_table", make_non_empty_batches()) + .execute() + .await + .unwrap(); + let expected = table.count_rows(None).await.unwrap(); + + let batches: Vec = table + .query() + .limit(usize::MAX) + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum(); + assert_eq!(num_rows, expected); + + let batches: Vec = table + .query() + .limit(usize::MAX) + .offset(1) + .nearest_to(&[0.1; 4]) + .unwrap() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum(); + assert_eq!(num_rows, expected - 1); + } + + #[tokio::test] + async fn test_indexed_vector_limit_usize_max() { + use crate::index::vector::IvfFlatIndexBuilder; + + let conn = connect("memory://indexed_limit").execute().await.unwrap(); + let table = conn + .create_table("vectors", make_non_empty_batches()) + .execute() + .await + .unwrap(); + table + .create_index( + &["vector"], + Index::IvfFlat(IvfFlatIndexBuilder::default().num_partitions(1)), + ) + .execute() + .await + .unwrap(); + let expected = table.count_rows(None).await.unwrap(); + + for limit in [expected, i64::MAX as usize, usize::MAX] { + for offset in [0, 1, usize::MAX] { + for (bypass, refine_factor) in [(false, None), (false, Some(2)), (true, None)] { + let query = table + .query() + .limit(limit) + .offset(offset) + .nearest_to(&[0.1; 4]) + .unwrap(); + let query = if bypass { + query.bypass_vector_index() + } else { + query + }; + let query = if let Some(factor) = refine_factor { + query.refine_factor(factor) + } else { + query + }; + let batches: Vec = + query.execute().await.unwrap().try_collect().await.unwrap(); + assert_eq!( + batches.iter().map(RecordBatch::num_rows).sum::(), + expected.saturating_sub(offset), + "limit={limit}, offset={offset}, bypass={bypass}, refine={refine_factor:?}" + ); + } + } + } + } + + #[tokio::test] + async fn test_empty_vector_limit_usize_max() { + let conn = connect("memory://empty_limit").execute().await.unwrap(); + let table = conn + .create_table("vectors", make_test_batches()) + .execute() + .await + .unwrap(); + let batches: Vec = table + .query() + .limit(usize::MAX) + .nearest_to(&[0.1; 128]) + .unwrap() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + } + + #[tokio::test] + async fn test_fts_limit_usize_max_with_offset() { + let conn = connect("memory://fts_limit").execute().await.unwrap(); + let data = RecordBatch::try_from_iter([( + "text", + Arc::new(StringArray::from_iter_values((0..32).map(|_| "hello"))) + as arrow_array::ArrayRef, + )]) + .unwrap(); + let table = conn + .create_table("documents", data) + .execute() + .await + .unwrap(); + table + .create_index(&["text"], Index::FTS(Default::default())) + .execute() + .await + .unwrap(); + + for limit in [32, i64::MAX as usize, usize::MAX] { + for offset in [0, 1, i64::MAX as usize, usize::MAX] { + let batches: Vec = table + .query() + .full_text_search(FullTextSearchQuery::new("hello".into())) + .limit(limit) + .offset(offset) + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!( + batches.iter().map(RecordBatch::num_rows).sum::(), + 32usize.saturating_sub(offset), + "limit={limit}, offset={offset}" + ); + } + } + } + #[tokio::test] async fn test_repeated_only_if_combines_with_and() { use crate::expr::{col, lit}; diff --git a/rust/lancedb/src/remote.rs b/rust/lancedb/src/remote.rs index a6b2f0e62..5abe4dcf7 100644 --- a/rust/lancedb/src/remote.rs +++ b/rust/lancedb/src/remote.rs @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors //! This module contains a remote client for a LanceDB server. This is used -//! to communicate with LanceDB cloud. It can also serve as an example for +//! to communicate with LanceDB Enterprise or LanceDB Cloud (legacy). It can also serve as an example for //! building client/server applications with LanceDB or as a client for some //! other custom LanceDB service. diff --git a/rust/lancedb/src/remote/catalog.rs b/rust/lancedb/src/remote/catalog.rs index df3782368..95facd04b 100644 --- a/rust/lancedb/src/remote/catalog.rs +++ b/rust/lancedb/src/remote/catalog.rs @@ -226,7 +226,14 @@ impl Catalog for RemoteCatalog { } .into(), ), - behavior: Some("Restrict".into()), + behavior: Some( + if request.cascade { + "Cascade" + } else { + "Restrict" + } + .into(), + ), ..Default::default() }) .await; @@ -474,7 +481,7 @@ mod tests { } #[tokio::test] - async fn catalog_preserves_errors_and_never_cascades() { + async fn catalog_preserves_errors_and_restricts_drops_by_default() { let (endpoint, task) = server(vec![ (404, json!({"error": "missing"})), (409, json!({"error": "exists"})), @@ -522,6 +529,26 @@ mod tests { ); } + #[tokio::test] + async fn drop_database_cascades_only_when_asked() { + let (endpoint, task) = server(vec![(200, json!({})), (200, json!({}))]).await; + let catalog = RemoteCatalog::try_new(endpoint, RemoteCatalogOptions::default()).unwrap(); + catalog.drop_database("db".into()).await.unwrap(); + catalog + .drop_database(DropDatabaseRequest::new("db").cascade(true)) + .await + .unwrap(); + let requests = task.await.unwrap(); + assert_eq!( + requests[0].body, + json!({"mode": "Fail", "behavior": "Restrict"}) + ); + assert_eq!( + requests[1].body, + json!({"mode": "Fail", "behavior": "Cascade"}) + ); + } + #[tokio::test] async fn database_names_follow_pages_lazily() { use futures::TryStreamExt; diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index 783d2ef84..ae4c1aaa5 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -83,7 +83,8 @@ const DEFAULT_MAX_BYTES_PER_REQUEST: u64 = 8 * 1024 * 1024 * 1024; /// timeout (which also covers the request-body upload) fires. const DEFAULT_MAX_REQUEST_DURATION_DIVISOR: u32 = 2; -/// Configuration for the LanceDB Cloud HTTP client. +/// Configuration for the HTTP client used to connect to LanceDB Enterprise or +/// LanceDB Cloud (legacy). #[derive(Clone)] pub struct ClientConfig { pub timeout_config: TimeoutConfig, @@ -108,7 +109,7 @@ pub struct ClientConfig { pub header_provider: Option>, /// User identifier for tracking purposes. /// - /// This is sent as the `x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise. + /// This is sent as the `x-lancedb-user-id` header in requests to LanceDB Enterprise. /// It can be set directly, or via the `LANCEDB_USER_ID` environment variable. /// Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment /// variable that contains the user ID value. @@ -233,6 +234,10 @@ pub struct TimeoutConfig { pub connect_timeout: Option, /// The timeout for reading a response from the server. /// + /// This also applies while waiting for response headers during an upload. + /// A large or slowly produced request body (for example, when creating a + /// table) may need a longer timeout even if data is still being uploaded. + /// /// You can also set the `LANCE_CLIENT_READ_TIMEOUT` environment variable /// to set this value. Use an integer value in seconds. /// @@ -378,23 +383,30 @@ pub struct ParsedDbUrl { /// Parse a database URL and extract the database name and optional prefix. /// -/// Expected format: `db://db_name` or `db://db_name/prefix` +/// Expected format: `db://db_name`, `db://db_name/prefix`, or `db://` when +/// connecting to the storage root through a host override. pub fn parse_db_url(db_url: &str) -> Result { let parsed_url = url::Url::parse(db_url).map_err(|err| Error::InvalidInput { message: format!("db_url is not a valid URL. '{db_url}'. Error: {err}"), })?; debug_assert_eq!(parsed_url.scheme(), "db"); - if !parsed_url.has_host() { - return Err(Error::InvalidInput { - message: format!("Invalid database URL (missing host) '{}'", db_url), - }); - } - let db_name = urlencoding::decode(parsed_url.host_str().unwrap()) - .map_err(|err| Error::InvalidInput { - message: format!("Invalid encoded database name: {err}"), - })? - .into_owned(); - validate_database_name(&db_name)?; + let db_name = match parsed_url.host_str() { + Some(db_name) => { + let db_name = urlencoding::decode(db_name) + .map_err(|err| Error::InvalidInput { + message: format!("Invalid encoded database name: {err}"), + })? + .into_owned(); + validate_database_name(&db_name)?; + db_name + } + None if matches!(parsed_url.path(), "" | "/") => String::new(), + None => { + return Err(Error::InvalidInput { + message: format!("Invalid database URL (missing host) '{}'", db_url), + }); + } + }; let db_prefix = { let prefix = parsed_url.path().trim_start_matches('/'); if prefix.is_empty() { @@ -802,6 +814,11 @@ impl RestfulLanceDbClient { self.client.get(full_uri) } + pub fn head(&self, uri: &str) -> RequestBuilder { + let full_uri = format!("{}{}", self.host, uri); + self.client.head(full_uri) + } + pub fn post(&self, uri: &str) -> RequestBuilder { let full_uri = format!("{}{}", self.host, uri); self.client.post(full_uri) @@ -1193,6 +1210,117 @@ pub mod test_utils { #[cfg(test)] mod tests { + #[tokio::test] + async fn test_http_timeout_error_is_actionable() { + use super::*; + use futures::StreamExt; + + // Keep consuming the upload without sending response headers (HTTP) or + // completing the TLS handshake (HTTPS). The HTTP body never reaches EOF, + // so its read timeout fires while it is still uploading. + for (scheme, retry) in [ + ("http", false), + ("http", true), + ("https", false), + ("https", true), + ] { + let connect_timeout = scheme == "https"; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let _ = tokio::io::copy(&mut socket, &mut tokio::io::sink()).await; + }); + let client = RestfulLanceDbClient::try_new( + &parse_db_url("db://test").unwrap(), + "us-east-1", + Some(format!("{scheme}://{address}")), + HeaderMap::new(), + ClientConfig { + timeout_config: TimeoutConfig { + connect_timeout: Some(Duration::from_millis(200)), + read_timeout: Some(Duration::from_secs(2)), + ..Default::default() + }, + retry_config: RetryConfig { + connect_retries: Some(1), + read_retries: Some(1), + ..Default::default() + }, + ..Default::default() + }, + None, + ) + .unwrap(); + let make_body = || { + Ok(Body::wrap_stream( + futures::stream::once(async { + Ok::<_, std::io::Error>(bytes::Bytes::from_static(b"upload")) + }) + .chain(futures::stream::pending()), + )) + }; + let request = client + .post("/v1/table/test/create/") + .header(REQUEST_ID_HEADER, "upload-timeout"); + let error = if retry { + client + .send_with_retry(request, Some(Box::new(make_body)), true) + .await + } else { + client.send(request.body(make_body().unwrap())).await + } + .unwrap_err(); + server.abort(); + + let message = error.to_string(); + assert!(message.contains("timed out"), "{message}"); + let (config, env_var) = if connect_timeout { + ( + "client_config.timeout_config.connect_timeout", + "LANCE_CLIENT_CONNECT_TIMEOUT", + ) + } else { + ( + "client_config.timeout_config.read_timeout", + "LANCE_CLIENT_READ_TIMEOUT", + ) + }; + assert!(message.contains(config), "{message}"); + assert!( + message.contains("client_config.timeout_config.timeout"), + "{message}" + ); + assert!(message.contains(env_var), "{message}"); + let (request_id, status_code, source) = match &error { + Error::Http { + request_id, + status_code, + source, + } if !retry => (request_id, status_code, source), + Error::Retry { + request_id, + status_code, + source, + read_failures, + connect_failures, + .. + } if retry => { + assert_eq!(*read_failures, u8::from(!connect_timeout)); + assert_eq!(*connect_failures, u8::from(connect_timeout)); + (request_id, status_code, source) + } + other => panic!("unexpected error: {other:?}"), + }; + assert_eq!(request_id, "upload-timeout"); + assert_eq!(*status_code, None); + // Retain the typed source for retry classification and Python causes. + let source = source.downcast_ref::().unwrap(); + assert!(source.is_timeout()); + assert_eq!(source.is_connect(), connect_timeout); + } + } + /// A configuration naming any other delimiter is refused where it was /// written, rather than producing identifiers no service splits the way the /// caller meant. diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a0f4aa953..5c85d0792 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -47,14 +47,11 @@ use super::client::{ Sender, }; use super::sql::SqlClient; +use super::sql::materialized_view::quote_identifier; use super::table::RemoteTable; use super::util::parse_server_version; use super::{ARROW_STREAM_CONTENT_TYPE, extract_job_id}; -fn quote_sql_identifier(identifier: &str) -> String { - format!("\"{}\"", identifier.replace('"', "\"\"")) -} - // Request structure for the remote clone table API #[derive(serde::Serialize)] struct RemoteCloneTableRequest { @@ -120,7 +117,7 @@ pub const OPT_REMOTE_SQL_HOST_OVERRIDE: &str = "remote_database_sql_host_overrid #[derive(Clone, Debug, Default)] pub struct RemoteDatabaseOptions { - /// The LanceDB Cloud API key + /// The LanceDB Enterprise or LanceDB Cloud (legacy) API key pub api_key: Option, /// The LanceDB Cloud region pub region: Option, @@ -190,11 +187,11 @@ impl RemoteDatabaseOptionsBuilder { } } - /// Set the LanceDB Cloud API key + /// Set the LanceDB Enterprise or LanceDB Cloud (legacy) API key /// /// # Arguments /// - /// * `api_key` - The LanceDB Cloud API key + /// * `api_key` - The API key pub fn api_key(mut self, api_key: String) -> Self { self.options.api_key = Some(api_key); self @@ -313,6 +310,13 @@ impl RemoteDatabase { read_consistency_interval: Option, ) -> Result { let parsed = super::client::parse_db_url(uri)?; + if parsed.db_name.is_empty() && host_overrides.rest.is_none() { + return Err(Error::InvalidInput { + message: + "A host override is required when connecting to the storage root with 'db://'" + .to_string(), + }); + } Self::try_new_with_identity( uri, api_key, @@ -582,6 +586,11 @@ mod test_utils { } } + pub(in crate::remote) fn with_sql_client(mut self, client: SqlClient) -> Self { + self.sql_client = Some(client); + self + } + pub fn new_mock_with_config(handler: F, config: ClientConfig) -> Self where F: Fn(reqwest::Request) -> http::Response + Send + Sync + 'static, @@ -862,7 +871,7 @@ impl Database for RemoteDatabase { async fn read_consistency(&self) -> Result { Err(Error::NotSupported { - message: "Getting the read consistency of a remote database is not yet supported" + message: "Getting the read consistency is not yet supported in LanceDB Distributed" .to_string(), }) } @@ -873,20 +882,49 @@ impl Database for RemoteDatabase { ) -> Result { if request.with_no_data { return Err(Error::NotSupported { - message: "remote materialized views are always populated by their SQL job" - .to_string(), + message: + "materialized views in LanceDB Distributed must be populated during creation" + .to_string(), }); } - let client = self.sql_client.clone().ok_or_else(|| Error::NotSupported { - message: "SQL is unavailable for this remote database client".to_string(), - })?; - let namespace = request.namespace_path; - let statement = format!( - "CREATE MATERIALIZED VIEW {} AS {}", - quote_sql_identifier(&request.name), - request.query - ); - Ok(client.submit_as_job(statement, namespace, || async { Ok(()) })) + if let Some(seconds) = request.auto_refresh_interval_seconds + && (!seconds.is_finite() || seconds <= 0.0) + { + return Err(Error::InvalidInput { + message: "auto_refresh_interval_seconds must be positive, finite seconds".into(), + }); + } + validate_table_name(&request.name)?; + validate_namespace(&request.namespace_path)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".into(), + })?; + let mut options = Vec::new(); + if let Some(enabled) = request.auto_refresh_enabled { + options.push(format!("auto_refresh_enabled = {enabled}")); + } + if let Some(seconds) = request.auto_refresh_interval_seconds { + options.push(format!("auto_refresh_interval_seconds = {seconds}")); + } + let name = request.name.replace('"', "\"\""); + let options = if options.is_empty() { + String::new() + } else { + format!(" WITH ({})", options.join(", ")) + }; + client + .submit_as_job( + format!( + "CREATE MATERIALIZED VIEW \"{name}\"{options} AS {}", + request.query + ), + request.namespace_path, + || async { Ok(()) }, + ) + .await } async fn drop_materialized_view_async( @@ -894,36 +932,26 @@ impl Database for RemoteDatabase { name: &str, namespace_path: &[String], ) -> Result { - let identifier = build_table_identifier(name, namespace_path)?; - let request = self - .client - .post(&format!("/v1/materialized_view/{identifier}/drop")); - let (request_id, response) = self.client.send(request).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 = match status { - StatusCode::OK => Job::new_done(), - StatusCode::ACCEPTED => { - let job_id = extract_job_id(&body).ok_or_else(|| Error::Http { - source: "materialized-view 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: "materialized-view drop must return 200 OK or 202 Accepted".into(), - request_id, - status_code: Some(status), - }); - } - }; - self.table_cache - .remove(&build_cache_key(name, namespace_path)) - .await; - Ok(job) + validate_table_name(name)?; + validate_namespace(namespace_path)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".into(), + })?; + let cache = self.table_cache.clone(); + let key = build_cache_key(name, namespace_path); + client + .submit_as_job( + format!("DROP MATERIALIZED VIEW {}", quote_identifier(name)), + namespace_path.to_vec(), + move || async move { + cache.remove(&key).await; + Ok(()) + }, + ) + .await } async fn list_materialized_views( @@ -931,23 +959,13 @@ impl Database for RemoteDatabase { namespace_path: &[String], options: ListingOptions, ) -> Result> { - let namespace_id = build_namespace_identifier(namespace_path)?; - let path = format!("/v1/namespace/{namespace_id}/materialized_view/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: RemoteListViewsResponse = response.json().await.err_to_http(request_id)?; - let items = response.views; - Ok(ListingPage { - items, - page_token: response.page_token, - }) + self.sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".into(), + })? + .list_materialized_views(namespace_path, options) + .await } async fn create_function_async( @@ -1339,6 +1357,16 @@ impl Database for RemoteDatabase { }) } + async fn check_sql_connection(&self) -> Result<()> { + self.sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".into(), + })? + .check_connection() + .await + } + async fn execute_query_async(&self, request: ExecuteQueryRequest) -> Result { let client = self .sql_client @@ -1446,6 +1474,25 @@ impl Database for RemoteDatabase { } async fn create_table(&self, mut request: CreateTableRequest) -> Result> { + // The remote create endpoint does not transmit Lance write parameters. + // Reject them before consuming data or issuing a request, especially + // for overwrite: silently using the server's format can lose intent. + for (option, provided) in [ + ( + "write_options (including storage_options)", + request.write_options.lance_write_params.is_some(), + ), + ("location", request.location.is_some()), + ("namespace_client", request.namespace_client.is_some()), + ] { + if provided { + return Err(Error::NotSupported { + message: format!( + "{option} is not supported for table creation in LanceDB Distributed" + ), + }); + } + } let data_schema = request.data.schema(); let body = stream_as_body(request.data.scan_as_stream())?; @@ -1570,11 +1617,41 @@ impl Database for RemoteDatabase { } async fn open_table(&self, request: OpenTableRequest) -> Result> { + // Validate before looking in the cache as well as before sending HTTP. + for (option, provided) in [ + ("index_cache_size", request.index_cache_size.is_some()), + ( + "lance_read_params (including storage_options)", + request.lance_read_params.is_some(), + ), + ("location", request.location.is_some()), + ("namespace_client", request.namespace_client.is_some()), + ("managed_versioning", request.managed_versioning.is_some()), + ] { + if provided { + return Err(Error::NotSupported { + message: format!( + "{option} is not supported for table access in LanceDB Distributed" + ), + }); + } + } let identifier = build_table_identifier(&request.name, &request.namespace_path)?; let cache_key = build_cache_key(&request.name, &request.namespace_path); // Every open gets its own checkout, schema cache, and freshness state. if let Some(version) = self.table_cache.get(&cache_key).await { + // A cached version can outlive a drop from another connection. Verify that + // the table still exists before returning a handle for it. + let req = self + .client + .post(&format!("/v1/table/{}/describe/", identifier)) + .json(&serde_json::json!({})); + let (request_id, rsp) = self.client.send_with_retry(req, None, true).await?; + let rsp = + RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; + self.client.check_response(&request_id, rsp).await?; + Ok(Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), request.name, @@ -1675,7 +1752,9 @@ impl Database for RemoteDatabase { // 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".to_string(), + message: "Dropping all tables is not currently supported in the remote API. \ + List tables and call drop_table for each table instead." + .to_string(), }) } @@ -1964,42 +2043,23 @@ mod tests { } #[tokio::test] - async fn test_create_materialized_view_requires_sql_client() { - let db = super::RemoteDatabase::new_mock(|request| -> http::Response { - panic!("unexpected REST request: {}", request.url().path()) + 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") }); - let error = db - .create_materialized_view_async(CreateMaterializedViewRequest { - name: "adults".into(), - namespace_path: vec!["analytics".into()], - query: "SELECT age AS \"age\" FROM \"raw\".\"people\" WHERE age >= 18 LIMIT 10" - .into(), - with_no_data: false, - }) - .await - .unwrap_err(); - assert!(error.to_string().contains("SQL is unavailable")); - } - - #[tokio::test] - async fn test_drop_materialized_view_uses_item_route_and_job() { - let db = super::RemoteDatabase::new_mock(|request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/materialized_view/analytics$adults/drop" - ); - assert!(request.body().is_none()); - http::Response::builder() - .status(202) - .body(serde_json::json!({"job_id": "j1-mv-drop"}).to_string()) - .unwrap() - }); - let job = db - .drop_materialized_view_async("adults", &["analytics".into()]) - .await - .unwrap(); - assert_eq!(job.id(), Some("j1-mv-drop")); + 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] @@ -2053,100 +2113,6 @@ mod tests { } } - #[tokio::test] - async fn test_drop_materialized_view_completed_inline() { - let db = super::RemoteDatabase::new_mock(|request| { - assert_eq!(request.method(), "POST"); - assert_eq!(request.url().path(), "/v1/materialized_view/adults/drop"); - http::Response::builder().status(200).body("{}").unwrap() - }); - let job = db - .drop_materialized_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_materialized_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_materialized_view_async("adults", &[]) - .await - .err() - .unwrap(); - assert!(error.to_string().contains("valid job_id")); - } - } - - #[tokio::test] - async fn test_drop_materialized_view_rejects_unexpected_success_status() { - let db = super::RemoteDatabase::new_mock(|_| { - http::Response::builder().status(204).body("").unwrap() - }); - let error = db - .drop_materialized_view_async("adults", &[]) - .await - .err() - .unwrap(); - assert!(error.to_string().contains("200 OK or 202 Accepted")); - } - - #[tokio::test] - async fn test_list_materialized_views_follows_empty_pages() { - let page = Arc::new(AtomicUsize::new(0)); - let db = super::RemoteDatabase::new_mock({ - let page = page.clone(); - move |request| { - assert_eq!(request.method(), "GET"); - assert_eq!( - request.url().path(), - "/v1/namespace/analytics/materialized_view/list" - ); - match page.fetch_add(1, Ordering::SeqCst) { - 0 => { - assert!(request.url().query().is_none()); - http::Response::builder() - .status(200) - .body( - serde_json::json!({"views": [], "page_token": "next"}).to_string(), - ) - .unwrap() - } - 1 => { - assert_eq!(request.url().query(), Some("page_token=next")); - http::Response::builder() - .status(200) - .body(serde_json::json!({"views": ["adults"]}).to_string()) - .unwrap() - } - _ => panic!("listing requested too many pages"), - } - } - }); - assert_eq!( - Listing::new(Default::default(), { - let db = Arc::new(db); - move |options| { - let db = db.clone(); - async move { - db.list_materialized_views(&["analytics".into()], options) - .await - } - } - }) - .try_collect::>() - .await - .unwrap(), - ["adults"] - ); - } - #[tokio::test] async fn test_retries() { // We'll record the request_id here, to check it matches the one in the error. @@ -2265,16 +2231,8 @@ mod tests { .unwrap() .is_empty() ); - let page = conn - .list_tables(lance_namespace::models::ListTablesRequest { - id: Some(namespace), - limit: Some(0), - ..Default::default() - }) - .await - .unwrap(); - assert!(page.tables.is_empty()); - assert!(page.page_token.is_none()); + let mut listing = conn.list_tables(&namespace, ListingOptions::default().page_limit(0)); + assert!(listing.next_page().await.is_err()); } #[rstest::rstest] @@ -2309,25 +2267,17 @@ mod tests { ) .unwrap() }); - let first = conn - .list_tables(lance_namespace::models::ListTablesRequest { - id: Some(namespace.clone()), - ..Default::default() - }) - .await - .unwrap(); - assert_eq!(first.tables.len(), 100); + let mut first_listing = conn.list_tables(&namespace, ListingOptions::default()); + let first = first_listing.next_page().await.unwrap().unwrap(); + assert_eq!(first.items.len(), 100); assert_eq!(first.page_token.as_deref(), Some("opaque-token")); - let second = conn - .list_tables(lance_namespace::models::ListTablesRequest { - id: Some(namespace), - page_token: first.page_token, - ..Default::default() - }) - .await - .unwrap(); + let mut second_listing = conn.list_tables( + &namespace, + ListingOptions::default().page_token(first.page_token.unwrap()), + ); + let second = second_listing.next_page().await.unwrap().unwrap(); let expected: Vec<_> = (100..130).map(|i| format!("t{i:03}")).collect(); - assert_eq!(second.tables, expected); + assert_eq!(second.items, expected); assert!(second.page_token.is_none()); } @@ -2470,14 +2420,45 @@ mod tests { let table = conn.open_table("table1").execute().await.unwrap(); assert_eq!(table.name(), "table1"); - // Storage options should be ignored. - let table = conn + // Per-table storage options must not be silently ignored. + let result = conn .open_table("table1") .storage_option("key", "value") .execute() - .await - .unwrap(); - assert_eq!(table.name(), "table1"); + .await; + assert!(matches!(result, Err(Error::NotSupported { message }) + if message.contains("storage_options"))); + } + + #[tokio::test] + async fn test_open_table_checks_that_a_cached_table_still_exists() { + let describe_calls = Arc::new(AtomicUsize::new(0)); + let calls = describe_calls.clone(); + let mut db = super::RemoteDatabase::new_mock(move |request| { + assert_eq!(request.url().path(), "/v1/table/table1/describe/"); + match calls.fetch_add(1, Ordering::SeqCst) { + 0 => http::Response::builder() + .status(200) + .body(r#"{"version": 1}"#.to_string()) + .unwrap(), + 1 => http::Response::builder() + .status(404) + .body("table not found".to_string()) + .unwrap(), + call => panic!("unexpected describe call: {call}"), + } + }); + db.table_cache = moka::future::Cache::new(10); + let conn = Connection::new( + Arc::new(db), + Arc::new(crate::embeddings::MemoryRegistry::new()), + ); + + conn.open_table("table1").execute().await.unwrap(); + let result = conn.open_table("table1").execute().await; + + assert!(matches!(result, Err(Error::TableNotFound { .. }))); + assert_eq!(describe_calls.load(Ordering::SeqCst), 2); } #[tokio::test] @@ -2670,6 +2651,126 @@ mod tests { ); } + #[rstest] + #[case("new_table_data_storage_version", "2.0")] + #[case("new_table_enable_v2_manifest_paths", "false")] + #[case("bogus_option_xyz", "1")] + #[tokio::test] + async fn test_create_rejects_local_storage_options(#[case] key: &str, #[case] value: &str) { + let conn = Connection::new_with_handler(|_| -> http::Response<&'static str> { + panic!("must not send a create request") + }); + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); + let data = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], + ) + .unwrap(); + for builder in [ + conn.create_table("table1", data), + conn.create_empty_table("table1", schema), + ] { + let result = builder + .mode(CreateTableMode::Overwrite) + .storage_option(key, value) + .execute() + .await; + assert!(matches!(result, Err(Error::NotSupported { message }) + if message.contains("write_options") && message.contains("LanceDB Distributed"))); + } + } + + #[tokio::test] + async fn test_create_rejects_local_write_params_and_location() { + let conn = Connection::new_with_handler(|_| -> http::Response<&'static str> { + panic!("must not send a create request") + }); + let schema = Arc::new(Schema::empty()); + for builder in [ + conn.create_empty_table("table1", schema.clone()) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(lance::dataset::WriteParams::default()), + }), + conn.create_empty_table("table1", schema) + .location("/tmp/elsewhere"), + ] { + assert!(matches!( + builder.execute().await, + Err(Error::NotSupported { .. }) + )); + } + } + + #[rstest] + #[tokio::test] + async fn test_open_rejects_local_options_even_when_cached(#[values(false, true)] cached: bool) { + let mut db = super::RemoteDatabase::new_mock(|request| { + assert_eq!(request.url().path(), "/v1/table/table1/create/"); + http::Response::builder().status(200).body("").unwrap() + }); + db.table_cache = moka::future::Cache::new(10); + let table_cache = db.table_cache.clone(); + let conn = Connection::new( + Arc::new(db), + Arc::new(crate::embeddings::MemoryRegistry::new()), + ); + if cached { + conn.create_empty_table("table1", Arc::new(Schema::empty())) + .execute() + .await + .unwrap(); + } + assert_eq!( + table_cache + .get(&build_cache_key("table1", &[])) + .await + .is_some(), + cached + ); + for (option, builder) in [ + ( + "index_cache_size", + conn.open_table("table1").index_cache_size(10), + ), + ( + "storage_options", + conn.open_table("table1").storage_option("x", "y"), + ), + ("location", conn.open_table("table1").location("/tmp/zzz")), + ( + "managed_versioning", + conn.open_table("table1").managed_versioning(false), + ), + ( + "lance_read_params", + conn.open_table("table1") + .lance_read_params(Default::default()), + ), + ] { + let result = builder.execute().await; + assert!(matches!(result, Err(Error::NotSupported { message }) + if message.contains(option) && message.contains("LanceDB Distributed"))); + } + } + + #[tokio::test] + async fn test_connect_rejects_local_options() { + for (option, builder) in [ + ( + "manifest_enabled", + ConnectBuilder::new("db://dev").manifest_enabled(true), + ), + ( + "namespace_client_properties", + ConnectBuilder::new("db://dev").namespace_client_properties([("root", "/tmp/db")]), + ), + ] { + 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"))); + } + } + #[rstest] #[case::matching(Field::new("a", DataType::Int32, false), true)] #[case::different_name(Field::new("x", DataType::Int32, false), false)] @@ -3596,14 +3697,9 @@ mod tests { assert!(table.is_ok(), "Failed to create table: {:?}", table.err()); // List tables in the child namespace - let list_response = conn - .list_tables(ListTablesRequest { - id: Some(namespace.clone()), - ..Default::default() - }) - .await - .expect("Failed to list tables"); - assert_eq!(list_response.tables, vec!["test_table"]); + let list_response = conn.list_tables(&namespace, ListingOptions::default()); + let names = list_response.try_collect::>().await.unwrap(); + assert_eq!(names, vec!["test_table"]); // Get namespace client and verify it can also list tables let namespace_client = conn.namespace_client().await.unwrap(); @@ -3670,17 +3766,12 @@ mod tests { } // List tables in the child namespace - let list_response = conn - .list_tables(ListTablesRequest { - id: Some(namespace.clone()), - ..Default::default() - }) - .await - .unwrap(); - assert_eq!(list_response.tables.len(), 3); - assert!(list_response.tables.contains(&"table1".to_string())); - assert!(list_response.tables.contains(&"table2".to_string())); - assert!(list_response.tables.contains(&"table3".to_string())); + let list_response = conn.list_tables(&namespace, ListingOptions::default()); + let names = list_response.try_collect::>().await.unwrap(); + assert_eq!(names.len(), 3); + assert!(names.contains(&"table1".to_string())); + assert!(names.contains(&"table2".to_string())); + assert!(names.contains(&"table3".to_string())); } } @@ -3703,7 +3794,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", "materialized_view", "jobs"] { + for resource in ["secret", "view", "function", "jobs"] { let count = Arc::new(AtomicUsize::new(0)); let conn = Connection::new_with_handler({ let count = count.clone(); @@ -3718,11 +3809,7 @@ mod tests { .unwrap(); assert_eq!(body, serde_json::json!({"page_token": token, "limit": 2})); } else { - let ns = if resource == "materialized_view" { - "$" - } else { - "team" - }; + let ns = "team"; assert_eq!( request.url().path(), format!("/v1/namespace/{ns}/{resource}/list") @@ -3762,7 +3849,6 @@ mod tests { "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, - "materialized_view" => check(conn.list_materialized_views(options), count).await, _ => check(conn.list_jobs(options), count).await, } } diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 41d8971ac..7d2e70ac9 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -18,7 +18,9 @@ use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; /// Delay before the second job-state poll; doubles up to [`MAX_POLL_INTERVAL`]. const INITIAL_POLL_INTERVAL: Duration = Duration::from_millis(200); -const MAX_POLL_INTERVAL: Duration = Duration::from_secs(5); +/// A job's completion is seen at most this long after it happens. A 5 s cap +/// added 2.5 s on average to every short refresh, as much as the job itself. +const MAX_POLL_INTERVAL: Duration = Duration::from_secs(1); #[derive(Debug, Clone, PartialEq, Eq)] enum JobState { @@ -268,13 +270,18 @@ impl JobHandle for RemoteJob { #[cfg(test)] mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + 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::remote::client::test_utils::client_with_handler; - use super::DescribeJobResponse; + use super::{DescribeJobResponse, RemoteJob}; const FUNCTION_JOB: &str = include_str!("../../tests/fixtures/first_class_functions/v1/remote_function_job.json"); @@ -333,6 +340,31 @@ mod tests { ); } + /// Five in-progress polls then done: 0.2 + 0.4 + 0.8 + 1 + 1 s of waiting. + /// Under the old 5 s cap the same job would have waited 10 s. + #[tokio::test(start_paused = true)] + async fn wait_polls_at_most_every_second() { + 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 < 5 { + r#"{"job_state":"IN_PROGRESS"}"#.to_string() + } else { + UNIT_JOB.to_string() + }; + http::Response::builder().status(200).body(body).unwrap() + }); + let started = tokio::time::Instant::now(); + RemoteJob::new(client, "job-1".to_string()) + .wait() + .await + .expect("unit job completes"); + assert_eq!(describes.load(Ordering::SeqCst), 6); + assert_eq!(started.elapsed(), Duration::from_millis(3400)); + } + #[test] fn remote_wire_unknown_fields_are_forward_decodable() { let response: DescribeJobResponse = diff --git a/rust/lancedb/src/remote/oauth.rs b/rust/lancedb/src/remote/oauth.rs index c7cffa327..95d74274e 100644 --- a/rust/lancedb/src/remote/oauth.rs +++ b/rust/lancedb/src/remote/oauth.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! OAuth authentication for LanceDB Cloud connections. +//! OAuth authentication for LanceDB Enterprise connections. //! //! Protocol mechanics (authorization URL and CSRF state, PKCE, token //! exchanges, refresh, device authorization and polling, standard response diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index a58a9afad..880f61045 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use std::fs; -use std::future::{Future, pending}; +use std::future::Future; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex as StdMutex, OnceLock}; use std::time::{Duration, Instant}; @@ -12,6 +12,7 @@ use arrow_array::RecordBatch; use arrow_flight::decode::FlightRecordBatchStream; use arrow_flight::error::FlightError; use arrow_flight::flight_service_client::FlightServiceClient; +#[cfg(test)] use arrow_flight::sql::{CommandStatementQuery, ProstMessageExt}; use arrow_flight::{ Action, CancelFlightInfoRequest, CancelFlightInfoResult, CancelStatus, FlightClient, @@ -22,7 +23,7 @@ use futures::TryStreamExt; use http::header::{HeaderMap, HeaderName, HeaderValue}; use prost::Message; use serde::{Serialize, de::DeserializeOwned}; -use tokio::sync::{Mutex, Notify, OnceCell, mpsc, watch}; +use tokio::sync::{Mutex, Notify, OnceCell, mpsc}; use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity}; use uuid::Uuid; @@ -34,9 +35,10 @@ use crate::remote::client::{ClientConfig, TlsConfig}; use crate::remote::retry::ResolvedRetryConfig; use crate::sql::{Query, QueryDescription, QueryHandle, QueryStatus}; -mod exchange; +pub(super) mod materialized_view; +mod stream; -use exchange::{ExchangeQuery, ExchangeQueryHandle}; +use stream::{StreamingQuery, StreamingQueryHandle, Submission}; const DEFAULT_SQL_PORT: u16 = 10025; const DEFAULT_SQL_TLS_PORT: u16 = 10026; @@ -168,6 +170,13 @@ impl std::fmt::Debug for SqlClient { } impl SqlClient { + pub(super) async fn check_connection(&self) -> Result<()> { + self.inner + .connection(&Uuid::new_v4().to_string()) + .await + .map(|_| ()) + } + pub(super) fn new( database: String, database_prefix: Option, @@ -191,22 +200,42 @@ impl SqlClient { } pub(super) async fn execute(&self, request: ExecuteQueryRequest) -> Result { - match request.parameters { - Some(parameters) => { - self.submit_with_parameters( - &request.query, - parameters, - &request.default_namespace_path, - ) - .await + 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( + self.inner.clone(), + &request.query, + request.parameters, + &request.default_namespace_path, + ) + .await?; + match 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)))) + } + Submission::Deferred(poll_info) => { + let query = Arc::new(RemoteQuery::new( + query_id, + self.inner.clone(), + request.default_namespace_path, + poll_info, + )?); + self.queries + .insert(query_id, RegisteredQuery::Polled(query.clone())); + Ok(Query::new(Arc::new(RemoteQueryHandle::new(query)))) + } } - None => { - self.submit(&request.query, &request.default_namespace_path) - .await - } - } + }) + .await } + #[cfg(test)] pub(super) async fn submit( &self, query: &str, @@ -235,69 +264,36 @@ impl SqlClient { .await } - pub(super) fn submit_as_job( + pub(super) async fn submit_as_job( &self, statement: String, namespace: Vec, finish: F, - ) -> Job + ) -> Result> where T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static, F: FnOnce() -> Fut + Send + 'static, Fut: Future> + Send + 'static, { - let client = self.clone(); - let (query_tx, query_rx) = watch::channel(None::>); + let query = Arc::new( + self.execute(ExecuteQueryRequest { + query: statement, + default_namespace_path: namespace, + parameters: None, + }) + .await?, + ); + let query_id = query.id(); + let execution = query.clone(); let task = tokio::spawn(async move { - let query = Arc::new(client.submit(&statement, &namespace).await?); - query_tx.send_replace(Some(query.clone())); - let mut reader = query.reader().await?; + let mut reader = execution.reader().await?; while reader.try_next().await?.is_some() {} finish().await }); - Job::spawned_with_cancellation(task, move || { - let mut query_rx = query_rx.clone(); - async move { - loop { - let query = query_rx.borrow().clone(); - if let Some(query) = query { - return query.cancel().await; - } - if query_rx.changed().await.is_err() { - pending::<()>().await; - } - } - } - }) - } - - /// Values cannot ride on a poll, so a statement that has them is sent on - /// its own exchange instead. - pub(super) async fn submit_with_parameters( - &self, - query: &str, - parameters: RecordBatch, - default_namespace_path: &[String], - ) -> Result { - let timeout = self.inner.overall_timeout()?; - with_overall_timeout(timeout, "SQL query submission", async { - validate_namespace_path(default_namespace_path)?; - let query_id = Uuid::now_v7(); - let query = Arc::new( - ExchangeQuery::open( - query_id, - self.inner.clone(), - query, - parameters, - default_namespace_path, - ) - .await?, - ); - self.queries - .insert(query_id, RegisteredQuery::Exchanged(query.clone())); - Ok(Query::new(Arc::new(ExchangeQueryHandle::new(query)))) - }) - .await + Ok(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 { @@ -325,6 +321,7 @@ impl SqlClientInner { ) } + #[cfg(test)] async fn poll( &self, descriptor: FlightDescriptor, @@ -586,14 +583,14 @@ impl SqlClientInner { #[derive(Clone)] enum RegisteredQuery { Polled(Arc), - Exchanged(Arc), + Streamed(Arc), } impl RegisteredQuery { fn touch(&self) { match self { Self::Polled(query) => query.touch(), - Self::Exchanged(query) => query.touch(), + Self::Streamed(query) => query.touch(), } } @@ -602,14 +599,14 @@ impl RegisteredQuery { fn registry_expired(&self) -> bool { match self { Self::Polled(query) => query.registry_expired(Arc::strong_count(query) == 1), - Self::Exchanged(query) => query.registry_expired(Arc::strong_count(query) == 1), + Self::Streamed(query) => query.registry_expired(Arc::strong_count(query) == 1), } } async fn describe(&self) -> Result { match self { Self::Polled(query) => query.describe().await, - Self::Exchanged(query) => query.describe(), + Self::Streamed(query) => query.describe(), } } } @@ -1438,7 +1435,18 @@ async fn connect_channel( tokio::time::timeout(connect_timeout, endpoint.connect()) .await .map_err(|_| sql_error(request_id, "SQL connection timed out"))? - .map_err(|err| sql_error(request_id, err)) + .map_err(|err| { + // tonic's Display only says "transport error"; preserve the source chain + // so callers can distinguish DNS, refused connections, and TLS failures. + let mut message = err.to_string(); + let mut source = std::error::Error::source(&err); + while let Some(error) = source { + message.push_str(": "); + message.push_str(&error.to_string()); + source = error.source(); + } + sql_error(request_id, message) + }) } fn tls_config(config: Option<&TlsConfig>) -> Result { diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs new file mode 100644 index 000000000..46c0a7bd2 --- /dev/null +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use arrow_array::{Array, RecordBatch, StringArray}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use futures::TryStreamExt; + +use super::SqlClient; +use crate::database::ExecuteQueryRequest; +use crate::error::{Error, Result}; +use crate::listing::{ListingOptions, ListingPage}; +use crate::materialized_view::{MaterializedViewDefinition, MaterializedViewInfo}; +use crate::utils::{validate_namespace, validate_table_name}; + +pub(in crate::remote) fn quote_identifier(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +fn strings(batch: &RecordBatch, name: &str) -> Result> { + let values = batch + .column_by_name(name) + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(|| Error::Runtime { + message: format!("materialized-view SQL result is missing UTF-8 column '{name}'"), + })?; + if values.null_count() != 0 { + return Err(Error::Runtime { + message: format!("materialized-view SQL result contains null '{name}'"), + }); + } + Ok(values + .iter() + .map(|value| value.unwrap().to_owned()) + .collect()) +} + +impl SqlClient { + pub(in crate::remote) async fn describe_materialized_view( + &self, + name: &str, + namespace: &[String], + ) -> Result { + validate_table_name(name)?; + validate_namespace(namespace)?; + let query = self + .execute(ExecuteQueryRequest { + query: format!("DESCRIBE MATERIALIZED VIEW {}", quote_identifier(name)), + default_namespace_path: namespace.to_vec(), + parameters: None, + }) + .await?; + let mut reader = query.reader().await?; + let mut definitions = Vec::new(); + while let Some(batch) = reader.try_next().await? { + definitions.extend(strings(&batch, "query")?); + } + let [definition_sql] = + <[String; 1]>::try_from(definitions).map_err(|_| Error::Runtime { + message: "DESCRIBE MATERIALIZED VIEW must return exactly one definition".into(), + })?; + let parsed_definition = MaterializedViewDefinition::from_sql(&definition_sql).ok(); + Ok(MaterializedViewInfo { + definition_sql, + parsed_definition, + }) + } + + pub(in crate::remote) async fn list_materialized_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 materialized-view page token for this database or namespace".into(), + }; + let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { + let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; + let (database, prefix, path, last): (String, Option, Vec, String) = + serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; + if database != self.inner.database + || prefix != self.inner.database_prefix + || path != namespace + { + return Err(invalid_token()); + } + format!(" WHERE name > '{}'", last.replace('\'', "''")) + } else { + String::new() + }; + let query = self + .execute(ExecuteQueryRequest { + query: format!( + "SHOW MATERIALIZED VIEWS{after} LIMIT {}", + u64::from(limit) + 1 + ), + default_namespace_path: namespace.to_vec(), + parameters: None, + }) + .await?; + let mut reader = query.reader().await?; + let mut items = Vec::new(); + while let Some(batch) = reader.try_next().await? { + items.extend(strings(&batch, "name")?); + } + let page_token = if items.len() > limit as usize { + items.truncate(limit as usize); + let cursor = serde_json::to_vec(&( + &self.inner.database, + &self.inner.database_prefix, + namespace, + items.last().unwrap(), + )) + .map_err(|error| Error::Runtime { + message: error.to_string(), + })?; + Some(URL_SAFE_NO_PAD.encode(cursor)) + } else { + None + }; + Ok(ListingPage { items, page_token }) + } +} diff --git a/rust/lancedb/src/remote/sql/exchange.rs b/rust/lancedb/src/remote/sql/stream.rs similarity index 69% rename from rust/lancedb/src/remote/sql/exchange.rs rename to rust/lancedb/src/remote/sql/stream.rs index 523aaf5d7..ed85c6c92 100644 --- a/rust/lancedb/src/remote/sql/exchange.rs +++ b/rust/lancedb/src/remote/sql/stream.rs @@ -1,26 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! SQL statements sent with parameters. -//! -//! A statement without parameters is polled: `PollFlightInfo` starts it -//! detached from the connection and `DoGet` reads its endpoints. Neither call -//! carries Arrow data, so a statement's values would have to be spelled into -//! its text. A statement with parameters is sent on one `DoExchange` instead: -//! the command and the parameter schema, then one row, and the result rows -//! come back on the same call. The call is the statement's lifetime, so -//! cancelling it -- or dropping the handle before reading -- stops the -//! statement on the server. +//! SQL submitted on one call, with either streamed rows or a polling handoff. use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex as StdMutex, OnceLock}; use std::time::Instant; use arrow_array::RecordBatch; -use arrow_flight::FlightDescriptor; +use arrow_flight::decode::FlightRecordBatchStream; use arrow_flight::encode::FlightDataEncoderBuilder; -use arrow_flight::sql::{CommandStatementQuery, ProstMessageExt}; +use arrow_flight::sql::{Any, CommandStatementQuery, ProstMessageExt}; +use arrow_flight::{FlightDescriptor, PollInfo, Ticket}; use arrow_schema::SchemaRef; +use futures::TryStreamExt; use prost::Message; use tokio::sync::{Notify, mpsc}; use uuid::Uuid; @@ -51,8 +44,8 @@ fn failure(error: &Error) -> Lifecycle { }) } -/// A statement running on its own `DoExchange` call. -pub(super) struct ExchangeQuery { +/// A statement streaming on its initial `DoGet` or `DoExchange` call. +pub(super) struct StreamingQuery { id: Uuid, client: Arc, /// The call's rows, until a reader takes them or a cancellation drops them. @@ -63,7 +56,7 @@ pub(super) struct ExchangeQuery { last_accessed: StdMutex, } -struct PreparedExchange { +struct PreparedStream { schema: SchemaRef, first: Option, rest: Option, @@ -76,7 +69,7 @@ struct PreparedExchange { /// this one did. A query cancelled meanwhile has its rows dropped instead, /// which ends the call. struct Borrowed<'a> { - query: &'a ExchangeQuery, + query: &'a StreamingQuery, rows: Option, } @@ -104,18 +97,37 @@ impl Drop for Borrowed<'_> { } } -impl ExchangeQuery { - /// Send the statement and its parameters, returning once the server has - /// planned it: a statement it refuses is refused here, as a polled one is - /// on its first poll. +pub(super) const PROTOCOL_HEADER: &str = "lancedb-sql-protocol"; +pub(super) const PROTOCOL_VERSION: &str = "adaptive-v1"; +const RESPONSE_TYPE_URL: &str = "type.googleapis.com/lancedb.sql.QueryResponse"; + +#[derive(Clone, PartialEq, Message)] +pub(super) struct QueryResponse { + #[prost(message, optional, tag = "1")] + pub poll_info: Option, +} + +#[derive(Clone, PartialEq, Message)] +struct CommandTicket { + #[prost(bytes = "vec", tag = "2")] + command: Vec, +} + +pub(super) enum Submission { + Stream(ResultEndpointStream), + Deferred(PollInfo), +} + +impl StreamingQuery { pub(super) async fn open( - id: Uuid, client: Arc, query: &str, - parameters: RecordBatch, + parameters: Option, default_namespace_path: &[String], - ) -> Result { - if parameters.num_rows() != 1 { + ) -> Result { + if let Some(parameters) = ¶meters + && parameters.num_rows() != 1 + { return Err(Error::InvalidInput { message: format!( "SQL query parameters must be exactly one row, got {}", @@ -130,39 +142,102 @@ impl ExchangeQuery { Some(DEFAULT_READ_TIMEOUT), )? .unwrap(); - let descriptor = FlightDescriptor::new_cmd( - CommandStatementQuery { - query: query.to_string(), - transaction_id: None, + let command = CommandStatementQuery { + query: query.to_string(), + transaction_id: None, + } + .as_any() + .encode_to_vec(); + let connection = client.connection(&request_id).await?; + let headers = client.headers(default_namespace_path, &request_id).await?; + let mut metadata = super::client_with_headers(connection.client.clone(), &headers)? + .metadata() + .clone(); + metadata.insert(PROTOCOL_HEADER, PROTOCOL_VERSION.parse().unwrap()); + let mut flight = connection.client.clone(); + let response = if let Some(parameters) = parameters { + let messages = FlightDataEncoderBuilder::new() + .with_flight_descriptor(Some(FlightDescriptor::new_cmd(command))) + .with_schema(parameters.schema()) + .build(futures::stream::iter([Ok(parameters)])) + .try_collect::>() + .await + .map_err(|error| sql_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 + } else { + let mut request = + tonic::Request::new(Ticket::new(CommandTicket { command }.encode_to_vec())); + *request.metadata_mut() = metadata; + 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))?; + let negotiated = response + .metadata() + .get(PROTOCOL_HEADER) + .is_some_and(|value| value == PROTOCOL_VERSION); + let mut response_stream = response.into_inner(); + if negotiated { + 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))? + .ok_or_else(|| { + sql_error(&request_id, "SQL response omitted its execution decision") + })?; + if !first.data_header.is_empty() || !first.data_body.is_empty() { + return Err(sql_error( + &request_id, + "SQL response sent rows before its execution decision", + )); } - .as_any() - .encode_to_vec(), + let envelope = + Any::decode(first.app_metadata).map_err(|error| sql_error(&request_id, error))?; + if envelope.type_url != RESPONSE_TYPE_URL { + return Err(sql_error( + &request_id, + "SQL response returned an unknown execution decision", + )); + } + let decision = QueryResponse::decode(envelope.value) + .map_err(|error| sql_error(&request_id, error))?; + if let Some(info) = decision.poll_info { + if info.info.is_none() && info.flight_descriptor.is_none() { + return Err(sql_error( + &request_id, + "SQL handoff omitted result and continuation information", + )); + } + return Ok(Submission::Deferred(info)); + } + } + let stream = FlightRecordBatchStream::new_from_flight_data( + response_stream + .map_err(|status| arrow_flight::error::FlightError::Tonic(Box::new(status))), ); - // The descriptor rides on the schema message, and the row follows it. - let request = FlightDataEncoderBuilder::new() - .with_flight_descriptor(Some(descriptor)) - .with_schema(parameters.schema()) - .build(futures::stream::iter([Ok(parameters)])); - let mut flight = client - .client_with_headers(default_namespace_path, &request_id) - .await?; - let stream = tokio::time::timeout(read_timeout, flight.do_exchange(request)) - .await - .map_err(|_| sql_error(&request_id, "SQL query submission timed out"))? - .map_err(|err| sql_error(&request_id, err))?; - Ok(Self { + Ok(Submission::Stream(ResultEndpointStream { + stream, + request_id, + read_timeout, + })) + } + + pub(super) fn new( + id: Uuid, + client: Arc, + response: ResultEndpointStream, + ) -> Self { + Self { id, client, - response: StdMutex::new(Some(ResultEndpointStream { - stream, - request_id, - read_timeout, - })), + response: StdMutex::new(Some(response)), lifecycle: StdMutex::new(Lifecycle::Running), cancelled: Notify::new(), terminal_at: OnceLock::new(), last_accessed: StdMutex::new(Instant::now()), - }) + } } pub(super) fn touch(&self) { @@ -242,7 +317,7 @@ impl ExchangeQuery { } /// Take the rows and wait for the first batch, which carries the schema. - async fn prepare(&self) -> Result { + async fn prepare(&self) -> Result { let Some(rows) = self.response.lock().unwrap().take() else { // Taken by an earlier attempt that failed, or dropped by a cancel. return Err(match &*self.lifecycle.lock().unwrap() { @@ -275,7 +350,7 @@ impl ExchangeQuery { if first.is_none() { self.settle(Lifecycle::Finished); } - Ok(PreparedExchange { + Ok(PreparedStream { schema, rest: first.is_some().then_some(rows), first, @@ -284,7 +359,7 @@ impl ExchangeQuery { async fn run( self: Arc, - mut prepared: PreparedExchange, + mut prepared: PreparedStream, sender: mpsc::Sender>, ) -> Result<()> { if let Some(batch) = prepared.first.take() @@ -343,13 +418,13 @@ impl ExchangeQuery { } } -pub(super) struct ExchangeQueryHandle { - query: Arc, +pub(super) struct StreamingQueryHandle { + query: Arc, result_started: AtomicBool, } -impl ExchangeQueryHandle { - pub(super) fn new(query: Arc) -> Self { +impl StreamingQueryHandle { + pub(super) fn new(query: Arc) -> Self { Self { query, result_started: AtomicBool::new(false), @@ -357,7 +432,7 @@ impl ExchangeQueryHandle { } } -impl Drop for ExchangeQueryHandle { +impl Drop for StreamingQueryHandle { // Rows nobody took are rows nobody will read. Keeping the call open would // hold the statement running on the server, stalled on flow control, // until the registry forgot it. @@ -369,7 +444,7 @@ impl Drop for ExchangeQueryHandle { } #[async_trait::async_trait] -impl QueryHandle for ExchangeQueryHandle { +impl QueryHandle for StreamingQueryHandle { fn id(&self) -> Uuid { self.query.touch(); self.query.id diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 79ca339db..6a0421fa6 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -19,8 +19,10 @@ use futures::{StreamExt, TryStreamExt}; use tonic::metadata::MetadataMap; use tonic::{Request, Response, Status, Streaming}; +use super::stream::{PROTOCOL_HEADER, PROTOCOL_VERSION, QueryResponse}; use super::*; use crate::database::Database; +use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::RemoteCatalogOptions; use crate::remote::client::HeaderProvider; use crate::remote::client::test_utils::client_with_handler; @@ -70,7 +72,11 @@ type ReceivedExchanges = Arc)> #[derive(Clone)] struct TestSqlService { + adaptive: bool, + defer: bool, + invalid_decision: bool, query_count: Arc, + statements: Arc>>, do_get_count: Arc, cancel_count: Arc, cancel_denied_count: Arc, @@ -120,6 +126,51 @@ impl TestSqlService { .unwrap_or_default(), }); } + fn adaptive_response( + &self, + query: &str, + rows: BoxStream<'static, std::result::Result>, + ) -> Response>> { + 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())), + )), + 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() + } else { + Any { + type_url: "type.googleapis.com/lancedb.sql.QueryResponse".to_string(), + value: QueryResponse { poll_info }.encode_to_vec().into(), + } + .encode_to_vec() + .into() + }, + ..Default::default() + }; + let rest = if self.defer { + futures::stream::empty().boxed() + } else { + rows + }; + let mut response = Response::new( + futures::stream::once(async { Ok(first) }) + .chain(rest) + .boxed(), + ); + response + .metadata_mut() + .insert(PROTOCOL_HEADER, PROTOCOL_VERSION.parse().unwrap()); + response + } } impl Default for TestSqlService { @@ -154,7 +205,11 @@ impl Default for TestSqlService { let dictionary_result = RecordBatch::try_new(dictionary_schema, vec![Arc::new(dictionary)]).unwrap(); Self { + adaptive: false, + defer: false, + invalid_decision: false, query_count: Arc::new(AtomicUsize::new(0)), + statements: Arc::new(std::sync::Mutex::new(Vec::new())), do_get_count: Arc::new(AtomicUsize::new(0)), cancel_count: Arc::new(AtomicUsize::new(0)), cancel_denied_count: Arc::new(AtomicUsize::new(0)), @@ -217,6 +272,7 @@ impl FlightService for TestSqlService { .and_then(|any| any.unpack::().ok().flatten()); let (query, stage) = if let Some(command) = command { self.query_count.fetch_add(1, Ordering::SeqCst); + self.statements.lock().unwrap().push(command.query.clone()); (command.query, 0_u8) } else { let continuation = std::str::from_utf8(request.get_ref().cmd.as_ref()) @@ -237,6 +293,9 @@ impl FlightService for TestSqlService { .ok_or_else(|| Status::invalid_argument("invalid continuation"))?; (query.to_string(), stage) }; + if query == "SELECT rejected" { + return Err(Status::invalid_argument("invalid statement")); + } if (query == "SELECT slow" || query == "SELECT cancelling") && stage > 0 { tokio::time::sleep(Duration::from_millis(250)).await; } @@ -308,8 +367,28 @@ impl FlightService for TestSqlService { request: Request, ) -> std::result::Result::DoGetStream>, Status> { self.do_get_count.fetch_add(1, Ordering::SeqCst); - let ticket = request.get_ref().ticket.as_ref(); - let gate_refresh = ticket == b"REFRESH MATERIALIZED VIEW \"cancel_view\""; + let initial = Any::decode(request.get_ref().ticket.clone()) + .ok() + .and_then(|envelope| Any::decode(envelope.value).ok()) + .and_then(|command| command.unpack::().ok().flatten()); + if let Some(command) = &initial { + self.statements.lock().unwrap().push(command.query.clone()); + if command.query == "SELECT rejected" { + return Err(Status::invalid_argument("invalid statement")); + } + self.capture_headers(request.metadata()); + assert_eq!( + request.metadata().get(PROTOCOL_HEADER).unwrap(), + PROTOCOL_VERSION + ); + } + let query = initial + .as_ref() + .map(|command| command.query.as_bytes()) + .unwrap_or(request.get_ref().ticket.as_ref()); + let ticket = query; + let gate_refresh = ticket == b"REFRESH MATERIALIZED VIEW \"cancel_view\"" + || ticket == b"SELECT job cancel denied"; let empty = ticket == b"SELECT empty"; let slow = ticket == b"SELECT slow get"; let large = ticket == b"SELECT large message"; @@ -337,7 +416,11 @@ impl FlightService for TestSqlService { encoder = encoder.with_max_flight_data_size(8 * 1024 * 1024); } let stream = encoder.build(input).map_err(Status::from); - Ok(Response::new(Box::pin(stream))) + if let Some(initial) = initial { + Ok(self.adaptive_response(&initial.query, stream.boxed())) + } else { + Ok(Response::new(stream.boxed())) + } } async fn do_put( @@ -387,7 +470,9 @@ impl FlightService for TestSqlService { { return Err(Status::not_found("query cancellation completed")); } - let status = if query == "SELECT cancel unspecified" { + let status = if query == "SELECT job cancel denied" { + CancelStatus::NotCancellable + } else if query == "SELECT cancel unspecified" { CancelStatus::Unspecified } else if query == "SELECT cancelling" { if self @@ -486,7 +571,7 @@ impl FlightService for TestSqlService { let _dropped = &dropped; message }); - Ok(Response::new(Box::pin(stream))) + Ok(self.adaptive_response(&query, stream.boxed())) } } @@ -810,14 +895,156 @@ async fn catalog_connections_use_explicit_sql_endpoint_and_database_scope() { } #[tokio::test] -async fn remote_refresh_twice_keeps_latest_selector() { +async fn remote_create_uses_sql_and_preserves_options_and_namespace() { + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let count = service.query_count.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("CREATE must use SQL, not REST: {}", request.url().path()); + }) + .with_sql_client(sql_client.clone()); + for (enabled, interval, expected) in [ + (None, None, ""), + (Some(true), None, " WITH (auto_refresh_enabled = true)"), + ( + Some(false), + Some(0.5), + " WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 0.5)", + ), + ] { + 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: enabled, + auto_refresh_interval_seconds: interval, + }) + .await + .unwrap(); + assert_eq!(job.job_type().as_deref(), Some("query")); + let query_id = + Uuid::parse_str(job.id().expect("SQL-backed job must expose its ID")).unwrap(); + job.wait().await.unwrap(); + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + assert!(job.events(Default::default()).await.is_err()); + assert_eq!(job.job_type().as_deref(), Some("query")); + assert_eq!( + sql_client.describe(query_id).await.unwrap().status, + QueryStatus::Finished + ); + assert_eq!( + statements.lock().unwrap().last().unwrap(), + &format!("CREATE MATERIALIZED VIEW \"adults\"{expected} AS SELECT * FROM people") + ); + } + assert_eq!(count.load(Ordering::SeqCst), 0); + assert_eq!(statements.lock().unwrap().len(), 3); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team$reports") + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn query_backed_jobs_propagate_submission_and_execution_failures() { + let (client, shutdown) = start_sql_service( + TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }, + ClientConfig::default(), + ) + .await; + let rejected = client + .submit_as_job("SELECT rejected".into(), vec![], || async { Ok(()) }) + .await; + assert!(rejected.is_err()); + let finished = Arc::new(AtomicBool::new(false)); + let callback_finished = finished.clone(); + let job = client + .submit_as_job("SELECT fail".into(), vec![], move || async move { + callback_finished.store(true, Ordering::SeqCst); + Ok(()) + }) + .await + .unwrap(); + assert!(matches!(job.wait().await, Err(Error::JobFailed { .. }))); + assert!(matches!(job.wait().await, Err(Error::JobFailed { .. }))); + assert_eq!(job.status().await.unwrap(), "failed"); + assert!(!finished.load(Ordering::SeqCst)); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn rejected_job_cancellation_does_not_abort_sql_completion() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; + let do_get_count = service.do_get_count.clone(); + let release = service.gate_refresh_release.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let job = client + .submit_as_job("SELECT job cancel denied".into(), vec![], || async { + Ok(()) + }) + .await + .unwrap(); + wait_for(&do_get_count, 1, "job did not begin reading its SQL result").await; + assert!(matches!( + job.cancel().await, + Err(Error::NotSupported { .. }) + )); + assert_eq!(job.status().await.unwrap(), "running"); + release.notify_one(); + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + job.cancel().await.unwrap(); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let incoming = futures::stream::try_unfold(listener, |listener| async { let (socket, _) = listener.accept().await?; Ok::<_, std::io::Error>(Some((socket, listener))) }); - let service = TestSqlService::default(); + let result = RecordBatch::try_from_iter(vec![ + ( + "name", + Arc::new(StringArray::from(vec!["view"])) as ArrayRef, + ), + ( + "query", + Arc::new(StringArray::from(vec!["SELECT * FROM source"])) as ArrayRef, + ), + ]) + .unwrap(); + let service = TestSqlService { + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); let server = tokio::spawn( tonic::transport::Server::builder() @@ -841,11 +1068,10 @@ async fn remote_refresh_twice_keeps_latest_selector() { .body() .and_then(reqwest::Body::as_bytes) .and_then(|bytes| serde_json::from_slice::(bytes).ok()) - .unwrap(); + .unwrap_or_default(); captured.lock().unwrap().push(body["version"].clone()); let text = match request.url().path() { "/v1/table/ns$view/describe/" => r#"{"version": 42, "schema": {"fields": []}}"#, - "/v1/table/ns$view/count_rows/" => "2", other => panic!("unexpected REST request: {other}"), }; http::Response::builder() @@ -861,24 +1087,55 @@ async fn remote_refresh_twice_keeps_latest_selector() { Default::default(), Some(sql_client), ); + let database = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected database request: {}", request.url()); + }); + let view = + crate::MaterializedView::from_table(crate::Table::new(Arc::new(table), Arc::new(database))) + .await + .unwrap(); - let first = table - .refresh_materialized_view_async(None) - .await - .unwrap() - .wait() - .await - .unwrap(); - let second = table - .refresh_materialized_view_async(None) + let first = view.refresh().execute().await.unwrap(); + let second = view + .refresh() + .full(true) + .execute_async() .await .unwrap() .wait() .await .unwrap(); - assert_eq!(first.version, 42); - assert_eq!(second.version, 42); + for result in [first, second] { + assert_eq!(result.mode, None); + assert_eq!(result.rows_written, None); + assert_eq!(result.source_version, None); + assert_eq!(result.version, 42); + // Query-backed jobs serialize their typed result before returning it. + let json = serde_json::to_value(result).unwrap(); + assert!(json["mode"].is_null()); + assert!(json["rows_written"].is_null()); + assert!(json["source_version"].is_null()); + } + assert!(matches!( + view.refresh().source_version(7).execute_async().await, + Err(Error::NotSupported { .. }) + )); + assert_eq!( + *statements.lock().unwrap(), + [ + "DESCRIBE MATERIALIZED VIEW \"view\"", + "REFRESH MATERIALIZED VIEW \"view\"", + "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true)", + ] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "ns") + ); assert!( selectors .lock() @@ -898,7 +1155,11 @@ async fn cancelling_remote_refresh_cancels_sql_query() { let (socket, _) = listener.accept().await?; Ok::<_, std::io::Error>(Some((socket, listener))) }); - let service = TestSqlService::default(); + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; let cancel_count = service.cancel_count.clone(); let do_get_count = service.do_get_count.clone(); let gate_refresh_release = service.gate_refresh_release.clone(); @@ -932,7 +1193,10 @@ async fn cancelling_remote_refresh_cancels_sql_query() { Default::default(), Some(sql_client), ); - let job = table.refresh_materialized_view_async(None).await.unwrap(); + let job = table + .refresh_materialized_view_async(None, false) + .await + .unwrap(); tokio::time::timeout(Duration::from_secs(10), async { while do_get_count.load(Ordering::SeqCst) == 0 { tokio::task::yield_now().await; @@ -1609,3 +1873,286 @@ fn validates_metadata_with_header_map() { assert!(insert_header(&mut headers, "bad header", "value").is_err()); assert!(insert_header(&mut headers, "valid-header", "bad\nvalue").is_err()); } + +#[tokio::test] +async fn adaptive_streams_start_on_one_rpc_for_both_inputs() { + for parameters in [None, Some(parameter_row())] { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let polls = service.query_count.clone(); + let gets = service.do_get_count.clone(); + let exchanges = service.exchanges.clone(); + let expected = parameters.clone().unwrap_or_else(|| service.result.clone()); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let with_parameters = parameters.is_some(); + let query = client + .execute(ExecuteQueryRequest { + parameters, + ..ExecuteQueryRequest::new("SELECT echo") + }) + .await + .unwrap(); + assert_eq!(query.describe().await.unwrap().status, QueryStatus::Running); + assert_eq!(collect_result(&query).await.unwrap(), vec![expected]); + assert_eq!( + query.describe().await.unwrap().status, + QueryStatus::Finished + ); + assert!(query.reader().await.is_err()); + assert_eq!(polls.load(Ordering::SeqCst), 0); + assert_eq!(gets.load(Ordering::SeqCst), usize::from(!with_parameters)); + assert_eq!( + exchanges.lock().unwrap().len(), + usize::from(with_parameters) + ); + } +} + +#[tokio::test] +async fn adaptive_handoffs_share_polling_and_survive_handle_drop() { + for parameters in [None, Some(parameter_row())] { + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; + let polls = service.query_count.clone(); + let gets = service.do_get_count.clone(); + let exchanges = service.exchanges.clone(); + let expected = service.result.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let with_parameters = parameters.is_some(); + let query = client + .execute(ExecuteQueryRequest { + parameters, + ..ExecuteQueryRequest::new("SELECT adaptive") + }) + .await + .unwrap(); + let id = query.id(); + assert_eq!(collect_result(&query).await.unwrap(), vec![expected]); + assert_eq!( + query.describe().await.unwrap().status, + QueryStatus::Finished + ); + assert!(query.reader().await.is_err()); + drop(query); + assert_eq!( + client.describe(id).await.unwrap().status, + QueryStatus::Finished + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 0, + "the original SQL must not be resubmitted through polling" + ); + assert_eq!( + gets.load(Ordering::SeqCst), + 1 + usize::from(!with_parameters) + ); + assert_eq!( + exchanges.lock().unwrap().len(), + usize::from(with_parameters) + ); + } +} + +#[tokio::test] +async fn adaptive_handoffs_use_server_cancellation_for_both_inputs() { + for parameters in [None, Some(parameter_row())] { + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; + let cancels = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let query = client + .execute(ExecuteQueryRequest { + parameters, + ..ExecuteQueryRequest::new("SELECT cancel") + }) + .await + .unwrap(); + query.cancel().await.unwrap(); + assert_eq!(cancels.load(Ordering::SeqCst), 1); + assert_eq!( + query.describe().await.unwrap().status, + QueryStatus::Cancelled + ); + assert!(query.reader().await.is_err()); + } +} + +#[tokio::test] +async fn malformed_adaptive_decision_never_resubmits_the_statement() { + for parameters in [None, Some(parameter_row())] { + let service = TestSqlService { + adaptive: true, + invalid_decision: true, + ..Default::default() + }; + let polls = service.query_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + assert!( + client + .execute(ExecuteQueryRequest { + parameters, + ..ExecuteQueryRequest::new("SELECT invalid") + }) + .await + .is_err() + ); + assert_eq!(polls.load(Ordering::SeqCst), 0); + } +} + +#[tokio::test] +async fn remote_drop_materialized_view_uses_a_query_job() { + for defer in [false, true] { + let service = TestSqlService { + 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 db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }) + .with_sql_client(client.clone()); + let job = db + .drop_materialized_view_async("daily_sales", &["team".into(), "reports".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(), + ["DROP MATERIALIZED VIEW \"daily_sales\""] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team$reports") + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { + for defer in [false, true] { + let result = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringArray::from(vec!["a", "b'c", "z"])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }) + .with_sql_client(client); + let namespace = vec!["team".to_owned(), "reports".to_owned()]; + let first = db + .list_materialized_views( + &namespace, + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!(first.items, ["a", "b'c"]); + let token = first.page_token.unwrap(); + db.list_materialized_views( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(&token), + ) + .await + .unwrap(); + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW MATERIALIZED VIEWS LIMIT 3", + "SHOW MATERIALIZED VIEWS WHERE name > 'b''c' LIMIT 3" + ] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team$reports") + ); + for (path, token) in [(vec![], token), (namespace, "invalid".into())] { + assert!(matches!( + db.list_materialized_views( + &path, + crate::listing::ListingOptions::default().page_token(token) + ) + .await, + Err(Error::InvalidInput { .. }) + )); + } + assert_eq!(statements.lock().unwrap().len(), 2); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_describe_materialized_view_preserves_the_sql_definition() { + for defer in [false, true] { + let definition = "SELECT s.x, d.label FROM source s JOIN dim d ON s.id = d.id"; + let result = RecordBatch::try_from_iter(vec![( + "query", + Arc::new(StringArray::from(vec![definition])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }), + "daily_sales".into(), + vec!["analytics".into()], + "analytics$daily_sales".into(), + Default::default(), + Some(client), + ); + let info = table.materialized_view_info().await.unwrap(); + assert_eq!(info.definition_sql, definition); + assert!(info.parsed_definition.is_none()); + assert_eq!( + *statements.lock().unwrap(), + ["DESCRIBE MATERIALIZED VIEW \"daily_sales\""] + ); + shutdown.send(()).unwrap(); + } +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index ce929249b..d997b64db 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -16,11 +16,9 @@ use crate::expr::expr_to_sql_string; use crate::index::Index; use crate::index::IndexStatistics; use crate::index::scalar::FtsQuery; -use crate::index::waiter::wait_for_index; +use crate::index::waiter::{MAX_WAIT, wait_for_index}; use crate::job::Job; -use crate::materialized_view::{ - MaterializedViewDefinition, MaterializedViewInfo, RefreshMaterializedViewResult, -}; +use crate::materialized_view::{MaterializedViewInfo, RefreshMaterializedViewResult}; use crate::query::wal_fusion::PkFusionMemory; // WAL-PK-FUSION: delete. use crate::query::{QueryFilter, QueryRequest, Select, VectorQueryRequest}; use crate::remote::job::RemoteJob; @@ -546,7 +544,7 @@ impl RemoteTable { ) && !self.server_version.support_fts_document_granularity() { return Err(Error::NotSupported { - message: "FTS document granularity requires remote server version 0.6.0 or later" + message: "FTS document granularity requires LanceDB Enterprise server version 0.6.0 or later" .into(), }); } @@ -571,7 +569,7 @@ impl RemoteTable { // Warn if train=false is specified since it's not meaningful if !index.train { log::warn!( - "train=false has no effect remote tables. The index will be created empty and automatically populated in the background." + "train=false has no effect in LanceDB Distributed. The index will be created empty and automatically populated in the background." ); } @@ -625,7 +623,7 @@ impl RemoteTable { } Index::IvfHnswPq(_) => { return Err(Error::NotSupported { - message: "IVF_HNSW_PQ is not supported for remote tables. Please use IVF_HNSW_SQ instead.".into(), + message: "IVF_HNSW_PQ is not supported in LanceDB Distributed. Please use IVF_HNSW_SQ instead.".into(), }); } }; @@ -650,13 +648,42 @@ impl RemoteTable { .and_then(|body| extract_job_id(&body)); if let Some(wait_timeout) = index.wait_timeout { - let index_name = index.name.unwrap_or_else(|| format!("{}_idx", column)); - self.wait_for_index(&[&index_name], wait_timeout).await?; + if let Some(job_id) = &job_id { + if wait_timeout > MAX_WAIT { + return Err(Error::InvalidInput { + message: format!("timeout must be less than {:?}", MAX_WAIT), + }); + } + // An older same-named index may still be ready while its + // replacement is building. Wait for this submission instead. + tokio::time::timeout(wait_timeout, self.index_job(job_id.clone()).wait()) + .await + .map_err(|_| Error::Timeout { + message: format!( + "timed out waiting for index job {:?} after {:?}", + job_id, wait_timeout + ), + })??; + } else { + // Older servers do not return a job ID. + let index_name = index.name.unwrap_or_else(|| format!("{}_idx", column)); + self.wait_for_index(&[&index_name], wait_timeout).await?; + } } Ok(job_id) } + fn index_job(&self, job_id: String) -> Job { + Job::new(Box::new(FreshnessJob { + inner: RemoteJob::new(self.client.clone(), job_id), + freshness: self.freshness.clone(), + version: self.version.clone(), + tracked_result: TrackedJobResult::None, + freshness_request: self.snapshot_freshness_headers(), + })) + } + pub(super) fn new_with_sql_client( client: RestfulLanceDbClient, name: String, @@ -1040,7 +1067,7 @@ impl RemoteTable { QueryFilter::Datafusion(expr) => expr_to_sql_string(expr)?, QueryFilter::Substrait(_) => { return Err(Error::NotSupported { - message: "Substrait filters are not supported for remote queries" + message: "Substrait filters are not supported in LanceDB Distributed" .to_string(), }); } @@ -1090,7 +1117,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 for remote tables.".into(), + message: "Wand factor is not supported in LanceDB Distributed.".into(), }); } @@ -1101,7 +1128,7 @@ impl RemoteTable { { return Err(Error::NotSupported { message: - "FTS document granularity requires remote server version 0.6.0 or later" + "FTS document granularity requires LanceDB Enterprise server version 0.6.0 or later" .into(), }); } @@ -1248,7 +1275,7 @@ impl RemoteTable { let body = response.text().await.err_to_http(request_id.clone())?; let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| Error::Http { source: format!("Failed to parse multipart create response: {}", e).into(), - request_id, + request_id: request_id.clone(), status_code: None, })?; parsed["upload_id"] @@ -1256,7 +1283,7 @@ impl RemoteTable { .map(|s| s.to_string()) .ok_or_else(|| Error::Http { source: "Missing upload_id in multipart create response".into(), - request_id: String::new(), + request_id, status_code: None, }) } @@ -1275,12 +1302,12 @@ impl RemoteTable { let body = response.text().await.err_to_http(request_id.clone())?; let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| Error::Http { source: format!("Failed to parse multipart complete response: {}", e).into(), - request_id, + request_id: request_id.clone(), status_code: None, })?; let version = parsed["version"].as_u64().ok_or_else(|| Error::Http { source: "Missing version in multipart complete response".into(), - request_id: String::new(), + request_id, status_code: None, })?; Ok(AddResult { version }) @@ -2172,29 +2199,19 @@ impl BaseTable for RemoteTable { &self.identifier } async fn materialized_view_info(&self) -> Result { - #[derive(Deserialize)] - struct DescribeMaterializedViewResponse { - query: String, - } - - let request = self.client.post(&format!( - "/v1/materialized_view/{}/describe", - self.identifier - )); - let (request_id, response) = self.send(request, true).await?; - let response = self.check_table_response(&request_id, response).await?; - let response: DescribeMaterializedViewResponse = - response.json().await.err_to_http(request_id)?; - let parsed_definition = MaterializedViewDefinition::from_sql(&response.query).ok(); - Ok(MaterializedViewInfo { - definition_sql: response.query, - parsed_definition, - }) + self.sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote table client".into(), + })? + .describe_materialized_view(&self.name, &self.namespace) + .await } async fn refresh_materialized_view_async( &self, source_version: Option, + full: bool, ) -> Result> { self.check_mutable().await?; if source_version.is_some() { @@ -2207,8 +2224,9 @@ impl BaseTable for RemoteTable { message: "SQL is unavailable for this remote table client".to_string(), })?; let statement = format!( - "REFRESH MATERIALIZED VIEW {}", - quote_sql_identifier(&self.name) + "REFRESH MATERIALIZED VIEW {}{}", + quote_sql_identifier(&self.name), + if full { " WITH (full = true)" } else { "" }, ); let namespace = self.namespace.clone(); let client = self.client.clone(); @@ -2218,8 +2236,8 @@ impl BaseTable for RemoteTable { let freshness = self.freshness.clone(); let freshness_request = self.snapshot_freshness_headers(); let job_sql_client = sql_client.clone(); - Ok( - sql_client.submit_as_job(statement, namespace.clone(), move || async move { + sql_client + .submit_as_job(statement, namespace.clone(), move || async move { let table = Self::new_with_sql_client( client, name, @@ -2230,19 +2248,17 @@ impl BaseTable for RemoteTable { ); table.checkout_latest().await?; let version = table.version().await?; - let rows_written = - u64::try_from(table.count_rows(None).await?).map_err(|_| Error::Runtime { - message: "materialized-view row count exceeds u64".to_string(), - })?; freshness_request.observe_version(&freshness, version); Ok(RefreshMaterializedViewResult { - mode: crate::materialized_view::RefreshMode::Rebuild, - rows_written, - source_version: 0, + // 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 } async fn query_snapshot(&self) -> Result> { let description = self.describe().await?; @@ -2744,7 +2760,7 @@ impl BaseTable for RemoteTable { if add.allow_external_blob_outside_bases { return Err(Error::NotSupported { - message: "allow_external_blob_outside_bases is only supported on local tables" + message: "allow_external_blob_outside_bases is only supported in LanceDB Embedded" .to_string(), }); } @@ -2898,6 +2914,10 @@ impl BaseTable for RemoteTable { self.fetch_blob_files_impl(column, row_ids).await } + async fn open_blob_file(&self, descriptor: &crate::blob::BlobDescriptor) -> Result { + self.open_blob_file_impl(descriptor).await + } + async fn explain_plan(&self, query: &AnyQuery, verbose: bool) -> Result { if let AnyQuery::Query(request) = query && let Some(offsets) = &request.take_offsets @@ -3101,13 +3121,7 @@ impl BaseTable for RemoteTable { async fn create_index_async(&self, index: IndexBuilder) -> Result { Ok(match self.submit_create_index(index).await? { - Some(job_id) => Job::new(Box::new(FreshnessJob { - inner: RemoteJob::new(self.client.clone(), job_id), - freshness: self.freshness.clone(), - version: self.version.clone(), - tracked_result: TrackedJobResult::None, - freshness_request: self.snapshot_freshness_headers(), - })), + Some(job_id) => self.index_job(job_id), None => Job::new_done(), }) } @@ -3421,7 +3435,7 @@ impl BaseTable for RemoteTable { async fn optimize(&self, _action: OptimizeAction) -> Result { self.check_mutable().await?; Err(Error::NotSupported { - message: "optimize is not supported for remote tables.".into(), + message: "optimize is not supported in LanceDB Distributed.".into(), }) } async fn add_columns( @@ -3500,7 +3514,11 @@ impl BaseTable for RemoteTable { Ok(result) } - async fn add_computed_columns(&self, columns: &[(String, String)]) -> Result { + async fn add_computed_columns( + &self, + columns: &[(String, String)], + options: crate::table::computed_columns::ComputedColumnOptions, + ) -> Result { self.check_mutable().await?; crate::table::computed_columns::ensure_not_function_bound( self.schema().await?.as_ref(), @@ -3519,7 +3537,10 @@ impl BaseTable for RemoteTable { }, ) .collect::>(); - let mut body = serde_json::json!({ "new_columns": entries }); + let mut body = serde_json::json!({ "new_columns": entries, "auto_refresh_enabled": options.auto_refresh_enabled }); + if let Some(interval) = options.auto_refresh_interval_seconds { + body["auto_refresh_interval_seconds"] = serde_json::json!(interval); + } self.apply_branch_body(&mut body); let request = self .client @@ -3553,6 +3574,7 @@ impl BaseTable for RemoteTable { &self, application: &crate::function::FunctionApplication, output_name: Option<&str>, + options: crate::table::computed_columns::ComputedColumnOptions, ) -> Result { self.check_mutable().await?; let schema = self.schema().await?; @@ -3573,6 +3595,7 @@ impl BaseTable for RemoteTable { .collect::>(); let mut body = serde_json::json!({ "new_columns": new_columns, + "auto_refresh_enabled": options.auto_refresh_enabled, "function": { "application": plan.application, "binding_metadata_version": plan.binding_metadata_version, @@ -3582,6 +3605,9 @@ impl BaseTable for RemoteTable { "outputs": plan.outputs, }, }); + if let Some(interval) = options.auto_refresh_interval_seconds { + body["auto_refresh_interval_seconds"] = serde_json::json!(interval); + } self.apply_branch_body(&mut body); let request = self .client @@ -3704,16 +3730,25 @@ impl BaseTable for RemoteTable { value["rename"] = serde_json::Value::String(rename.clone()); } if let Some(data_type) = &alteration.data_type { - let json_data_type = JsonDataType::try_from(data_type).unwrap(); - let json_data_type = serde_json::to_value(&json_data_type).unwrap(); - value["data_type"] = json_data_type; + let json_data_type = + JsonDataType::try_from(data_type).map_err(|err| Error::InvalidInput { + message: format!( + "Cannot serialize data type for column '{}': {err}", + alteration.path + ), + })?; + value["data_type"] = serde_json::to_value(&json_data_type).map_err(|err| { + Error::InvalidInput { + message: format!("Cannot serialize column alteration: {err}"), + } + })?; } if let Some(nullable) = &alteration.nullable { value["nullable"] = serde_json::Value::Bool(*nullable); } - value + Ok(value) }) - .collect::>(); + .collect::>>()?; let mut body = serde_json::json!({ "alterations": body }); self.apply_branch_body(&mut body); let request = self @@ -4450,7 +4485,7 @@ mod tests { .unwrap_err(); assert!(matches!(err, Error::NotSupported { .. }), "got {err:?}"); - assert!(err.to_string().contains("local tables")); + assert!(err.to_string().contains("LanceDB Embedded")); } #[tokio::test] @@ -5037,6 +5072,24 @@ mod tests { } } + #[rstest] + #[case::string_view(DataType::Utf8View)] + #[case::binary_view(DataType::BinaryView)] + #[case::nested_view(DataType::Struct(vec![Field::new("value", DataType::Utf8View, true)].into()))] + #[tokio::test] + async fn test_alter_columns_unsupported_type(#[case] data_type: DataType) { + let table = Table::new_with_handler("my_table", |_| -> http::Response { + panic!("an unserializable alteration must not reach the server") + }); + let err = table + .alter_columns(&[ColumnAlteration::new("value".into()).cast_to(data_type)]) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. }), "got {err:?}"); + assert!(err.to_string().contains("value")); + assert!(err.to_string().contains("Unsupported type")); + } + #[rstest] #[case(true)] #[case(false)] @@ -5649,6 +5702,252 @@ mod tests { schema_describe_response(&schema) } + #[tokio::test] + async fn test_adapter_construction_only_describes_blob_schema() { + use datafusion_catalog::TableProvider; + + let requests = Arc::new(AtomicUsize::new(0)); + let observed = requests.clone(); + let table = Table::new_with_handler("my_table", move |request| { + observed.fetch_add(1, Ordering::SeqCst); + assert_eq!(request.url().path(), "/v1/table/my_table/describe/"); + blob_describe_response() + }); + + let adapter = + crate::table::datafusion::BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(); + assert_eq!(requests.load(Ordering::SeqCst), 1); + let schema = adapter.schema(); + let DataType::Struct(fields) = schema.field_with_name("image").unwrap().data_type() else { + panic!("expected a blob descriptor"); + }; + assert!(fields.find("size").unwrap().1.is_nullable()); + assert!(fields.find("data").is_none()); + } + + #[tokio::test] + async fn test_adapter_blob_read_schema_matches_remote_scan() { + use datafusion::prelude::SessionContext; + use datafusion_catalog::TableProvider; + use lance_core::datatypes::Projection; + + let write_schema = Schema::new(vec![ + Field::new("id", DataType::Int64, false), + crate::blob("image", true), + ]); + let read_schema = Arc::new( + Projection::full(Arc::new(LanceSchema::try_from(&write_schema).unwrap())) + .to_arrow_schema(), + ); + let descriptor = arrow_array::new_null_array(read_schema.field(1).data_type(), 2); + let response = RecordBatch::try_new( + read_schema, + vec![Arc::new(Int64Array::from(vec![1, 2])), descriptor], + ) + .unwrap(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => { + schema_describe_response(&write_schema).map(String::into_bytes) + } + "/v1/table/my_table/query/" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let columns = body["columns"] + .as_array() + .unwrap() + .iter() + .map(|column| { + response + .schema() + .index_of(column.as_str().unwrap()) + .unwrap() + }) + .collect::>(); + http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_FILE_CONTENT_TYPE) + .body(write_ipc_file(&response.project(&columns).unwrap())) + .unwrap() + } + path => panic!("unexpected request: {path}"), + }); + let adapter = + crate::table::datafusion::BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(); + let ctx = SessionContext::new(); + let plan = adapter.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), adapter.schema()); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + assert!( + batches + .iter() + .all(|batch| batch.schema() == adapter.schema()) + ); + let adapter = adapter.with_blob_schema(crate::table::datafusion::BlobSchema::Write); + let plan = adapter + .scan(&ctx.state(), Some(&vec![0]), &[], None) + .await + .unwrap(); + let expected = Arc::new(adapter.schema().project(&[0]).unwrap()); + assert_eq!(plan.schema(), expected); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert!(batches.iter().all(|batch| batch.schema() == expected)); + } + + #[tokio::test] + async fn test_adapter_write_scan_checks_metadata_and_nullability() { + use crate::table::datafusion::{BaseTableAdapter, BlobSchema}; + use datafusion::prelude::SessionContext; + use datafusion_catalog::TableProvider; + + let declared = Field::new("id", DataType::Int64, false) + .with_metadata(HashMap::from([("meaning".into(), "identifier".into())])); + for returned in [ + declared.clone(), + declared.clone().with_nullable(true), + declared.clone().with_metadata(HashMap::new()), + ] { + let matches = returned == declared; + let write_schema = Schema::new(vec![declared.clone()]); + let response = RecordBatch::try_new( + Arc::new(Schema::new(vec![returned])), + vec![Arc::new(Int64Array::from(vec![1]))], + ) + .unwrap(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => { + schema_describe_response(&write_schema).map(String::into_bytes) + } + "/v1/table/my_table/query/" => http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_FILE_CONTENT_TYPE) + .body(write_ipc_file(&response)) + .unwrap(), + path => panic!("unexpected request: {path}"), + }); + let adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write); + let ctx = SessionContext::new(); + let result = adapter.scan(&ctx.state(), None, &[], None).await; + if matches { + let plan = result.unwrap(); + assert_eq!(plan.schema(), adapter.schema()); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(batches[0].schema(), adapter.schema()); + } else { + let error = result.unwrap_err(); + assert!( + error.to_string().contains("Scan schema mismatch"), + "{error}" + ); + } + } + } + + #[tokio::test] + async fn test_adapter_blob_write_sql_remote_payload_round_trip() { + use crate::table::datafusion::{BaseTableAdapter, BlobSchema}; + use datafusion::prelude::SessionContext; + + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + crate::blob("image", true), + ])); + let described_schema = schema.clone(); + let (sender, receiver) = std::sync::mpsc::channel(); + let table = + Table::new_with_handler("my_table", move |mut request| match request.url().path() { + "/v1/table/my_table/describe/" => schema_describe_response(&described_schema), + "/v1/table/my_table/insert/" => { + let body = request.body_mut().take().unwrap(); + sender.send(body).unwrap(); + http::Response::builder() + .status(200) + .body(r#"{"version": 2}"#.to_string()) + .unwrap() + } + path => panic!("unexpected request: {path}"), + }); + let adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write); + let ctx = SessionContext::new(); + ctx.register_table("docs", Arc::new(adapter)).unwrap(); + + // Persist the exact Arrow stream sent to the mocked remote endpoint to + // a real native sink, then check storage bytes independently of schemas. + let tmp = tempfile::tempdir().unwrap(); + let db = crate::connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let sink = db + .create_empty_table("sink", schema) + .execute() + .await + .unwrap(); + for query in [ + "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", + "INSERT INTO docs VALUES (2, NULL)", + "INSERT INTO docs (id) VALUES (3)", + "INSERT INTO docs SELECT 4, named_struct('data', X'', 'uri', NULL)", + ] { + ctx.sql(query).await.unwrap().collect().await.unwrap(); + let body = collect_body(receiver.recv().unwrap()).await; + let reader = StreamReader::try_new(Cursor::new(body), None).unwrap(); + for batch in reader { + sink.add(batch.unwrap()).execute().await.unwrap(); + } + } + let batches = sink + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let row_ids = batches + .iter() + .flat_map(|batch| { + batch + .column_by_name("_rowid") + .unwrap() + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect::>(); + let actual = sink.fetch_blobs("image", &row_ids).await.unwrap(); + assert_eq!( + actual, + LargeBinaryArray::from(vec![ + Some(b"hi".as_slice()), + None, + None, + Some(b"".as_slice()) + ]) + ); + } + #[rstest] #[case(semver::Version::new(0, 1, 0))] #[case(semver::Version::new(0, 5, 0))] @@ -6289,7 +6588,7 @@ mod tests { match result.unwrap_err() { Error::NotSupported { message } => assert_eq!( message, - format!("{operation} is not supported for remote tables.") + format!("{operation} is not supported in LanceDB Distributed.") ), error => panic!("expected not-supported error, got {error}"), } @@ -6317,7 +6616,7 @@ mod tests { .unwrap_err(); assert_not_supported_error( error, - "IVF_HNSW_PQ is not supported for remote tables. Please use IVF_HNSW_SQ instead.", + "IVF_HNSW_PQ is not supported in LanceDB Distributed. Please use IVF_HNSW_SQ instead.", ); } @@ -7421,10 +7720,9 @@ mod tests { panic!("legacy remote query unexpectedly succeeded") }; - assert!( - err.to_string() - .contains("document granularity requires remote server version 0.6.0 or later") - ); + assert!(err.to_string().contains( + "document granularity requires LanceDB Enterprise server version 0.6.0 or later" + )); } #[rstest] @@ -8016,6 +8314,157 @@ mod tests { assert_eq!(err.to_string(), "Job job-err failed: preempted (in commit)"); } + // The name-based endpoint deliberately exposes an already-ready old index. + // A replacement must wait on the new job, not mistake that index for success. + fn index_wait_fixture( + job_id: Option<&'static str>, + terminal_state: &'static str, + ) -> ( + Table, + Arc, + Arc, + ) { + let job_polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let index_polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let jobs = job_polls.clone(); + let indices = index_polls.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let body = match request.url().path() { + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); + return http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap(); + } + "/v1/table/my_table/create_index/" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + // Replacement is the default and omitted from the wire body. + assert!(body.get("replace").is_none()); + match job_id { + Some(id) => json!({"job_id": id}), + None => json!({}), + } + } + "/v1/jobs/describe" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["job_id"], json!(job_id.unwrap())); + let poll = jobs.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + json!({ + "job_id": job_id.unwrap(), + "job_state": if poll == 0 { "IN_PROGRESS" } else { terminal_state }, + "failure": {"phase": "build", "message": "invalid index config", + "retryable": false} + }) + } + "/v1/table/my_table/index/list/" => { + indices.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + json!({"indexes": [{"index_name": "a_idx", "columns": ["a"], + "index_uuid": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "index_status": "done"}]}) + } + "/v1/table/my_table/index/a_idx/stats/" => json!({ + "num_indexed_rows": 100, "num_unindexed_rows": 0, "index_type": "BTREE" + }), + path => panic!("Unexpected path: {path}"), + }; + http::Response::builder() + .status(200) + .body(body.to_string()) + .unwrap() + }); + (table, job_polls, index_polls) + } + + #[tokio::test] + async fn test_create_index_wait_timeout_tracks_job() { + for state in ["DONE", "FAILED", "CANCELLED"] { + let (table, jobs, indices) = index_wait_fixture(Some("new-index-job"), state); + let result = table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(true) + .wait_timeout(Duration::from_secs(2)) + .execute() + .await; + match state { + "DONE" => result.unwrap(), + "FAILED" => match result.unwrap_err() { + Error::JobFailed { job_id, failure } => { + assert_eq!(job_id.as_deref(), Some("new-index-job")); + assert_eq!(failure.message.as_deref(), Some("invalid index config")); + assert_eq!(failure.phase.as_deref(), Some("build")); + } + error => panic!("Expected job failure, got {error:?}"), + }, + "CANCELLED" => assert!(matches!(result, Err(Error::JobCancelled { .. }))), + _ => unreachable!(), + } + assert_eq!(jobs.load(std::sync::atomic::Ordering::SeqCst), 2); + assert_eq!(indices.load(std::sync::atomic::Ordering::SeqCst), 0); + } + } + + #[tokio::test] + async fn test_create_index_wait_timeout_bounds_job_polling() { + let (table, jobs, indices) = index_wait_fixture(Some("new-index-job"), "IN_PROGRESS"); + let error = table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(true) + .wait_timeout(Duration::from_millis(10)) + .execute() + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout { message } if message.contains("new-index-job"))); + assert_eq!(jobs.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!(indices.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn test_create_index_wait_timeout_legacy_fallback() { + let (table, jobs, indices) = index_wait_fixture(None, "DONE"); + table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(true) + .wait_timeout(Duration::from_secs(2)) + .execute() + .await + .unwrap(); + assert_eq!(jobs.load(std::sync::atomic::Ordering::SeqCst), 0); + assert_eq!(indices.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_create_index_wait_timeout_absent_does_not_poll() { + let (table, jobs, indices) = index_wait_fixture(Some("new-index-job"), "IN_PROGRESS"); + table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(true) + .execute() + .await + .unwrap(); + assert_eq!(jobs.load(std::sync::atomic::Ordering::SeqCst), 0); + assert_eq!(indices.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn test_create_index_wait_timeout_preserves_maximum() { + let (table, jobs, indices) = index_wait_fixture(Some("new-index-job"), "DONE"); + let error = table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(true) + .wait_timeout(Duration::from_secs(2 * 60 * 60 + 1)) + .execute() + .await + .unwrap_err(); + assert!(matches!(error, Error::InvalidInput { .. })); + assert_eq!(jobs.load(std::sync::atomic::Ordering::SeqCst), 0); + assert_eq!(indices.load(std::sync::atomic::Ordering::SeqCst), 0); + } + /// Servers that return no job id (e.g. an empty create-index response) /// yield an already-done job. #[tokio::test] @@ -8219,12 +8668,9 @@ mod tests { .execute() .await; - assert!( - result - .unwrap_err() - .to_string() - .contains("document granularity requires remote server version 0.6.0 or later") - ); + assert!(result.unwrap_err().to_string().contains( + "document granularity requires LanceDB Enterprise server version 0.6.0 or later" + )); } #[tokio::test] @@ -8686,6 +9132,131 @@ mod tests { ); } + #[tokio::test] + #[serial_test::serial(language_model_env)] + async fn test_tokenize_model_backed_tokenizer_without_model_files() { + let model_home = tempfile::tempdir().unwrap(); + // SAFETY: This is only called in tests, serialized on the env key. + unsafe { + std::env::set_var("LANCE_LANGUAGE_MODEL_HOME", model_home.path()); + } + let schema = Schema::new(vec![Field::new("text", DataType::Utf8, false)]); + let index_details = serde_json::json!({ + "base_tokenizer": "jieba/default", + "language": "English", + "with_position": false, + "max_token_length": 40, + "lower_case": true, + "stem": false, + "remove_stop_words": false, + "ascii_folding": false, + }) + .to_string(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.method(), "POST"); + match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap(), + "/v1/table/my_table/index/list/" => { + let body = serde_json::json!({ + "indexes": [ + { + "index_name": "text_idx", + "columns": ["text"], + "index_type": "FTS", + "index_details": index_details, + }, + ] + }); + http::Response::builder() + .status(200) + .body(serde_json::to_string(&body).unwrap()) + .unwrap() + } + path => panic!("Unexpected path: {}", path), + } + }); + + let result = table.tokenize("我们是中国人", "text_idx").await; + // SAFETY: This is only called in tests, serialized on the env key. + unsafe { + std::env::remove_var("LANCE_LANGUAGE_MODEL_HOME"); + } + + let err = result.unwrap_err(); + let Error::InvalidInput { message } = err else { + panic!("expected InvalidInput, got {err:?}"); + }; + // The original cause and the index context are preserved... + assert!(message.contains("Invalid directory path"), "{message}"); + assert!( + message.contains("full text search index 'text_idx'"), + "{message}" + ); + // ...and the message explains that this is a client-side limitation. + assert!( + message.contains("tokenize() runs on the client"), + "{message}" + ); + assert!(message.contains("'jieba/default'"), "{message}"); + assert!(message.contains("LANCE_LANGUAGE_MODEL_HOME"), "{message}"); + assert!( + message.contains("match the files the server uses"), + "{message}" + ); + } + + #[tokio::test] + async fn test_tokenize_unknown_tokenizer_error_has_no_model_files_hint() { + let schema = Schema::new(vec![Field::new("text", DataType::Utf8, false)]); + let index_details = serde_json::json!({ + "base_tokenizer": "no_such_tokenizer", + "language": "English", + "with_position": false, + "max_token_length": 40, + "lower_case": true, + "stem": false, + "remove_stop_words": false, + "ascii_folding": false, + }) + .to_string(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.method(), "POST"); + match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap(), + "/v1/table/my_table/index/list/" => { + let body = serde_json::json!({ + "indexes": [ + { + "index_name": "text_idx", + "columns": ["text"], + "index_type": "FTS", + "index_details": index_details, + }, + ] + }); + http::Response::builder() + .status(200) + .body(serde_json::to_string(&body).unwrap()) + .unwrap() + } + path => panic!("Unexpected path: {}", path), + } + }); + + let err = table.tokenize("hello", "text_idx").await.unwrap_err(); + let message = err.to_string(); + assert!( + !message.contains("tokenize() runs on the client"), + "{message}" + ); + } + #[tokio::test] async fn test_tokenize_requires_existing_index_name() { let schema = Schema::new(vec![Field::new("text", DataType::Utf8, false)]); @@ -9291,31 +9862,44 @@ mod tests { /// client never types the expression itself. #[tokio::test] async fn test_add_computed_columns_sends_the_expression() { - let table = Table::new_with_handler("my_table", |request| match request.url().path() { - "/v1/table/my_table/describe/" => simple_describe_response(), - "/v1/table/my_table/add_columns/" => { - assert_eq!(request.method(), "POST"); - let body = request.body().unwrap().as_bytes().unwrap(); - let value: serde_json::Value = serde_json::from_slice(body).unwrap(); - assert_eq!( - value["new_columns"], - serde_json::json!([{"name": "doubled", "computed": "x * 2"}]) - ); - http::Response::builder() - .status(200) - .body(r#"{"version": 7}"#.to_string()) - .unwrap() - } - path => panic!("Unexpected path: {path}"), - }); + for interval in [None, Some(300)] { + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => simple_describe_response(), + "/v1/table/my_table/add_columns/" => { + assert_eq!(request.method(), "POST"); + let body = request.body().unwrap().as_bytes().unwrap(); + let value: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!( + value["new_columns"], + serde_json::json!([{"name": "doubled", "computed": "x * 2"}]) + ); + assert_eq!(value["auto_refresh_enabled"], false); + if let Some(interval) = interval { + assert_eq!(value["auto_refresh_interval_seconds"], interval); + } else { + assert!(value.get("auto_refresh_interval_seconds").is_none()); + } + http::Response::builder() + .status(200) + .body(r#"{"version": 7}"#.to_string()) + .unwrap() + } + path => panic!("Unexpected path: {path}"), + }); - let result = table - .add_columns() - .computed("doubled", "x * 2") - .execute() - .await - .unwrap(); - assert_eq!(result.version, 7); + let result = table + .add_columns() + .computed("doubled", "x * 2") + .computed_options(crate::table::computed_columns::ComputedColumnOptions { + auto_refresh_enabled: false, + auto_refresh_interval_seconds: interval, + }) + .execute() + .await + .unwrap(); + assert_eq!(result.version, 7); + } } #[tokio::test] @@ -9333,10 +9917,11 @@ mod tests { request.body().unwrap().as_bytes().unwrap(), ) .unwrap(); - let expected: serde_json::Value = serde_json::from_str(include_str!( + let mut expected: serde_json::Value = serde_json::from_str(include_str!( "../../tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json" )) .unwrap(); + expected["auto_refresh_enabled"] = serde_json::json!(true); assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -9532,10 +10117,11 @@ mod tests { request.body().unwrap().as_bytes().unwrap(), ) .unwrap(); - let expected: serde_json::Value = serde_json::from_str(include_str!( + let mut expected: serde_json::Value = serde_json::from_str(include_str!( "../../tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json" )) .unwrap(); + expected["auto_refresh_enabled"] = serde_json::json!(true); assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -9578,10 +10164,11 @@ mod tests { "/v1/table/my_table/add_columns/" => { let actual: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - let expected: serde_json::Value = serde_json::from_str(include_str!( + let mut expected: serde_json::Value = serde_json::from_str(include_str!( "../../tests/fixtures/first_class_functions/v1/remote_multi_output_declaration_request.json" )) .unwrap(); + expected["auto_refresh_enabled"] = serde_json::json!(true); assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -12395,6 +12982,67 @@ mod tests { ); } + #[rstest] + #[case("create", "{}")] + #[case("create", r#"{"upload_id": 1}"#)] + #[case("create", "not json")] + #[case("complete", "{}")] + #[case("complete", r#"{"version": "invalid"}"#)] + #[case("complete", "not json")] + #[tokio::test] + async fn test_multipart_write_error_preserves_request_id( + #[case] failed_stage: &str, + #[case] body: &str, + ) { + let failed_stage = failed_stage.to_string(); + let body = body.to_string(); + let request_id = Arc::new(std::sync::Mutex::new(String::new())); + let observed_request_id = request_id.clone(); + let table = Table::new_with_handler_version( + "my_table", + semver::Version::new(0, 4, 0), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/describe/" { + return simple_describe_response(); + } + if path == format!("/v1/table/my_table/multipart_write/{failed_stage}") { + *observed_request_id.lock().unwrap() = request.headers()["x-request-id"] + .to_str() + .unwrap() + .to_string(); + return http::Response::builder() + .status(200) + .body(body.clone()) + .unwrap(); + } + let response = match path { + "/v1/table/my_table/multipart_write/create" => r#"{"upload_id":"upload-1"}"#, + "/v1/table/my_table/insert/" => r#"{"version":1}"#, + "/v1/table/my_table/multipart_write/abort" => "", + _ => panic!("Unexpected request path: {path}"), + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }, + ); + let batch = record_batch!(("id", Int32, [1, 2, 3])).unwrap(); + let error = table + .add(vec![batch]) + .write_parallelism(2) + .execute() + .await + .unwrap_err(); + let expected = request_id.lock().unwrap(); + assert!(!expected.is_empty()); + match error { + Error::Http { request_id, .. } => assert_eq!(request_id, *expected), + other => panic!("Expected Http error, got {other:?}"), + } + } + #[tokio::test] async fn test_multipart_write_progress() { let callback_count = Arc::new(AtomicUsize::new(0)); @@ -13973,26 +14621,15 @@ mod tests { } #[tokio::test] - async fn test_materialized_view_describe_and_refresh_requires_sql() { - const QUERY: &str = - "SELECT s.x, d.label FROM analytics.source s JOIN analytics.dim d ON s.id = d.id"; - let table = Table::new_with_handler("my_table", |request| match request.url().path() { - "/v1/materialized_view/my_table/describe" => http::Response::builder() - .status(200) - .body( - json!({ - "name": "my_table", - "query": QUERY - }) - .to_string(), - ) - .unwrap(), - path => panic!("unexpected request: {path}"), + async fn test_materialized_view_requires_sql() { + let table = Table::new_with_handler("my_table", |request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()) }); - let view = crate::MaterializedView::from_table(table).await.unwrap(); - assert_eq!(view.definition_sql(), QUERY); - assert!(view.definition().is_err()); - let error = view.refresh().execute().await.unwrap_err(); + let error = table + .base_table() + .materialized_view_info() + .await + .unwrap_err(); assert!(error.to_string().contains("SQL is unavailable")); } diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index bcaf47765..65ab13935 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -21,7 +21,7 @@ use reqwest::{Response, StatusCode, header}; use tokio::sync::{Mutex, OwnedSemaphorePermit}; use crate::Error; -use crate::blob::{BlobFile, BlobRangeRequest}; +use crate::blob::{BlobDescriptor, BlobDescriptorSource, BlobFile, BlobRangeRequest}; use crate::error::Result; use crate::query::{QueryFilter, QueryRequest, Select}; use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; @@ -49,6 +49,7 @@ fn is_fetch_blobs_byte_limit_error(error: &Error) -> bool { enum RangeRequestMode { SizeProbe, DataRead, + MetadataRead, } #[async_trait::async_trait] @@ -86,6 +87,9 @@ struct TableBlobRangeRequester { path: String, version: Option, branch: Option, + source_uri: Option, + source_commit_micros: Option, + row_is_address: bool, freshness: Arc>, parent_freshness: Arc>, parent_freshness_request: FreshnessHeaders, @@ -109,15 +113,27 @@ impl BlobRangeRequester for TableBlobRangeRequester { .expect("blob request semaphore is never closed"); let freshness_request = freshness_headers_snapshot(&self.freshness, self.read_consistency_interval); - let mut request = freshness_request - .apply(self.client.get(&self.path)) - .header(header::RANGE, range_header); + let mut request = if matches!(mode, RangeRequestMode::MetadataRead) { + freshness_request.apply(self.client.head(&self.path)) + } else { + freshness_request + .apply(self.client.get(&self.path)) + .header(header::RANGE, range_header) + }; if let Some(version) = version.or(self.version) { request = request.query(&[("version", version)]); } if let Some(branch) = &self.branch { request = request.query(&[("branch", branch)]); } + if let Some(source_uri) = &self.source_uri { + request = request + .query(&[("source_uri", source_uri)]) + .query(&[("row_is_address", self.row_is_address)]); + } + if let Some(timestamp) = self.source_commit_micros { + request = request.query(&[("source_commit_micros", timestamp)]); + } let (request_id, response) = self.client.send_with_retry(request, None, true).await?; // Preserve 416 size-probe responses so the caller can detect empty blobs. if response.status() == StatusCode::RANGE_NOT_SATISFIABLE @@ -131,8 +147,10 @@ impl BlobRangeRequester for TableBlobRangeRequester { } let response = self.client.check_response(&request_id, response).await?; freshness_request.observe_headers(&self.freshness, response.headers()); - self.parent_freshness_request - .observe_headers(&self.parent_freshness, response.headers()); + if self.source_uri.is_none() { + self.parent_freshness_request + .observe_headers(&self.parent_freshness, response.headers()); + } Ok(BlobRangeResponse { request_id, response, @@ -387,7 +405,7 @@ impl RemoteTable { error } - /// Blob v2 columns are marked in field metadata, which `describe` returns. Reading + /// Blob columns are marked in field metadata, which `describe` returns. Reading /// them from the cached schema needs no route of its own and no version gate. pub(super) async fn blob_columns_impl(&self) -> Result> { let schema = self.schema().await?; @@ -630,6 +648,51 @@ impl RemoteTable { Ok(files) } + pub(super) async fn open_blob_file_impl( + &self, + descriptor: &BlobDescriptor, + ) -> Result { + descriptor.validate()?; + self.ensure_blob_files_supported()?; + let source = &descriptor.source; + let snapshot = ReadSnapshot { + version: Some(source.version), + freshness_state: FreshnessState { + pinned: true, + ..Default::default() + }, + ..Default::default() + }; + let requester = self.blob_range_requester_with_source( + &source.column, + source.row_reference, + &snapshot, + Some(source), + ); + let size = if descriptor.kind == 3 && descriptor.size == 0 { + let metadata = requester + .request_range("", RangeRequestMode::MetadataRead, Some(source.version)) + .await?; + if metadata.response.status() != StatusCode::OK { + return Err(Error::InvalidInput { + message: "non-null blob descriptor did not resolve to a stored value".into(), + }); + } + metadata + .response + .headers() + .get(header::CONTENT_LENGTH) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .ok_or_else(|| Error::InvalidInput { + message: "blob metadata response has no valid Content-Length".into(), + })? + } else { + descriptor.size + }; + Ok(RemoteBlobFile::new(requester, size, Some(source.version)).into()) + } + /// Probe each row once for its size. /// /// Serves callers that must not issue a query, such as a single blob that @@ -793,6 +856,16 @@ impl RemoteTable { column: &str, row_id: u64, read_snapshot: &ReadSnapshot, + ) -> Arc { + self.blob_range_requester_with_source(column, row_id, read_snapshot, None) + } + + fn blob_range_requester_with_source( + &self, + column: &str, + row_id: u64, + read_snapshot: &ReadSnapshot, + source: Option<&BlobDescriptorSource>, ) -> Arc { let path = format!( "/v1/table/{}/blob/{}/{row_id}/bytes", @@ -803,7 +876,10 @@ impl RemoteTable { client: self.client.clone(), path, version: read_snapshot.version, - branch: self.branch.clone(), + branch: source.map_or_else(|| self.branch.clone(), |source| source.branch.clone()), + source_uri: source.map(|source| source.uri.clone()), + source_commit_micros: source.map(|source| source.committed_at_micros), + row_is_address: source.is_some_and(|source| source.row_is_address), freshness: Arc::new(std::sync::Mutex::new(read_snapshot.freshness_state)), parent_freshness: self.freshness.clone(), parent_freshness_request: read_snapshot.freshness, @@ -1024,6 +1100,99 @@ mod tests { .unwrap() } + #[tokio::test] + async fn open_descriptor_files_are_lazy_and_pin_ranges_for_every_storage_kind() { + for kind in 0..=5 { + let requests = Arc::new(StdMutex::new(Vec::new())); + let captured = requests.clone(); + let table = RemoteTable::new_mock( + "videos".to_string(), + move |request| { + for name in [ + "x-lancedb-min-version", + "x-lancedb-min-read-version", + "x-lancedb-min-timestamp", + ] { + assert!(request.headers().get(name).is_none()); + } + assert_eq!( + request.url().path(), + "/v1/table/videos/blob/video/12884901889/bytes" + ); + let parameters = request + .url() + .query_pairs() + .into_owned() + .collect::>(); + assert_eq!(parameters["version"], "7"); + assert_eq!(parameters["source_commit_micros"], "1234"); + assert_eq!(parameters["branch"], "dev"); + assert_eq!(parameters["row_is_address"], "true"); + assert_eq!( + parameters["source_uri"], + "s3://bucket/videos.lance/tree/dev" + ); + captured.lock().unwrap().push(request.method().clone()); + if request.method() == reqwest::Method::HEAD { + assert!(request.headers().get(header::RANGE).is_none()); + http::Response::builder() + .status(200) + .header(header::CONTENT_LENGTH, PAYLOAD.len().to_string()) + .body(Vec::new()) + .unwrap() + } else { + range_response(&request, PAYLOAD) + } + }, + Some(Version::new(0, 5, 0)), + ); + { + let mut freshness = table.freshness.lock().unwrap(); + freshness.min_version = Some(99); + freshness.min_read_version = Some(2); + } + let descriptor = BlobDescriptor { + kind, + position: 0, + size: if kind == 3 { 0 } else { PAYLOAD.len() as u64 }, + blob_id: 0, + blob_uri: String::new(), + source: BlobDescriptorSource { + uri: "s3://bucket/videos.lance/tree/dev".into(), + version: 7, + committed_at_micros: 1234, + branch: Some("dev".into()), + column: "video".into(), + row_reference: 12884901889, + row_is_address: true, + }, + }; + let file = table.open_blob_file(&descriptor).await.unwrap(); + let expected = if kind == 3 { + vec![reqwest::Method::HEAD] + } else { + vec![] + }; + assert_eq!(*requests.lock().unwrap(), expected); + assert_eq!(file.size(), PAYLOAD.len() as u64); + file.seek(4).await.unwrap(); + assert_eq!(file.read_up_to(5).await.unwrap().as_ref(), &PAYLOAD[4..9]); + assert_eq!(file.tell().await.unwrap(), 9); + assert_eq!(table.freshness.lock().unwrap().min_read_version, Some(2)); + assert_eq!(file.read_range(0..3).await.unwrap().as_ref(), &PAYLOAD[..3]); + assert_eq!(file.tell().await.unwrap(), 9); + assert_eq!( + requests + .lock() + .unwrap() + .iter() + .filter(|method| **method == reqwest::Method::GET) + .count(), + 2 + ); + } + } + fn mock_remote_blob_table( requests: Arc>>, ) -> RemoteTable { diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index 8a735fa03..ebae823e1 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -589,6 +589,16 @@ impl DisplayAs for RemoteWriteExec { } impl ExecutionPlan for RemoteWriteExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { Self::static_name() } @@ -1149,6 +1159,16 @@ mod tests { } impl ExecutionPlan for ErroringExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "ErroringExec" } diff --git a/rust/lancedb/src/sql.rs b/rust/lancedb/src/sql.rs index c2ef13ba5..713a79e86 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 remote database. +//! Handles to SQL queries running on a LanceDB Distributed database. use std::{fmt, sync::Arc}; @@ -18,9 +18,9 @@ pub enum QueryStatus { Running, /// The server has made the complete result available. /// - /// A query submitted with parameters streams its rows on the call that - /// runs it, so it reports `Finished` only once its reader has received - /// the last batch. Read it rather than waiting for this status. + /// Directly streamed queries report `Finished` when their stream reaches + /// its end. Deferred queries report the server's execution state. Open the + /// reader directly instead of waiting for this status before reading. Finished, /// The server accepted cancellation but has not confirmed it yet. Cancelling, @@ -64,9 +64,10 @@ pub(crate) trait QueryHandle: Send + Sync { /// A handle to a submitted SQL query. /// /// The handle can be inspected, opened as an Arrow reader, or cancelled. -/// Dropping it does not cancel the server-side query, unless the query was -/// submitted with parameters: those run on the call that returns their rows, -/// so dropping the handle before reading, or dropping the reader, stops them. +/// The server may stream results on the initial call or defer execution and +/// return result tickets. Dropping an unread handle or its reader stops a +/// directly streamed query; deferred execution continues until explicitly +/// cancelled. This applies equally with and without parameters. /// Identifier lookup is scoped to the connection that submitted the query and /// is not a durable resume mechanism. pub struct Query { @@ -95,10 +96,9 @@ impl Query { /// Get a point-in-time description of the query. /// - /// For a query submitted with parameters the status follows its result - /// stream: it stays [`QueryStatus::Running`] until the reader has received - /// every row, so open [`Self::reader`] directly instead of polling for - /// [`QueryStatus::Finished`] first. + /// Directly streamed queries stay [`QueryStatus::Running`] until the result + /// stream ends. Deferred queries expose the server's execution state. Open + /// [`Self::reader`] directly instead of waiting for [`QueryStatus::Finished`]. pub async fn describe(&self) -> Result { self.handle.describe().await } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 624b1a31c..cf2442d50 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -3,7 +3,7 @@ //! LanceDB Table APIs -use crate::blob::BlobFile; +use crate::blob::{BlobDescriptor, BlobFile}; use arrow_array::{LargeBinaryArray, RecordBatch, RecordBatchReader}; use arrow_schema::{Schema, SchemaRef}; use async_trait::async_trait; @@ -107,7 +107,9 @@ use futures::future::join_all; pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags}; pub use lance::dataset::scanner::DatasetRecordBatchStream; pub use lance_index::optimize::OptimizeOptions; -pub use optimize::{CompactionOptions, OptimizeAction, OptimizeStats}; +pub use optimize::{ + CompactionMode, CompactionOptions, IndexRemapMode, OptimizeAction, OptimizeStats, +}; pub use refresh::RefreshColumnResult; pub use rte_stats::{MemtableStats, RTEStats, SsTableStats, TableShardStats}; pub use schema_evolution::{ @@ -549,7 +551,7 @@ pub fn tokenize(query: &str, params: &InvertedIndexParams) -> Result, + _full: bool, ) -> Result> { Err(Error::NotSupported { message: "remote materialized-view refresh is not supported on this table type".into(), @@ -649,7 +652,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 on remote tables. + /// Currently only supported in LanceDB Distributed. /// If `columns` is `None`, all columns are prewarmed. async fn prewarm_data(&self, columns: Option>) -> Result<()>; /// Get statistics about the index. @@ -764,7 +767,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn close_rte_writers(&self) -> Result<()> { Ok(()) } - /// Names of the blob v2 columns in this table, in declaration order. + /// Names of the blob v1 and v2 columns in this table, in declaration order. async fn blob_columns(&self) -> Result> { Err(Error::NotSupported { message: "blob_columns is not supported on this table type".into(), @@ -796,6 +799,12 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "fetch_blob_files is not supported on this table type".into(), }) } + /// Open a descriptor at its pinned source version. See [`Table::open_blob_file`]. + async fn open_blob_file(&self, _descriptor: &BlobDescriptor) -> Result { + Err(Error::NotSupported { + message: "open_blob_file is not supported on this table type".into(), + }) + } /// Gets the table tag manager. async fn tags(&self) -> Result>; /// Optimize the dataset. @@ -808,12 +817,13 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { ) -> Result; /// Declare computed columns, each defined by a SQL expression. /// - /// Where the declaration is planned depends on the backend: a local table - /// validates and types the expression itself, while a remote one sends the - /// expression for the server to plan. + /// Where the declaration is planned depends on the backend: a LanceDB Embedded + /// table validates and types the expression itself, while a LanceDB Distributed + /// table sends the expression for the server to plan. async fn add_computed_columns( &self, _columns: &[(String, String)], + _options: computed_columns::ComputedColumnOptions, ) -> Result { Err(Error::NotSupported { message: "computed columns are not supported on this table type".into(), @@ -824,9 +834,10 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { &self, _application: &crate::function::FunctionApplication, _output_name: Option<&str>, + _options: computed_columns::ComputedColumnOptions, ) -> Result { Err(Error::NotSupported { - message: "Function columns are supported only on LanceDB Cloud and Enterprise".into(), + message: "Function columns are supported only in LanceDB Distributed".into(), }) } /// Fill a computed column's unfilled rows and recompute those whose @@ -835,7 +846,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// The default returns `NotSupported`; Lance-backed tables override it. async fn refresh_column(&self, _column: &str) -> Result { Err(Error::NotSupported { - message: "computed columns are supported only on local tables".into(), + message: "this operation is only supported on LanceDB Embedded".into(), }) } /// Fill a computed column's unfilled rows and recompute those whose @@ -845,7 +856,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { _column: &str, ) -> Result> { Err(Error::NotSupported { - message: "computed columns are supported only on local tables".into(), + message: "this operation is only supported on LanceDB Embedded".into(), }) } /// The per-row errors Function refreshes recorded on this table; see @@ -855,8 +866,7 @@ 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 on LanceDB Cloud and Enterprise" - .into(), + message: "per-row Function errors are recorded only in LanceDB Distributed".into(), }) } /// Alter columns in the table. @@ -983,7 +993,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 remote tables override it. + /// The default returns `NotSupported`; Lance-backed and LanceDB Distributed tables override it. async fn update_field_metadata( &self, _updates: &[FieldMetadataUpdate], @@ -1261,7 +1271,7 @@ impl Table { self.inner.count_rows(filter).await } - /// Names of the row-addressable blob v2 columns, in declaration order. + /// Names of the row-addressable blob v1 and v2 columns, in declaration order. /// /// Blobs nested in structs use dotted paths (e.g. `info.blob`). Blobs /// inside lists are omitted because row ids cannot identify their elements. @@ -1272,9 +1282,10 @@ impl Table { /// Materialize blob bytes for the given row ids. /// + /// 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. Cloud limits individual - /// requests to 1024 row ids and 64 MiB of blob bytes; the remote client + /// valid empty blobs contain empty byte strings. LanceDB Distributed 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 /// [`Self::fetch_blob_files`] for large selections. @@ -1307,7 +1318,7 @@ impl Table { /// /// Blobs inside lists cannot be fetched by row id. Returns /// [`Error::InvalidInput`] for those paths, when the column does not exist, - /// or when it is not a blob v2 column. Returns [`Error::NotSupported`] on + /// or when it is not a blob column. Returns [`Error::NotSupported`] on /// table types without blob support. pub async fn fetch_blobs( &self, @@ -1317,14 +1328,15 @@ impl Table { self.inner.fetch_blobs(column.as_ref(), row_ids).await } - /// Materialize row-specific ranges from a blob v2 column. + /// Materialize row-specific ranges from a blob column. /// + /// Native tables support both legacy blob v1 and blob v2 columns. /// Each request contains a row id and a blob-local offset and length. /// Requests may be duplicated or reordered, including multiple /// 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. - /// Remote tables read through version-pinned [`BlobFile`] handles using + /// LanceDB Distributed tables read through version-pinned [`BlobFile`] handles using /// HTTP byte-range requests. /// /// `_rowid` values stay valid after compaction when the table has stable @@ -1351,7 +1363,7 @@ impl Table { /// ``` /// /// Returns an error when a range is invalid, a requested row id does not - /// exist, or the column is not a blob v2 column. Returns + /// exist, or the column is not a blob column. Returns /// [`Error::NotSupported`] on table types without blob support. pub async fn fetch_blob_ranges( &self, @@ -1366,6 +1378,7 @@ impl Table { /// Open lazy [`BlobFile`] handles for the given row ids. /// + /// Native tables support both legacy blob v1 and blob v2 columns. /// Same length and order as `row_ids`. Null rows are `None`. Bytes are not /// read from disk until a call to [`BlobFile::read`]. /// Remote blob requests share a connection-wide concurrency limit. Set @@ -1395,6 +1408,26 @@ impl Table { self.inner.fetch_blob_files(column.as_ref(), row_ids).await } + /// Open a seekable file from a SQL `blob_descriptor` result. + /// + /// The descriptor carries its table version, branch, column and row identity. + /// Opening does not materialize the payload or change this table's checkout. + /// Remote reads use the table's authenticated HTTP byte-range endpoint. + /// + /// ``` + /// use lancedb::{Table, blob::BlobDescriptor}; + /// + /// # async fn read_header(videos: &Table, descriptor: &BlobDescriptor) -> lancedb::Result<()> { + /// let video = videos.open_blob_file(descriptor).await?; + /// let header = video.read_range(0..video.size().min(4096)).await?; + /// video.close().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn open_blob_file(&self, descriptor: &BlobDescriptor) -> Result { + self.inner.open_blob_file(descriptor).await + } + /// Insert new records into this Table /// /// # Arguments @@ -1562,7 +1595,7 @@ impl Table { } /// See [Table::create_index] - /// For remote tables, this allows an optional wait_timeout to poll until asynchronous indexing is complete + /// In LanceDB Distributed, this allows an optional wait_timeout to poll until asynchronous indexing is complete pub fn create_index_with_timeout( &self, columns: &[impl AsRef], @@ -1843,7 +1876,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 on LanceDB cloud.".into(), + message: "optimize is not supported in LanceDB Distributed.".into(), })?; let prune = optimize::cleanup_old_versions_before( native, @@ -1873,7 +1906,7 @@ impl Table { /// [`freshness`](crate::table::freshness)); everything else is left as /// it is. /// - /// Local tables only: a remote refresh runs as a server job, through + /// LanceDB Embedded only: in LanceDB Distributed a refresh runs as a server job, through /// [`Table::refresh_column_async`]. /// /// ``` @@ -1896,8 +1929,8 @@ impl Table { /// wait returns the durable [`crate::function::RefreshColumnResult`] for /// 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. On local tables the job runs as an - /// in-process task; on LanceDB Cloud and Enterprise it is the server's + /// 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 /// backfill job. /// /// ``` @@ -1923,7 +1956,7 @@ impl Table { /// capped. Filter by job or column through the request; a listing that /// hit its limit reports [`FunctionErrors::truncated`]. /// - /// LanceDB Cloud and Enterprise only, and the caller needs read access + /// LanceDB Distributed only, and the caller needs read access /// to the table, since a message carries the value that failed. /// /// ``` @@ -1984,8 +2017,6 @@ impl Table { /// - `lancedb:description`: for a human-readable description of a field. /// - `lancedb:tag:`: for a user-defined key-value tag, where the suffix /// names the tag category; e.g. `lancedb:tag:model: "clip"`. - /// - `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and - /// `feature_v2` might be in the same logical column. /// - `lancedb:status`: for status options (`production`, `candidate`, /// `deprecated`, `archived`) to designate the current life cycle state of /// this column. @@ -2059,7 +2090,9 @@ impl Table { /// Remove the [`RTEWriteSpec`] from this table, reverting to the standard /// `merge_insert` write path. /// - /// Errors if no spec is currently set. + /// Errors if no spec is currently set, or if the RTE still holds rows that + /// have not been merged into the base table, since removing it would drop + /// them. pub async fn disable_rte(&self) -> Result<()> { self.inner.disable_rte().await } @@ -2278,8 +2311,12 @@ 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. For remote tables, this means the - /// same tokenizer model files must also exist locally. + /// the client process from index metadata. In LanceDB Distributed, 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 + /// missing, this returns an error naming the tokenizer and + /// `LANCE_LANGUAGE_MODEL_HOME`. pub async fn tokenize(&self, query: &str, index_name: &str) -> Result> { let indices = self.inner.list_indices().await?; let matches = indices @@ -2312,8 +2349,9 @@ 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. For remote tables, this means the same tokenizer model - /// files must also exist locally. + /// index metadata. In LanceDB Distributed, 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> { let schema = self.inner.schema().await?; let (column, _) = resolve_arrow_field_path(schema.as_ref(), column)?; @@ -2369,13 +2407,30 @@ impl Table { ), } })?; + let model_backed_tokenizer = serde_json::from_str::(details) + .ok() + .and_then(|details| { + let tokenizer = details.get("base_tokenizer")?.as_str()?.to_string(); + (tokenizer.starts_with("jieba/") || tokenizer.starts_with("lindera/")) + .then_some(tokenizer) + }); tokenize(query, ¶ms).map_err(|err| match err { - Error::InvalidInput { message } => Error::InvalidInput { - message: format!( + Error::InvalidInput { message } => { + let mut message = format!( "{} for full text search index '{}' for {}", message, index.name, selector_description - ), - }, + ); + if let Some(tokenizer) = model_backed_tokenizer { + message.push_str(&format!( + ". tokenize() runs on the client: the '{}' tokenizer is rebuilt \ + in this process from the index metadata, so its model files must \ + be available under LANCE_LANGUAGE_MODEL_HOME and, for remote \ + tables, match the files the server uses", + tokenizer + )); + } + Error::InvalidInput { message } + } err => err, }) } @@ -2383,7 +2438,7 @@ impl Table { /// Get the table URI (storage location) /// /// Returns the full storage location of the table (e.g., S3/GCS path). - /// For remote tables, this fetches the location from the server via describe. + /// In LanceDB Distributed, this fetches the location from the server via describe. pub async fn uri(&self) -> Result { self.inner.uri().await } @@ -2428,7 +2483,7 @@ impl Table { /// Drop an index from the table. /// - /// Note: This is not yet available in LanceDB cloud. + /// Note: This is not yet available in LanceDB Distributed. /// /// 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. @@ -2461,7 +2516,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 on remote tables. + /// supported in LanceDB Distributed. /// /// This call initiates prewarming and returns once the request is accepted. /// It is idempotent and safe to call from multiple clients concurrently — @@ -2808,7 +2863,7 @@ impl NativeTable { /// The registry belongs to this handle, its clones and its branch handles, /// and is not stored with the table: a handle opened separately starts from /// Lance's built-ins. Set it before the handle's first LSM write; writers - /// already open keep the registry they were opened with. Local tables only, + /// already open keep the registry they were opened with. LanceDB Embedded only, /// reached through [`Table::as_native`]. /// /// ``` @@ -3662,7 +3717,7 @@ impl BaseTable for NativeTable { async fn prewarm_data(&self, _columns: Option>) -> Result<()> { Err(Error::NotSupported { - message: "prewarm_data is currently only supported on remote tables.".into(), + message: "prewarm_data is currently only supported in LanceDB Distributed.".into(), }) } @@ -3761,6 +3816,11 @@ impl BaseTable for NativeTable { crate::blob::take_blob_files_aligned(&dataset, column, row_ids).await } + async fn open_blob_file(&self, descriptor: &BlobDescriptor) -> Result { + let dataset = self.dataset.get().await?; + crate::blob::open_native_blob_file(&dataset, descriptor).await + } + /// Delete rows from the table async fn delete(&self, predicate: Predicate<'_>) -> Result { let result = delete::execute_delete(self, predicate).await?; @@ -3789,8 +3849,12 @@ impl BaseTable for NativeTable { Ok(result) } - async fn add_computed_columns(&self, columns: &[(String, String)]) -> Result { - let result = schema_evolution::execute_declare(self, columns).await?; + async fn add_computed_columns( + &self, + columns: &[(String, String)], + options: computed_columns::ComputedColumnOptions, + ) -> Result { + let result = schema_evolution::execute_declare(self, columns, options).await?; self.bump_freshness(); Ok(result) } @@ -3836,10 +3900,7 @@ impl BaseTable for NativeTable { let mut indices: Vec = descriptions .iter() .filter_map(|idx_desc| { - let index_type: crate::index::IndexType = idx_desc - .index_type() - .parse() - .unwrap_or(crate::index::IndexType::Unknown); + let index_type = crate::index::IndexType::from_description(idx_desc.as_ref()); if index_type == crate::index::IndexType::Unknown { // Internal or future index types that this version doesn't recognize // (e.g. Lance's internal FragReuseIndex) are silently excluded from @@ -3975,10 +4036,7 @@ impl BaseTable for NativeTable { return Ok(None); }; - let index_type: crate::index::IndexType = description - .index_type() - .parse() - .unwrap_or(crate::index::IndexType::Unknown); + let index_type = crate::index::IndexType::from_description(description.as_ref()); let is_vector = matches!( index_type, @@ -4276,7 +4334,7 @@ mod tests { assert_eq!(table.name, "test") } - /// The per-row error store is a server feature; a local table says so + /// The per-row error store is a server feature; a LanceDB Embedded table says so /// rather than answering with an empty listing. #[tokio::test] async fn test_function_errors_are_remote_only() { @@ -4296,7 +4354,7 @@ mod tests { .await .unwrap_err(); assert!( - matches!(&err, Error::NotSupported { message } if message.contains("Cloud and Enterprise")), + matches!(&err, Error::NotSupported { message } if message.contains("LanceDB Distributed")), "{err:?}" ); } diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 635a99bea..24329d323 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use lance::dataset::NewColumnTransform; use super::BaseTable; +use super::computed_columns::ComputedColumnOptions; use super::schema_evolution::AddColumnsResult; use crate::function::FunctionApplication; use crate::{Error, Result}; @@ -19,6 +20,7 @@ pub struct AddColumnsBuilder { computed: Vec<(String, String)>, function: Option<(FunctionApplication, Option)>, read_columns: Option>, + options: Option, } impl std::fmt::Debug for AddColumnsBuilder { @@ -41,6 +43,7 @@ impl AddColumnsBuilder { computed: Vec::new(), function: None, read_columns: None, + options: None, } } @@ -66,7 +69,10 @@ impl AddColumnsBuilder { /// renamed, retyped or dropped while a declaration reads it, since the /// expression names it. /// - /// On LanceDB Cloud and Enterprise the expression is planned by the + /// LanceDB Embedded declaration and refresh require the `experimental-functions` + /// Cargo feature. LanceDB Distributed operations do not require this feature. + /// + /// In LanceDB Distributed 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). /// @@ -139,6 +145,26 @@ impl AddColumnsBuilder { self } + /// Configure automatic refresh for every output declared in this call. + /// Settings are stored with the declaration. They require computed or + /// Function columns; LanceDB Embedded persists them without starting a scheduler. + /// + /// ``` + /// # use lancedb::{Table, table::computed_columns::ComputedColumnOptions}; + /// # async fn declare(table: &Table) -> lancedb::Result<()> { + /// table.add_columns().computed("doubled", "x * 2") + /// .computed_options(ComputedColumnOptions { + /// auto_refresh_enabled: true, + /// auto_refresh_interval_seconds: Some(300), + /// }).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn computed_options(mut self, options: ComputedColumnOptions) -> Self { + self.options = Some(options); + self + } + /// Add the columns. pub async fn execute(self) -> Result { let Self { @@ -147,7 +173,18 @@ impl AddColumnsBuilder { computed, function, read_columns, + options, } = self; + if let Some(options) = options { + options.validate()?; + if computed.is_empty() && function.is_none() { + return Err(Error::InvalidInput { + message: "automatic refresh options require computed or Function columns" + .into(), + }); + } + } + let options = options.unwrap_or_default(); let declaration_count = usize::from(!computed.is_empty()) + usize::from(function.is_some()); if transform.is_some() && declaration_count != 0 || declaration_count > 1 { @@ -179,7 +216,7 @@ impl AddColumnsBuilder { .into(), }); } - parent.add_computed_columns(&computed).await + parent.add_computed_columns(&computed, options).await } (None, true, Some((application, output_name))) => { if read_columns.is_some() { @@ -189,7 +226,7 @@ impl AddColumnsBuilder { }); } parent - .add_function_columns(&application, output_name.as_deref()) + .add_function_columns(&application, output_name.as_deref(), options) .await } _ => unreachable!("mixed add_columns modes were rejected above"), @@ -201,6 +238,9 @@ impl AddColumnsBuilder { mod tests { use std::sync::Arc; + use super::ComputedColumnOptions; + use crate::table::computed_columns::AUTO_REFRESH_INTERVAL_META_KEY; + use arrow_array::{Int32Array, RecordBatch, record_batch}; use arrow_schema::{DataType, Field, Schema}; use lance::dataset::{BatchUDF, NewColumnTransform}; @@ -214,6 +254,101 @@ mod tests { conn.create_table(name, batch).execute().await.unwrap() } + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn computed_options_commit_with_declaration() { + let table = table_with_two_columns("options").await; + let version = table.version().await.unwrap(); + let options = ComputedColumnOptions { + auto_refresh_enabled: false, + auto_refresh_interval_seconds: Some(300), + }; + let result = table + .add_columns() + .computed("doubled", "x * 2") + .computed_options(options) + .execute() + .await + .unwrap(); + assert_eq!(result.version, version + 1); + let schema = table.schema().await.unwrap(); + assert_eq!( + ComputedColumnOptions::from_metadata( + schema.field_with_name("doubled").unwrap().metadata() + ) + .unwrap(), + options + ); + for interval in [0, u64::MAX] { + let invalid = ComputedColumnOptions { + auto_refresh_interval_seconds: Some(interval), + ..options + }; + assert!( + table + .add_columns() + .computed("bad", "x") + .computed_options(invalid) + .execute() + .await + .is_err() + ); + } + assert!( + table + .add_columns() + .transform(NewColumnTransform::SqlExpressions(vec![( + "once".into(), + "x".into() + )])) + .computed_options(options) + .execute() + .await + .is_err() + ); + assert!( + table + .schema() + .await + .unwrap() + .field_with_name("bad") + .is_err() + ); + } + + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn omitted_refresh_interval_stays_unset() { + let table = table_with_two_columns("server_interval").await; + let version = table.version().await.unwrap(); + let result = table + .add_columns() + .computed("doubled", "x * 2") + .execute() + .await + .unwrap(); + assert_eq!(result.version, version + 1); + let schema = table.schema().await.unwrap(); + let metadata = schema.field_with_name("doubled").unwrap().metadata(); + assert!(!metadata.contains_key(AUTO_REFRESH_INTERVAL_META_KEY)); + assert_eq!( + ComputedColumnOptions::from_metadata(metadata).unwrap(), + ComputedColumnOptions::default() + ); + assert!( + serde_json::to_value(ComputedColumnOptions::default()) + .unwrap() + .get("auto_refresh_interval_seconds") + .is_none() + ); + } + #[tokio::test] async fn test_requires_a_transform() { let table = table_with_two_columns("no_transform").await; diff --git a/rust/lancedb/src/table/add_data.rs b/rust/lancedb/src/table/add_data.rs index 12404ec73..8c5dc4b45 100644 --- a/rust/lancedb/src/table/add_data.rs +++ b/rust/lancedb/src/table/add_data.rs @@ -45,10 +45,12 @@ pub struct AddResult { #[derive(Debug, Default, Clone, Copy)] pub enum NaNVectorBehavior { - /// Reject any vectors containing NaN values (the default) + /// Reject any vectors containing NaN values or null elements (the default). + /// Whole null vectors are allowed. #[default] Error, - /// Allow NaN values to be added, but they will not be indexed for search + /// Allow NaN values and null elements to be added, but they will not be indexed + /// for search. Keep, } @@ -104,11 +106,12 @@ impl AddDataBuilder { self } - /// Configure how to handle NaN values in vector columns. + /// Configure how to handle NaN values and null elements in vector columns. /// - /// By default, any vectors containing NaN values will be rejected with an - /// error, since NaNs cannot be indexed for search. Setting this to `Keep` - /// will allow NaN values to be added to the table, but they will not be + /// By default, any vectors containing NaN values or null elements will be + /// rejected with an error, since these vectors cannot be indexed for search. + /// Whole null vectors are allowed. Setting this to `Keep` will allow NaN values + /// and null elements to be added to the table, but these vectors will not be /// indexed and will not be searchable. pub fn on_nan_vectors(mut self, behavior: NaNVectorBehavior) -> Self { self.on_nan_vectors = behavior; @@ -149,7 +152,7 @@ impl AddDataBuilder { /// /// The row keeps a reference, so the object has to stay readable. /// [`crate::table::Table::fetch_blobs`] reads from that location. - /// Defaults to `false`. Local tables only. + /// Defaults to `false`. LanceDB Embedded only. pub fn allow_external_blob_outside_bases(mut self, allow: bool) -> Self { self.allow_external_blob_outside_bases = allow; self @@ -953,8 +956,11 @@ mod tests { ); } + #[rstest::rstest] + #[case::nan(Some(f32::NAN))] + #[case::null(None)] #[tokio::test] - async fn test_add_rejects_nan_vectors() { + async fn test_add_rejects_nan_or_null_vectors(#[case] bad_value: Option) { let schema = Arc::new(Schema::new(vec![Field::new( "embedding", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), @@ -974,7 +980,12 @@ mod tests { FixedSizeListArray::try_new( Arc::new(Field::new("item", DataType::Float32, true)), 4, - Arc::new(Float32Array::from(vec![0.1, 0.2, f32::NAN, 0.4])), + Arc::new(Float32Array::from(vec![ + Some(0.1), + Some(0.2), + bad_value, + Some(0.4), + ])), None, ) .unwrap(), @@ -984,8 +995,8 @@ mod tests { let res = table.add(batch.clone()).execute().await; let err = res.unwrap_err(); assert!( - err.to_string().contains("NaN"), - "Expected error mentioning NaN values, but got: {err:?}" + err.to_string().contains("NaN or null"), + "Expected error mentioning NaN or null values, but got: {err:?}" ); table diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 27dad7bd8..45d0e95dc 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -55,6 +55,106 @@ pub const EXPRESSION_META_KEY: &str = "computed_column.expression"; /// Field metadata key holding the column's inputs, as a JSON array of names. pub const INPUTS_META_KEY: &str = "computed_column.inputs"; +/// Whether the server may automatically refresh this output. +pub const AUTO_REFRESH_ENABLED_META_KEY: &str = "computed_column.auto_refresh_enabled"; +/// Minimum interval between successful automatic refreshes, in seconds. +pub const AUTO_REFRESH_INTERVAL_META_KEY: &str = "computed_column.auto_refresh_interval_seconds"; + +/// Scheduling settings persisted on each computed output. LanceDB Embedded +/// stores these settings; automatic scheduling requires LanceDB Distributed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ComputedColumnOptions { + /// Permit automatic refresh. Manual refresh is always available. + pub auto_refresh_enabled: bool, + /// Minimum seconds after a successful refresh before another is eligible. + /// When omitted, the server determines when to refresh. + #[serde(skip_serializing_if = "Option::is_none")] + pub auto_refresh_interval_seconds: Option, +} + +impl Default for ComputedColumnOptions { + fn default() -> Self { + Self { + auto_refresh_enabled: true, + auto_refresh_interval_seconds: None, + } + } +} + +impl ComputedColumnOptions { + /// Reject intervals that cannot be represented by the server scheduler. + pub fn validate(&self) -> Result<()> { + if self + .auto_refresh_interval_seconds + .is_some_and(|interval| interval == 0 || interval.checked_mul(1000).is_none()) + { + return Err(Error::InvalidInput { + message: "auto_refresh_interval_seconds must be a positive integer no greater than u64::MAX / 1000".into(), + }); + } + Ok(()) + } + + /// Read scheduling settings, using defaults for omitted properties. + pub fn from_metadata(metadata: &HashMap) -> Result { + let mut options = Self::default(); + if let Some(value) = metadata.get(AUTO_REFRESH_ENABLED_META_KEY) { + options.auto_refresh_enabled = value.parse().map_err(|_| Error::InvalidInput { + message: "auto_refresh_enabled must be true or false".into(), + })?; + } + if let Some(value) = metadata.get(AUTO_REFRESH_INTERVAL_META_KEY) { + options.auto_refresh_interval_seconds = + Some(value.parse().map_err(|_| Error::InvalidInput { + message: "auto_refresh_interval_seconds must be a positive integer".into(), + })?); + } + options.validate()?; + Ok(options) + } + + /// Attach validated settings to newly declared computed output fields. + pub fn apply_to_schema(&self, schema: &ArrowSchema) -> Result { + self.validate()?; + let fields = schema + .fields() + .iter() + .map(|field| { + if computed_column_from_field(field).is_none() + || field + .metadata() + .get(FUNCTION_OUTPUT_ORDINAL_META_KEY) + .is_some_and(|ordinal| { + ordinal == &FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL.to_string() + }) + { + return field.clone(); + } + let mut metadata = field.metadata().clone(); + metadata.extend(self.metadata()); + Arc::new(field.as_ref().clone().with_metadata(metadata)) + }) + .collect::>(); + Ok(ArrowSchema::new_with_metadata( + fields, + schema.metadata().clone(), + )) + } + + /// Field metadata values shared by native and server declaration paths. + pub fn metadata(&self) -> HashMap { + let mut metadata = HashMap::from([( + AUTO_REFRESH_ENABLED_META_KEY.into(), + self.auto_refresh_enabled.to_string(), + )]); + if let Some(interval) = self.auto_refresh_interval_seconds { + metadata.insert(AUTO_REFRESH_INTERVAL_META_KEY.into(), interval.to_string()); + } + metadata + } +} + /// Field metadata key holding the Function binding identity. pub const FUNCTION_BINDING_ID_META_KEY: &str = "computed_column.function.binding_id"; @@ -391,24 +491,6 @@ pub(crate) fn ensure_supported_function_metadata(schema: &ArrowSchema) -> Result ensure_computed_inputs_acyclic(schema, &bindings) } -/// Refuse `operation` outright on a table with a Function binding. For -/// operations that cannot say which columns they touch; the others use -/// [`ensure_not_function_bound`]. -pub(crate) fn ensure_no_function_bindings_for_mutation( - schema: &ArrowSchema, - operation: &str, -) -> Result<()> { - ensure_supported_function_metadata(schema)?; - if !function_bindings(schema)?.is_empty() { - return Err(Error::NotSupported { - message: format!( - "{operation} is not supported on a table with registered Function bindings" - ), - }); - } - Ok(()) -} - /// Refuse `operation` only when a path in `touched` names a column a Function /// binding depends on: an input's root, an output, or the assignment column. /// A binding stores those columns' exact Arrow fields, so editing one strands it. @@ -2306,6 +2388,111 @@ impl lance_datafusion::utils:: } } +/// Test fixtures for a table carrying a Function binding, shared by the +/// write-path tests. No local path declares a binding, so these stamp one +/// the way the server does. +#[cfg(test)] +pub(crate) mod test_support { + use arrow_array::record_batch; + + use super::{ + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, FUNCTION_BINDINGS_META_KEY, + ensure_supported_function_metadata, function_bindings_metadata, + function_computed_column_metadata, + }; + use crate::Table; + use crate::connect; + use crate::function::FunctionBinding; + + /// A table carrying the fixture binding: `title` and `body` are its + /// inputs, `search_text` and `search_token_count` its outputs, `spare` + /// nobody's. Stamped the way the server does it, since no local path + /// declares a binding. + pub async fn bound_table() -> Table { + let batch = record_batch!( + ("title", Utf8, ["a"]), + ("body", Utf8, ["b"]), + ("search_text", Utf8, ["a b"]), + ("search_token_count", Int64, [2]), + ("spare", Int32, [1]) + ) + .unwrap(); + bound_table_from(batch).await + } + + /// [`bound_table`] over a caller's batch, which must carry `title`, `body`, + /// `search_text` and `search_token_count`. + pub async fn bound_table_from(batch: arrow_array::RecordBatch) -> Table { + let conn = connect("memory://").execute().await.unwrap(); + let table = conn.create_table("bound", batch).execute().await.unwrap(); + stamp_bindings(&table, &[text_features_binding("")]).await; + table + } + + /// The fixture binding, its id and output names suffixed so a table can + /// carry more than one. + pub fn text_features_binding(suffix: &str) -> FunctionBinding { + let raw = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + ); + if suffix.is_empty() { + return FunctionBinding::from_json(raw).unwrap(); + } + FunctionBinding::from_json( + &raw.replace("fb_01K3TEXT", &format!("fb_01K3TEXT{suffix}")) + .replace("search_text", &format!("search_text{suffix}")) + .replace("search_token_count", &format!("search_token_count{suffix}")), + ) + .unwrap() + } + + /// Stamp bindings the way the server does it, since no local path + /// declares one: the envelope on the schema, a declaration marker on + /// every output field. + pub async fn stamp_bindings(table: &Table, bindings: &[FunctionBinding]) { + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + dataset + .update_schema_metadata(vec![( + FUNCTION_BINDINGS_META_KEY.to_string(), + Some(function_bindings_metadata(bindings).unwrap()), + )]) + .await + .unwrap(); + let inputs = ["title".to_string(), "body".to_string()]; + let outputs = bindings + .iter() + .flat_map(|binding| { + let assignment = binding.assignment().map(|assignment| { + ( + assignment.output_name.clone(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + ) + }); + binding + .outputs() + .iter() + .map(|output| (output.output_name.clone(), output.output_ordinal)) + .chain(assignment) + .map(|(name, ordinal)| { + ( + dataset.schema().field(&name).unwrap().id as u32, + function_computed_column_metadata( + binding.binding_id(), + ordinal, + &inputs, + ), + ) + }) + .collect::>() + }) + .collect::>(); + dataset.replace_field_metadata(outputs).await.unwrap(); + native.dataset.update(dataset); + ensure_supported_function_metadata(&table.schema().await.unwrap()).unwrap(); + } +} + #[cfg(test)] mod tests { /// The gate's reproducer: the validator applies the same schema-level @@ -2444,6 +2631,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_declare_infers_type_and_inputs() { let table = table_with_ints("declare_infers").await; let initial = table.version().await.unwrap(); @@ -2511,6 +2702,10 @@ mod tests { /// The binding reaches the schema only if `AllNulls` carries per-field /// metadata through the commit. The whole representation rests on it. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_all_nulls_preserves_field_metadata() { let table = table_with_ints("metadata_survives").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -2535,6 +2730,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_declared_column_is_all_null() { let table = table_with_ints("declare_is_null").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -2559,6 +2758,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_unknown_column_fails_at_declare_time() { let table = table_with_ints("unknown_input").await; let err = add_computed(&table, &[("bad".into(), "missing + 1".into())]) @@ -2571,6 +2774,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_unparsable_expression_fails_at_declare_time() { let table = table_with_ints("bad_syntax").await; let err = add_computed(&table, &[("bad".into(), "x *".into())]) @@ -2591,6 +2798,10 @@ mod tests { /// resolution is missing. When a registry-aware planner exists this /// becomes a supported declaration rather than a new API. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_unregistered_function_is_rejected_for_now() { let table = table_with_ints("udf_not_yet").await; let err = add_computed(&table, &[("vec".into(), "embed(x)".into())]) @@ -2608,6 +2819,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_existing_column_name_is_rejected() { let table = table_with_ints("name_taken").await; let err = add_computed(&table, &[("x".into(), "x * 2".into())]) @@ -2618,6 +2833,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_constant_expression_needs_no_inputs() { let table = table_with_ints("constant").await; add_computed(&table, &[("answer".into(), "42".into())]) @@ -2630,6 +2849,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_multiple_columns_in_one_commit() { let table = table_with_ints("multi").await; let initial = table.version().await.unwrap(); @@ -2652,6 +2875,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_duplicate_declaration_in_one_call_is_rejected() { let table = table_with_ints("dupe").await; let err = add_computed( @@ -2670,6 +2897,10 @@ mod tests { /// A batch may build on itself: one commit, and the later entry's inputs /// name the earlier one. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_declaration_may_read_one_declared_before_it() { let table = table_with_ints("chain").await; let before = table.version().await.unwrap(); @@ -2722,6 +2953,10 @@ mod tests { /// Built-in functions type the column the same way an operator does. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_builtin_function_inference() { let conn = connect("memory://").execute().await.unwrap(); let batch = record_batch!(("name", Utf8, ["ada", "grace"]), ("n", Int32, [-1, 2])).unwrap(); @@ -2772,6 +3007,10 @@ mod tests { /// an ordinary column. Reported as absent it would be refreshable by /// nothing and redeclarable over, silently. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_unrecognized_kind_is_reported_rather_than_hidden() { let table = table_with_ints("foreign_kind").await; super::add_foreign_kind(&table, "embedding", "udf").await; @@ -2815,6 +3054,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_inputs_are_deduplicated_and_sorted() { let conn = connect("memory://").execute().await.unwrap(); let batch = record_batch!(("b", Int32, [1, 2]), ("a", Int32, [3, 4])).unwrap(); @@ -2831,6 +3074,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_dropping_an_input_is_refused() { let table = table_with_ints("drop_input").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -2845,6 +3092,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_renaming_an_input_is_refused() { let table = table_with_ints("rename_input").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -2863,6 +3114,10 @@ mod tests { /// Nothing resolves against nullability, so it is not a rebinding. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_altering_an_input_nullability_is_allowed() { let table = table_with_ints("nullable_input").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -2879,6 +3134,10 @@ mod tests { /// the counting and writing passes, so the declared value is incoherent. /// Refused at declare time. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_volatile_expression_is_refused() { let table = table_with_ints("volatile_expr").await; let err = add_computed(&table, &[("maybe".into(), "random() < 0.5".into())]) @@ -2895,6 +3154,10 @@ mod tests { /// constant, but the stored SQL still names `x`, so the recorded inputs /// must too -- otherwise dropping `x` is allowed and refresh breaks. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_inputs_survive_expression_optimization() { let table = table_with_ints("optimized_inputs").await; add_computed(&table, &[("flag".into(), "true OR x > 0".into())]) @@ -2912,6 +3175,10 @@ mod tests { /// The gate's reproducer: casting a computed column rewrites the field /// without its metadata, silently destroying the declaration. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_retyping_the_computed_column_is_refused() { use arrow_schema::DataType as ArrowDataType; @@ -2936,6 +3203,10 @@ mod tests { /// A declaration cannot be edited, fabricated or erased through field /// metadata: it is validated as a whole at declare time. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_declaration_metadata_is_immutable() { use crate::table::FieldMetadataUpdate; @@ -2983,6 +3254,10 @@ mod tests { /// The gate's reproducer: only refresh materializes a declared column; /// a direct write would store an arbitrary durable value. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_computed_column_cannot_be_written_directly() { let table = table_with_ints("direct_write").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -3018,6 +3293,10 @@ mod tests { /// The gate's reproducer: the reciprocal of the declare-under-spec check. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_installing_an_lsm_spec_over_computed_columns_is_refused() { use crate::table::RTEWriteSpec; @@ -3086,6 +3365,10 @@ mod tests { /// The gate's reproducer: SQL INSERT is a write path too. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_sql_insert_cannot_write_a_computed_column() { use datafusion::prelude::SessionContext; @@ -3185,6 +3468,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_sql_insert_omitting_computed_is_allowed() { use datafusion::prelude::SessionContext; @@ -3211,6 +3498,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_nested_computed_field_cannot_be_renamed() { let table = table_with_ints("computed_struct_rename").await; add_computed(&table, &[("payload".into(), "named_struct('a', x)".into())]) @@ -3229,6 +3520,10 @@ mod tests { /// Stale handles must not commit the computed/RTE state in either order. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_stale_handles_cannot_mix_computed_and_lsm() { use crate::table::RTEWriteSpec; @@ -3275,10 +3570,13 @@ mod tests { assert!(matches!(err, Error::NotSupported { .. }), "declare won"); } - /// The gate's reproducer: after catch-up activation, an LSM write, and - /// unset, retained SSTable rows survive without a live spec. The catch-up - /// flag is the durable marker; declaration refuses on it. + /// Rows written through the RTE keep the spec installed, since + /// `disable_rte` refuses while they are unmerged, so declaration refuses. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_unset_with_retained_lsm_rows_cannot_admit_a_declaration() { use crate::table::RTEWriteSpec; use arrow_array::Int64Array; @@ -3314,7 +3612,8 @@ mod tests { .when_not_matched_insert_all() .use_rte(true); merge.execute(batch).await.unwrap(); - table.disable_rte().await.unwrap(); + // The RTE holds the written rows, so unsetting it is refused. + table.disable_rte().await.unwrap_err(); let err = add_computed(&table, &[("doubled".into(), "value * 2".into())]) .await @@ -3327,6 +3626,10 @@ mod tests { /// A declaration does not read itself, so it travels with its binding. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_dropping_the_computed_column_is_allowed() { let table = table_with_ints("drop_computed").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -4467,6 +4770,10 @@ mod tests { /// downstream binding's immutable input schema must not record them, or /// the first upstream refresh strands the table. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_computed_input_survives_upstream_refresh() { use arrow_array::{Int32Array, Int64Array, RecordBatch}; diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 3ac759bdd..1795b778e 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -355,7 +355,10 @@ impl NativeTable { index.sample_rate, index.max_iterations, ); - let rq_params = RQBuildParams::new(index.num_bits.unwrap_or(1) as u8); + let rq_params = index + .num_bits + .map(|num_bits| RQBuildParams::new(num_bits as u8)) + .unwrap_or_default(); let lance_idx_params = VectorIndexParams::with_ivf_rq_params( index.distance_type.into(), ivf_params, diff --git a/rust/lancedb/src/table/datafusion.rs b/rust/lancedb/src/table/datafusion.rs index 39f3cd4c6..81df7d300 100644 --- a/rust/lancedb/src/table/datafusion.rs +++ b/rust/lancedb/src/table/datafusion.rs @@ -4,6 +4,7 @@ //! This module contains adapters to allow LanceDB tables to be used as DataFusion table providers. mod blob_coerce; +mod blob_nulls; pub mod cast; pub mod insert; pub mod reject_nan; @@ -25,10 +26,14 @@ use datafusion_physical_plan::{ }; use futures::{TryFutureExt, TryStreamExt}; use lance::dataset::{WriteMode, WriteParams}; +use lance_core::{ + ROW_ADDR, ROW_ADDR_FIELD, ROW_ID, ROW_ID_FIELD, + datatypes::{Projection, Schema as LanceSchema}, +}; use super::{AnyQuery, BaseTable}; use crate::{ - Result, + Error, Result, query::{QueryExecutionOptions, QueryFilter, QueryRequest, Select}, }; use arrow_schema::{DataType, Field}; @@ -99,6 +104,16 @@ impl DisplayAs for MetadataEraserExec { } impl ExecutionPlan for MetadataEraserExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "MetadataEraserExec" } @@ -152,8 +167,21 @@ impl ExecutionPlan for MetadataEraserExec { ) } - fn partition_statistics(&self, partition: Option) -> DataFusionResult> { - self.input.partition_statistics(partition) + fn child_stats_requests( + &self, + partition: Option, + ) -> Vec { + vec![datafusion_physical_plan::statistics::ChildStats::At( + partition, + )] + } + + fn statistics_from_inputs( + &self, + input_stats: &[Arc], + _args: &datafusion_physical_plan::statistics::StatisticsArgs, + ) -> DataFusionResult> { + Ok(input_stats[0].clone()) } fn supports_limit_pushdown(&self) -> bool { @@ -161,31 +189,147 @@ impl ExecutionPlan for MetadataEraserExec { } } +/// The blob schema exposed by a [`BaseTableAdapter`]. +/// +/// DataFusion uses one provider schema for both scans and INSERT coercion. +/// Blob descriptors and blob write inputs have different types, so applications +/// that need both can register separate read and write adapters for one table. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum BlobSchema { + /// Expose Blob v2 descriptors (`kind`, `position`, `size`, `blob_id`, `blob_uri`) + /// and legacy v1 descriptors (`position`, `size`). Scans support all blob fields; + /// SQL INSERT into Blob v2 tables is unsupported. + #[default] + Read, + /// Expose Blob v2 write inputs (`data`, `uri`, `position`, `size`) and legacy + /// v1 `LargeBinary` inputs for SQL INSERT. Scans must match the projected + /// provider schema exactly; use [`Self::Read`] to scan blob descriptors or + /// scalar siblings whose projected parent contains a blob. + Write, +} + +/// A DataFusion provider for a LanceDB table. +/// +/// Defaults to [`BlobSchema::Read`], matching the descriptor schema produced by +/// scans without fetching blob bytes. Use [`Self::with_blob_schema`] to enable +/// SQL INSERT into blob columns. Legacy v1 blobs expose descriptors in read mode +/// and `LargeBinary` inputs in write mode; write-mode descriptor scans fail with +/// a schema mismatch. Tables without blob columns behave the same in both modes. #[derive(Debug)] pub struct BaseTableAdapter { table: Arc, + // Only the read schema includes opted-in system/FTS columns. schema: Arc, + write_schema: Arc, + blob_schema: BlobSchema, fts_query: Option, use_rte: Option, } impl BaseTableAdapter { + /// Create an adapter whose schema matches default scans, including blob descriptors. + /// + /// Deriving the descriptor schema does not execute a query or read blob payloads. pub async fn try_new(table: Arc) -> Result { - let schema = table - .schema() - .await? - .as_ref() - .clone() - .with_metadata(HashMap::default()); + let write_schema = table.schema().await?; + let schema = Projection::full(Arc::new(LanceSchema::try_from(write_schema.as_ref())?)) + .to_arrow_schema(); + let schema = blob_nulls::read_schema(&schema).with_metadata(HashMap::default()); + let write_schema = Arc::new( + write_schema + .as_ref() + .clone() + .with_metadata(HashMap::default()), + ); Ok(Self { table, schema: Arc::new(schema), + write_schema, + blob_schema: BlobSchema::Read, fts_query: None, use_rte: None, }) } + /// Choose the schema used by DataFusion for blob columns. + /// + /// [`BlobSchema::Write`] enables INSERT with blob write structs, NULLs, and + /// omitted nullable blobs. Scans requiring blobs fail with + /// "Blob v2 scans require BlobSchema::Read" before execution. Legacy v1 blobs + /// expose `LargeBinary` write inputs, so their descriptor scans fail with a + /// schema mismatch. Write-mode scans are accepted only when the actual schema + /// exactly matches the projected provider schema, including metadata and + /// nullability. No blob payloads are fetched to emulate reads. + /// + /// Scalar projections that exclude blob fields, `COUNT(*)`, and scalar filters + /// remain supported. DataFusion projects whole top-level fields, so selecting + /// `extra.note` also requests its parent `extra`. If that struct contains a blob, + /// even this scalar projection requires [`BlobSchema::Read`], as do computed + /// scalar and window queries that project the same parent. + /// + /// Register a separate read adapter for blob descriptor queries and scalar + /// queries rejected in write mode. A self-insert whose SELECT accesses blobs + /// also fails before writing any rows. + /// Other adapter builders preserve the selected mode. Generated `_rowid`, + /// `_rowaddr`, and `_score` columns are exposed only in read mode. + /// + /// ``` + /// use lancedb::table::datafusion::{BaseTableAdapter, BlobSchema}; + /// + /// # async fn adapter(table: &lancedb::Table) -> lancedb::Result { + /// Ok(BaseTableAdapter::try_new(table.base_table().clone()) + /// .await? + /// .with_blob_schema(BlobSchema::Write)) + /// # } + /// ``` + pub fn with_blob_schema(mut self, blob_schema: BlobSchema) -> Self { + self.blob_schema = blob_schema; + self + } + + /// Expose the requested Lance system columns to DataFusion. + /// + /// Supports [`ROW_ID`] (`_rowid`) and [`ROW_ADDR`] (`_rowaddr`), both nullable + /// `UInt64` fields. Columns are appended in the requested order, skipping any + /// already exposed by this adapter. Other names return [`Error::InvalidInput`]. + /// + /// System columns are hidden by default so existing `SELECT *` queries keep + /// their data-only schema. After opting in, `SELECT *` includes these columns + /// in [`BlobSchema::Read`] mode. The write schema remains data-only for INSERT. + /// + /// ``` + /// use lance_core::{ROW_ADDR, ROW_ID}; + /// use lancedb::table::datafusion::BaseTableAdapter; + /// + /// # async fn adapter(table: &lancedb::Table) -> lancedb::Result { + /// BaseTableAdapter::try_new(table.base_table().clone()) + /// .await? + /// .with_system_columns(&[ROW_ID, ROW_ADDR]) + /// # } + /// ``` + pub fn with_system_columns(mut self, columns: &[impl AsRef]) -> Result { + let mut fields = self.schema.fields().to_vec(); + for column in columns { + let column = column.as_ref(); + let field = match column { + ROW_ID => &*ROW_ID_FIELD, + ROW_ADDR => &*ROW_ADDR_FIELD, + _ => { + return Err(Error::InvalidInput { + message: format!("Unsupported system column: {column}"), + }); + } + }; + if !fields.iter().any(|field| field.name() == column) { + fields.push(Arc::new(field.clone())); + } + } + self.schema = Arc::new(ArrowSchema::new(fields)); + Ok(self) + } + /// Set the RTE read routing of every scan; see [`QueryRequest::use_rte`]. pub fn with_use_rte(mut self, use_rte: Option) -> Self { self.use_rte = use_rte; @@ -193,6 +337,8 @@ impl BaseTableAdapter { } /// Create a new adapter with an FTS query applied. + /// + /// The generated `_score` column is exposed only in [`BlobSchema::Read`] mode. pub fn with_fts_query(&self, fts_query: FullTextSearchQuery) -> Self { // Add _score column to the schema let score_field = Field::new("_score", DataType::Float32, true); @@ -203,16 +349,28 @@ impl BaseTableAdapter { Self { table: self.table.clone(), schema, + write_schema: self.write_schema.clone(), + blob_schema: self.blob_schema, fts_query: Some(fts_query), use_rte: self.use_rte, } } } +fn blob_scan_error() -> DataFusionError { + DataFusionError::Plan( + "Blob v2 scans require BlobSchema::Read; use a separate read adapter for blob fields" + .into(), + ) +} + #[async_trait] impl TableProvider for BaseTableAdapter { fn schema(&self) -> Arc { - self.schema.clone() + match self.blob_schema { + BlobSchema::Read => self.schema.clone(), + BlobSchema::Write => self.write_schema.clone(), + } } fn table_type(&self) -> TableType { @@ -226,8 +384,18 @@ impl TableProvider for BaseTableAdapter { filters: &[Expr], limit: Option, ) -> DataFusionResult> { - // For FTS queries, disable auto-projection of _score to match DataFusion expectations - let disable_scoring = self.fts_query.is_some() && projection.is_some(); + // Check directly supplied filters too, not just optimizer pushdown calls. + if self.blob_schema == BlobSchema::Write { + for filter in filters { + if blob_nulls::references_descriptor(filter, &self.schema)? { + return Err(blob_scan_error()); + } + } + } + // The writer never advertises _score. For readers, an explicit projection + // controls whether it is included, rather than FTS auto-projection. + let disable_scoring = self.fts_query.is_some() + && (projection.is_some() || self.blob_schema == BlobSchema::Write); let mut query = QueryRequest { full_text_search: self.fts_query.clone(), @@ -236,12 +404,22 @@ impl TableProvider for BaseTableAdapter { ..Default::default() }; + let provider_schema = self.schema(); if let Some(projection) = projection { let field_names = projection .iter() - .map(|i| self.schema.field(*i).name().clone()) + .map(|i| provider_schema.field(*i).name().clone()) .collect(); query.select = Select::Columns(field_names); + } else { + // Select::All excludes system columns, which may be part of our schema. + query.select = Select::Columns( + provider_schema + .fields() + .iter() + .map(|field| field.name().clone()) + .collect(), + ); } if !filters.is_empty() { let first = filters.first().unwrap().clone(); @@ -267,14 +445,57 @@ impl TableProvider for BaseTableAdapter { .create_plan(&AnyQuery::Query(query), options) .map_err(|err| DataFusionError::External(err.into())) .await?; - Ok(Arc::new(MetadataEraserExec::new(plan))) + let plan = blob_nulls::mask_plan(plan)?; + let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + if self.blob_schema == BlobSchema::Write { + let schema = match projection { + Some(projection) => Arc::new(provider_schema.project(projection)?), + None => provider_schema, + }; + // Compare the full schemas, including field metadata and nullability. + // A scan must satisfy its advertised contract before it is returned + // to DataFusion; later projections cannot repair a mismatched scan. + if plan.schema() != schema { + if plan + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + { + return Err(blob_scan_error()); + } + return Err(arrow_schema::ArrowError::SchemaError(format!( + "Scan schema mismatch: expected {schema:?}, got {:?}", + plan.schema() + )) + .into()); + } + } + Ok(plan) } fn supports_filters_pushdown( &self, filters: &[&Expr], ) -> DataFusionResult> { - Ok(vec![TableProviderFilterPushDown::Exact; filters.len()]) + // Lance evaluates pushed filters before the descriptor validity mask. + // Keep predicates touching blobs above that mask, including IS NULL: + // the stored descriptor's children are not independently nullable. + filters + .iter() + .map(|filter| { + Ok( + if blob_nulls::references_descriptor(filter, &self.schema)? { + if self.blob_schema == BlobSchema::Write { + return Err(blob_scan_error()); + } + TableProviderFilterPushDown::Unsupported + } else { + TableProviderFilterPushDown::Exact + }, + ) + }) + .collect() } fn statistics(&self) -> Option { @@ -288,6 +509,17 @@ impl TableProvider for BaseTableAdapter { input: Arc, insert_op: InsertOp, ) -> DataFusionResult> { + if self.blob_schema == BlobSchema::Read + && self + .schema + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + { + return Err(DataFusionError::NotImplemented( + "SQL INSERT into Blob v2 tables requires BlobSchema::Write".into(), + )); + } let mode = match insert_op { InsertOp::Append => WriteMode::Append, InsertOp::Overwrite => WriteMode::Overwrite, @@ -319,6 +551,7 @@ pub mod tests { BinaryArray, Float64Array, Int32Array, Int64Array, RecordBatch, StringArray, UInt32Array, }; use arrow_schema::{DataType, Field, Schema}; + use arrow_select::concat::concat_batches; use datafusion::{ datasource::provider_as_source, prelude::{SessionConfig, SessionContext}, @@ -328,11 +561,13 @@ pub mod tests { use datafusion_execution::SendableRecordBatchStream; use datafusion_expr::{LogicalPlan, LogicalPlanBuilder, col, lit}; use futures::{StreamExt, TryStreamExt}; + use lance_core::{ROW_ADDR, ROW_ADDR_FIELD, ROW_ID, ROW_ID_FIELD}; use tempfile::tempdir; use crate::{ connect, index::{Index, scalar::BTreeIndexBuilder}, + query::{ExecutableQuery, Query, QueryBase, Select}, table::datafusion::BaseTableAdapter, }; @@ -509,6 +744,518 @@ pub mod tests { } } + fn inline_blob_input(values: Vec>) -> arrow_array::ArrayRef { + use arrow_array::{Array, LargeBinaryArray, StructArray, UInt64Array}; + + let data = LargeBinaryArray::from(values); + let len = data.len(); + let nulls = data.nulls().cloned(); + let DataType::Struct(fields) = crate::blob("payload", true).data_type().clone() else { + unreachable!() + }; + Arc::new(StructArray::new( + fields, + vec![ + Arc::new(data), + Arc::new(StringArray::new_null(len)), + Arc::new(UInt64Array::new_null(len)), + Arc::new(UInt64Array::new_null(len)), + ], + nulls, + )) + } + + #[tokio::test] + async fn test_blob_schema_builders_preserve_modes_and_system_columns() { + use super::BlobSchema; + + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = db + .create_empty_table( + "docs", + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + crate::blob("payload", true), + ])), + ) + .execute() + .await + .unwrap(); + let adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write) + .with_system_columns(&[ROW_ID]) + .unwrap() + .with_use_rte(Some(false)) + .with_fts_query(lance_index::scalar::FullTextSearchQuery::new( + "hello".into(), + )) + .with_system_columns(&[ROW_ADDR]) + .unwrap(); + assert_eq!(adapter.blob_schema, BlobSchema::Write); + assert_eq!(adapter.use_rte, Some(false)); + assert!(adapter.fts_query.is_some()); + let names = adapter + .schema() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>() + .join(","); + assert_eq!(names, "id,payload"); + let DataType::Struct(fields) = adapter.schema().field(1).data_type().clone() else { + unreachable!() + }; + assert!(fields.find("data").is_some()); + let adapter = adapter.with_blob_schema(BlobSchema::Read); + assert_eq!( + adapter + .schema() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>(), + ["id", "payload", "_rowid", "_score", "_rowaddr"] + ); + let DataType::Struct(fields) = adapter.schema().field(1).data_type().clone() else { + unreachable!() + }; + assert!(fields.find("kind").is_some()); + assert_eq!(adapter.schema().fields().len(), 5); + } + + #[tokio::test] + async fn test_sql_blob_descriptor_nulls() { + use arrow_array::{UInt8Array, UInt64Array}; + use arrow_select::concat::concat_batches; + + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let blobs = inline_blob_input(vec![Some(b"hello"), Some(b""), None]); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + crate::blob("payload", true), + ])), + vec![Arc::new(Int32Array::from(vec![1, 2, 3])), blobs], + ) + .unwrap(); + let table = db.create_table("docs", batch).execute().await.unwrap(); + let adapter = Arc::new( + BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(), + ); + let ctx = SessionContext::new_with_config(SessionConfig::new().with_batch_size(2)); + ctx.register_table("docs", adapter.clone()).unwrap(); + + let batches = ctx + .sql("SELECT id, payload.kind, payload.position, payload.size, payload.blob_id, payload.blob_uri FROM docs ORDER BY id") + .await.unwrap().collect().await.unwrap(); + let batch = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!(batch.num_rows(), 3); + assert_eq!( + batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(), + &UInt8Array::from(vec![Some(0), Some(0), None]) + ); + assert_eq!( + batch + .column(3) + .as_any() + .downcast_ref::() + .unwrap(), + &UInt64Array::from(vec![Some(5), Some(0), None]) + ); + for column in &batch.columns()[1..] { + assert!(!column.is_null(0)); + assert!(!column.is_null(1)); + assert!(column.is_null(2)); + } + + for (predicate, expected) in [ + ("payload.size = 0", vec![2]), + ("payload.kind = 0", vec![1, 2]), + ("payload.blob_uri = ''", vec![1, 2]), + ("payload.size IS NULL", vec![3]), + ("payload.size IS NOT NULL", vec![1, 2]), + ("payload.kind IS NULL", vec![3]), + ("payload.position IS NULL", vec![3]), + ("payload.blob_id IS NULL", vec![3]), + ("payload.blob_uri IS NULL", vec![3]), + ("payload IS NULL", vec![3]), + ("payload.size = 0 OR payload.size IS NULL", vec![2, 3]), + ("id > 1 AND payload.size = 0", vec![2]), + ] { + let batches = ctx + .sql(&format!( + "SELECT id FROM docs WHERE {predicate} ORDER BY id" + )) + .await + .unwrap() + .collect() + .await + .unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect(); + assert_eq!(ids, expected, "{predicate}"); + } + + let batches = ctx + .sql("SELECT id FROM docs WHERE payload.size IS NULL LIMIT 1") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 3 + ); + let batches = ctx + .sql("SELECT COUNT(*), COUNT(payload.size) FROM docs") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 3 + ); + assert_eq!( + batches[0] + .column(1) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 2 + ); + assert!(ctx.sql("SELECT payload.data FROM docs").await.is_err()); + + // Whole-struct scans must agree with the declared schema too. + let plan = adapter.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), adapter.schema()); + + // Opted-in system columns must compose with the descriptor schema and mask. + let adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID, ROW_ADDR]) + .unwrap(); + let plan = adapter.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), adapter.schema()); + let expected = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + let expected = concat_batches(&adapter.schema(), &expected).unwrap(); + ctx.register_table("docs_with_system_columns", Arc::new(adapter)) + .unwrap(); + let batches = ctx + .sql("SELECT _rowaddr, _rowid, id FROM docs_with_system_columns WHERE payload.size IS NULL") + .await + .unwrap() + .collect() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + let columns = + [ROW_ADDR, ROW_ID, "id"].map(|name| expected.schema().index_of(name).unwrap()); + assert_eq!(actual, expected.project(&columns).unwrap().slice(2, 1)); + } + + #[tokio::test] + async fn test_nested_blob_sibling_filter_pushdown() { + use arrow_array::{Array, StructArray}; + + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let blobs = inline_blob_input(vec![Some(b"hello"), None, Some(b"")]); + let fields = vec![ + Arc::new(Field::new("note", DataType::Utf8, false)), + Arc::new(crate::blob("clip", true)), + Arc::new(Field::new("note.with.dot", DataType::Utf8, false)), + ]; + let extra = StructArray::new( + fields.into(), + vec![ + Arc::new(StringArray::from(vec!["note 7", "note 8", "note 9"])), + blobs, + Arc::new(StringArray::from(vec!["a", "b", "c"])), + ], + None, + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("extra", extra.data_type().clone(), false), + ])), + vec![Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(extra)], + ) + .unwrap(); + let table = db.create_table("docs", batch).execute().await.unwrap(); + let adapter = Arc::new( + BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(), + ); + let ctx = SessionContext::new(); + ctx.register_table("docs", adapter).unwrap(); + + for (predicate, pushed, expected) in [ + ("extra.note = 'note 7'", true, vec![1]), + ("extra.\"note.with.dot\" = 'b'", true, vec![2]), + ("extra.clip.size IS NULL", false, vec![2]), + ("get_field(extra, 'clip', 'size') = 0", false, vec![3]), + ("extra.clip IS NULL", false, vec![2]), + ( + "extra.note = 'note 7' OR extra.clip.size IS NULL", + false, + vec![1, 2], + ), + ] { + let sql = format!("SELECT id FROM docs WHERE {predicate}"); + let explain = ctx + .sql(&format!("EXPLAIN {sql}")) + .await + .unwrap() + .collect() + .await + .unwrap(); + let explain = explain + .iter() + .flat_map(|batch| batch.column(1).as_string::().iter()) + .flatten() + .collect::>() + .join("\n"); + assert_eq!(explain.contains("FilterExec"), !pushed, "{explain}"); + if pushed { + assert!(explain.contains("full_filters=["), "{explain}"); + } + let batches = ctx + .sql(&format!("{sql} ORDER BY id")) + .await + .unwrap() + .collect() + .await + .unwrap(); + let ids = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect::>(); + assert_eq!(ids, expected, "{predicate}"); + } + } + + #[tokio::test] + async fn test_system_columns_opt_in() { + let fixture = TestFixture::new().await; + let ctx = SessionContext::new(); + ctx.register_table("foo", fixture.adapter.clone()).unwrap(); + + let batches = ctx + .sql("SELECT * FROM foo") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(batches[0].num_columns(), 2); + assert_eq!(batches[0].schema(), fixture.adapter.schema()); + for column in [ROW_ID, ROW_ADDR] { + assert!(ctx.sql(&format!("SELECT {column} FROM foo")).await.is_err()); + } + + let adapter = BaseTableAdapter::try_new(fixture.adapter.table.clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ADDR, ROW_ADDR]) + .unwrap(); + assert_eq!(adapter.schema().fields().len(), 3); + assert_eq!(adapter.schema().field(2), &*ROW_ADDR_FIELD); + assert!(adapter.schema().index_of(ROW_ID).is_err()); + + let adapter = adapter + .with_system_columns(&[ROW_ID.to_string(), ROW_ADDR.to_string()]) + .unwrap(); + assert_eq!(adapter.schema().fields().len(), 4); + assert_eq!(adapter.schema().field(3), &*ROW_ID_FIELD); + assert!(adapter.schema().metadata().is_empty()); + + let err = adapter.with_system_columns(&["_unknown"]).unwrap_err(); + assert!(matches!(err, crate::Error::InvalidInput { .. })); + + // Default adapters must remain compatible with INSERT ... SELECT *. + ctx.sql("INSERT INTO foo SELECT * FROM foo") + .await + .unwrap() + .collect() + .await + .unwrap(); + let batches = ctx + .sql("SELECT COUNT(*) FROM foo") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 20 + ); + } + + #[tokio::test] + async fn test_system_columns_sql() { + let fixture = TestFixture::new().await; + let adapter = BaseTableAdapter::try_new(fixture.adapter.table.clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID, ROW_ADDR]) + .unwrap(); + let ctx = SessionContext::new(); + ctx.register_table("foo", Arc::new(adapter)).unwrap(); + + // Compare SQL results with the native query's row IDs and row addresses. + let native = Query::new(fixture.adapter.table.clone()) + .select(Select::columns(&["i", "indexed", ROW_ADDR])) + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let schema = Arc::new( + native[0] + .schema() + .as_ref() + .clone() + .with_metadata(HashMap::new()), + ); + let expected = concat_batches(&schema, &native).unwrap(); + + for columns in [ + vec!["i", ROW_ID], + vec![ROW_ID, "i"], + vec!["i", ROW_ADDR], + vec![ROW_ADDR, "i"], + vec![ROW_ADDR, ROW_ID], + vec![ROW_ID], + vec![ROW_ADDR], + vec!["i", "indexed", ROW_ID, ROW_ADDR], + ] { + let sql = format!("SELECT {} FROM foo ORDER BY i", columns.join(", ")); + let batches = ctx.sql(&sql).await.unwrap().collect().await.unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + let indices = columns + .iter() + .map(|name| schema.index_of(name).unwrap()) + .collect::>(); + assert_eq!(actual, expected.project(&indices).unwrap(), "{sql}"); + } + + let batches = ctx + .sql("SELECT * FROM foo ORDER BY i") + .await + .unwrap() + .collect() + .await + .unwrap(); + let indices = ["i", "indexed", ROW_ID, ROW_ADDR].map(|name| schema.index_of(name).unwrap()); + assert_eq!(batches[0], expected.project(&indices).unwrap()); + + // Filtering on the ID must work even when the ID is not in the output. + let row_id = expected + .column_by_name(ROW_ID) + .unwrap() + .as_primitive::() + .value(3); + let batches = ctx + .sql(&format!("SELECT i FROM foo WHERE _rowid = {row_id}")) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(batches[0], expected.project(&[0]).unwrap().slice(3, 1)); + } + + #[tokio::test] + async fn test_system_columns_scan_without_projection() { + let fixture = TestFixture::new().await; + let adapter = BaseTableAdapter::try_new(fixture.adapter.table.clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ADDR, ROW_ID]) + .unwrap(); + let ctx = SessionContext::new(); + let plan = adapter.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), adapter.schema()); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 10); + for batch in batches { + assert_eq!(batch.schema(), adapter.schema()); + assert_eq!( + batch + .column(2) + .as_primitive::() + .values(), + batch + .column(3) + .as_primitive::() + .values() + ); + } + } + #[tokio::test] async fn test_batch_size() { let fixture = TestFixture::new().await; @@ -674,7 +1421,9 @@ pub mod tests { assert_eq!(physical_plan.name(), "MetadataEraserExec"); - let partition_stats = physical_plan.partition_statistics(None).unwrap(); + let partition_stats = datafusion_physical_plan::statistics::StatisticsContext::new() + .compute(physical_plan.as_ref(), &Default::default()) + .unwrap(); assert!(matches!(partition_stats.num_rows, Precision::Exact(10))); } @@ -768,7 +1517,9 @@ pub mod tests { .await .unwrap(); - let rewired = foo.with_new_children(vec![tbl2.clone()]).unwrap(); + let rewired = + datafusion_physical_plan::replace_children_if_necessary(foo, vec![tbl2.clone()]) + .unwrap(); assert_eq!(rewired.schema(), tbl2.schema()); } } diff --git a/rust/lancedb/src/table/datafusion/blob_nulls.rs b/rust/lancedb/src/table/datafusion/blob_nulls.rs new file mode 100644 index 000000000..5befee5c3 --- /dev/null +++ b/rust/lancedb/src/table/datafusion/blob_nulls.rs @@ -0,0 +1,396 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Apply Blob v2 struct validity before DataFusion extracts descriptor fields. + +use std::fmt; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use arrow_array::{ + Array, ArrayRef, FixedSizeListArray, LargeListArray, ListArray, RecordBatch, StructArray, + cast::AsArray, make_array, +}; +use arrow_buffer::NullBuffer; +use arrow_schema::{DataType, Field, FieldRef, Schema}; +use datafusion_common::{ + Result, + tree_node::{TreeNode, TreeNodeRecursion}, +}; +use datafusion_expr::{ColumnarValue, Expr}; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::{PhysicalExpr, expressions::Column}; +use datafusion_physical_plan::{ExecutionPlan, projection::ProjectionExec}; +use lance_arrow::FieldExt; +use lance_core::datatypes::BlobV2Layout; + +pub(super) fn is_descriptor(field: &Field) -> bool { + field.is_blob() + && matches!(field.data_type(), DataType::Struct(fields) + if BlobV2Layout::classify(fields) == Some(BlobV2Layout::Descriptor)) +} + +pub(super) fn has_descriptor(field: &Field) -> bool { + if is_descriptor(field) { + return true; + } + match field.data_type() { + DataType::Struct(fields) => fields.iter().any(|field| has_descriptor(field)), + DataType::List(item) | DataType::LargeList(item) | DataType::FixedSizeList(item, _) => { + has_descriptor(item) + } + _ => false, + } +} + +/// Resolve static struct accesses without confusing a scalar sibling with the +/// entire root column. Track descriptor ancestors too: `blob.size` is scalar, +/// but still requires the descriptor validity mask before evaluation. +fn referenced_field<'a>(expr: &Expr, schema: &'a Schema) -> Option<(&'a Field, bool)> { + match expr { + Expr::Column(column) => Some((schema.field_with_name(&column.name).ok()?, false)), + Expr::ScalarFunction(call) + if call.func.inner().downcast_ref::().is_some() => + { + let (base, path) = call.args.split_first()?; + let (mut field, mut within_descriptor) = referenced_field(base, schema)?; + for name in path { + let Expr::Literal(name, _) = name else { + return None; + }; + within_descriptor |= is_descriptor(field); + let DataType::Struct(fields) = field.data_type() else { + return None; + }; + field = fields.find(name.try_as_str().flatten()?)?.1; + } + Some((field, within_descriptor)) + } + _ => None, + } +} + +pub(super) fn references_descriptor(expr: &Expr, schema: &Schema) -> Result { + let mut found = false; + expr.apply(|expr| { + if let Some((field, within_descriptor)) = referenced_field(expr, schema) { + if within_descriptor || has_descriptor(field) { + found = true; + return Ok(TreeNodeRecursion::Stop); + } + // The complete path is safe. Do not revisit its root as a whole + // struct, which could contain an unrelated blob sibling. + return Ok(TreeNodeRecursion::Jump); + } + // Unknown/computed paths conservatively visit their arguments. + Ok(TreeNodeRecursion::Continue) + })?; + Ok(found) +} + +fn nullable_descriptor_fields(field: &FieldRef) -> FieldRef { + let data_type = match field.data_type() { + DataType::Struct(fields) if is_descriptor(field) => DataType::Struct( + fields + .iter() + .map(|field| Arc::new(field.as_ref().clone().with_nullable(true))) + .collect(), + ), + DataType::Struct(fields) => { + DataType::Struct(fields.iter().map(nullable_descriptor_fields).collect()) + } + DataType::List(item) => DataType::List(nullable_descriptor_fields(item)), + DataType::LargeList(item) => DataType::LargeList(nullable_descriptor_fields(item)), + DataType::FixedSizeList(item, size) => { + DataType::FixedSizeList(nullable_descriptor_fields(item), *size) + } + _ => return field.clone(), + }; + Arc::new(field.as_ref().clone().with_data_type(data_type)) +} + +pub(super) fn read_schema(schema: &Schema) -> Schema { + Schema::new_with_metadata( + schema + .fields() + .iter() + .map(nullable_descriptor_fields) + .collect::>(), + schema.metadata().clone(), + ) +} + +/// Preserve value buffers, offsets, metadata, and existing child nulls. Only +/// validity buffers are combined; this never materializes blob payloads. +fn mask_array(array: &ArrayRef, field: &Field, ancestors: Option<&NullBuffer>) -> Result { + if !has_descriptor(field) { + return Ok(array.clone()); + } + match field.data_type() { + DataType::Struct(fields) => { + let values = array.as_struct(); + let nulls = NullBuffer::union(values.nulls(), ancestors); + let columns = if is_descriptor(field) { + values + .columns() + .iter() + .map(|column| { + let nulls = NullBuffer::union(column.nulls(), nulls.as_ref()); + Ok(make_array( + column.to_data().into_builder().nulls(nulls).build()?, + )) + }) + .collect::>>()? + } else { + values + .columns() + .iter() + .zip(fields) + .map(|(column, field)| mask_array(column, field, nulls.as_ref())) + .collect::>>()? + }; + Ok(Arc::new(StructArray::try_new_with_length( + fields.clone(), + columns, + nulls, + values.len(), + )?)) + } + DataType::List(item) => { + let list = array.as_list::(); + Ok(Arc::new(ListArray::try_new( + item.clone(), + list.offsets().clone(), + mask_array(list.values(), item, None)?, + list.nulls().cloned(), + )?)) + } + DataType::LargeList(item) => { + let list = array.as_list::(); + Ok(Arc::new(LargeListArray::try_new( + item.clone(), + list.offsets().clone(), + mask_array(list.values(), item, None)?, + list.nulls().cloned(), + )?)) + } + DataType::FixedSizeList(item, size) => { + let list = array.as_fixed_size_list(); + Ok(Arc::new(FixedSizeListArray::try_new( + item.clone(), + *size, + mask_array(list.values(), item, None)?, + list.nulls().cloned(), + )?)) + } + _ => Ok(array.clone()), + } +} + +#[derive(Debug)] +struct MaskBlobNulls { + source: Arc, + field: FieldRef, +} + +impl fmt::Display for MaskBlobNulls { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "mask_blob_nulls({})", self.source) + } +} + +impl PartialEq for MaskBlobNulls { + fn eq(&self, other: &Self) -> bool { + self.source.eq(&other.source) && self.field == other.field + } +} + +impl Eq for MaskBlobNulls {} + +impl Hash for MaskBlobNulls { + fn hash(&self, state: &mut H) { + self.source.hash(state); + self.field.hash(state); + } +} + +impl PhysicalExpr for MaskBlobNulls { + fn return_field(&self, _input_schema: &Schema) -> Result { + Ok(self.field.clone()) + } + + fn evaluate(&self, batch: &RecordBatch) -> Result { + let source = self.source.evaluate(batch)?.into_array(batch.num_rows())?; + Ok(ColumnarValue::Array(mask_array( + &source, + &self.field, + None, + )?)) + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.source] + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + assert_eq!(children.len(), 1); + Ok(Arc::new(Self { + source: children[0].clone(), + field: self.field.clone(), + })) + } + + fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{self}") + } +} + +pub(super) fn mask_plan(input: Arc) -> Result> { + let schema = input.schema(); + if !schema.fields().iter().any(|field| has_descriptor(field)) { + return Ok(input); + } + let expressions = schema + .fields() + .iter() + .enumerate() + .map(|(index, field)| { + let source: Arc = Arc::new(Column::new(field.name(), index)); + let expression: Arc = if has_descriptor(field) { + Arc::new(MaskBlobNulls { + source, + field: nullable_descriptor_fields(field), + }) + } else { + source + }; + (expression, field.name().clone()) + }) + .collect::>(); + Ok(Arc::new(ProjectionExec::try_new(expressions, input)?)) +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::{StringArray, UInt8Array, UInt32Array, UInt64Array}; + use arrow_buffer::OffsetBuffer; + use lance_core::datatypes::BLOB_V2_DESC_FIELD; + + fn descriptor() -> (FieldRef, ArrayRef) { + let field = Arc::new(BLOB_V2_DESC_FIELD.clone().with_nullable(true)); + let field = nullable_descriptor_fields(&field); + let DataType::Struct(fields) = field.data_type() else { + unreachable!() + }; + let array = StructArray::new( + fields.clone(), + vec![ + Arc::new(UInt8Array::from(vec![0; 5])), + Arc::new(UInt64Array::from(vec![10; 5])), + Arc::new(UInt64Array::from(vec![ + Some(9), + Some(5), + Some(0), + Some(0), + None, + ])), + Arc::new(UInt32Array::from(vec![0; 5])), + Arc::new(StringArray::from(vec![""; 5])), + ], + Some(NullBuffer::from(vec![true, true, true, false, true])), + ); + (field, Arc::new(array)) + } + + #[test] + fn test_sliced_descriptor_preserves_child_nulls_and_buffers() { + let (field, array) = descriptor(); + let array = array.slice(1, 4); + let masked = mask_array(&array, &field, None).unwrap(); + let masked = masked.as_struct(); + let size = masked + .column_by_name("size") + .unwrap() + .as_primitive::(); + assert_eq!(size, &UInt64Array::from(vec![Some(5), Some(0), None, None])); + assert_eq!(masked.nulls(), array.nulls()); + for (input, output) in array.as_struct().columns().iter().zip(masked.columns()) { + assert_eq!(input.to_data().buffers(), output.to_data().buffers()); + assert!(output.is_null(2)); + } + + let empty = mask_array(&array.slice(0, 0), &field, None).unwrap(); + assert_eq!(empty.len(), 0); + } + + #[test] + fn test_nested_descriptor_inherits_struct_nulls() { + let (blob_field, array) = descriptor(); + let parent = Arc::new(Field::new( + "parent", + DataType::Struct(vec![blob_field.clone()].into()), + true, + )); + let array: ArrayRef = Arc::new(StructArray::new( + vec![blob_field].into(), + vec![array], + Some(NullBuffer::from(vec![true, false, true, true, true])), + )); + let array = array.slice(1, 3); + let masked = mask_array(&array, &parent, None).unwrap(); + let blob = masked.as_struct().column(0).as_struct(); + assert_eq!( + blob.nulls().unwrap(), + &NullBuffer::from(vec![false, true, false]) + ); + for column in blob.columns() { + assert!(column.is_null(0)); + assert!(!column.is_null(1)); + assert!(column.is_null(2)); + } + } + + #[test] + fn test_list_descriptor_masks_preserve_offsets_and_validity() { + let (item, values) = descriptor(); + let nulls = Some(NullBuffer::from(vec![true, false, true])); + let arrays: Vec = vec![ + Arc::new(ListArray::new( + item.clone(), + OffsetBuffer::new(vec![0, 1, 3, 5].into()), + values.clone(), + nulls.clone(), + )), + Arc::new(LargeListArray::new( + item.clone(), + OffsetBuffer::new(vec![0_i64, 1, 3, 5].into()), + values.clone(), + nulls, + )), + Arc::new(FixedSizeListArray::new(item.clone(), 1, values, None)), + ]; + for array in arrays { + let field = Field::new("blobs", array.data_type().clone(), true); + let masked = mask_array(&array, &field, None).unwrap(); + assert_eq!(masked.nulls(), array.nulls()); + assert_eq!(masked.to_data().buffers(), array.to_data().buffers()); + let values = match masked.data_type() { + DataType::List(_) => masked.as_list::().values(), + DataType::LargeList(_) => masked.as_list::().values(), + DataType::FixedSizeList(_, _) => masked.as_fixed_size_list().values(), + _ => unreachable!(), + }; + for column in values.as_struct().columns() { + assert!(column.is_null(3)); + } + assert_eq!( + mask_array(&array.slice(1, 1), &field, None).unwrap().len(), + 1 + ); + } + } +} diff --git a/rust/lancedb/src/table/datafusion/insert.rs b/rust/lancedb/src/table/datafusion/insert.rs index b9bd2396e..ec1e603d2 100644 --- a/rust/lancedb/src/table/datafusion/insert.rs +++ b/rust/lancedb/src/table/datafusion/insert.rs @@ -141,6 +141,16 @@ impl DisplayAs for InsertExec { } impl ExecutionPlan for InsertExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { Self::static_name() } diff --git a/rust/lancedb/src/table/datafusion/reject_nan.rs b/rust/lancedb/src/table/datafusion/reject_nan.rs index 084c9722b..462216929 100644 --- a/rust/lancedb/src/table/datafusion/reject_nan.rs +++ b/rust/lancedb/src/table/datafusion/reject_nan.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! A DataFusion projection that rejects vectors containing NaN values. +//! A DataFusion projection that rejects vectors containing NaN or null elements. use std::sync::{Arc, LazyLock}; @@ -31,10 +31,12 @@ fn is_vector_field(field: &Field) -> bool { } } -/// Wraps the input plan with a projection that checks vector columns for NaN values. +/// Wraps the input plan with a projection that checks vector columns for NaN or +/// null elements. /// /// Non-vector columns pass through unchanged. Vector columns are wrapped with a -/// UDF that returns the column as-is if no NaNs are present, or errors otherwise. +/// UDF that returns the column as-is if no NaN or null elements are present, or +/// errors otherwise. Whole null vectors pass through unchanged. pub fn reject_nan_vectors(input: Arc) -> Result> { let schema = input.schema(); let config = Arc::new(ConfigOptions::default()); @@ -70,7 +72,7 @@ pub fn reject_nan_vectors(input: Arc) -> Result datafusion_common::Result<()> { ) })?; - // Only inspect elements that are both in a valid parent row and non-null - // themselves. Values backing null parent rows or null child elements may - // contain garbage (including NaN) per the Arrow spec. - let has_nan = (0..fsl.len()).filter(|i| fsl.is_valid(*i)).any(|i| { + // Values backing null parent rows may contain garbage per the Arrow spec. + // A null child in a valid row is an invalid vector component, however: + // pandas can represent NaN components as Arrow nulls. + let has_bad_values = (0..fsl.len()).filter(|i| fsl.is_valid(*i)).any(|i| { let row = fsl.value(i); + if row.null_count() > 0 { + return true; + } match row.data_type() { DataType::Float16 => row .as_any() @@ -150,10 +155,10 @@ fn check_no_nans(array: &dyn Array) -> datafusion_common::Result<()> { } }); - if has_nan { + if has_bad_values { return Err(datafusion_common::DataFusionError::ArrowError( Box::new(arrow_schema::ArrowError::ComputeError( - "Vector column contains NaN values".to_string(), + "Vector column contains NaN or null values".to_string(), )), None, )); @@ -165,7 +170,7 @@ fn check_no_nans(array: &dyn Array) -> datafusion_common::Result<()> { #[cfg(test)] mod tests { use super::*; - use arrow_array::Float32Array; + use arrow_array::{Float16Array, Float32Array, Float64Array}; #[test] fn test_passes_clean_vectors() { @@ -209,23 +214,43 @@ mod tests { } #[test] - fn test_skips_null_elements_within_valid_row() { - // A valid row with null child elements: the underlying buffer may hold - // NaN but the null bitmap says they're absent — should not reject. - let values = Float32Array::from(vec![ - Some(1.0), - None, // null element — buffer may contain NaN - Some(3.0), - None, // null element - ]); + fn test_rejects_null_elements_within_valid_row() { + let arrays: Vec> = vec![ + Arc::new(Float16Array::from(vec![Some(half::f16::ONE), None])), + Arc::new(Float32Array::from(vec![Some(1.0), None])), + Arc::new(Float64Array::from(vec![Some(1.0), None])), + ]; + for values in arrays { + let fsl = FixedSizeListArray::try_new( + Arc::new(Field::new("item", values.data_type().clone(), true)), + 2, + values, + None, + ) + .unwrap(); + let err = check_no_nans(&fsl).unwrap_err(); + assert!(err.to_string().contains("null")); + } + } + + #[test] + fn test_skips_null_elements_in_null_rows_and_outside_slice() { let fsl = FixedSizeListArray::try_new( Arc::new(Field::new("item", DataType::Float32, true)), 2, - Arc::new(values), - None, // both rows are valid + Arc::new(Float32Array::from(vec![ + None, + Some(1.0), + Some(2.0), + Some(3.0), + None, + None, + ])), + Some(vec![true, true, false].into()), ) .unwrap(); - assert!(check_no_nans(&fsl).is_ok()); + assert!(check_no_nans(&fsl.slice(1, 2)).is_ok()); + assert!(check_no_nans(&fsl.slice(0, 2)).is_err()); } #[test] diff --git a/rust/lancedb/src/table/datafusion/scannable_exec.rs b/rust/lancedb/src/table/datafusion/scannable_exec.rs index a5421ac31..77d17a931 100644 --- a/rust/lancedb/src/table/datafusion/scannable_exec.rs +++ b/rust/lancedb/src/table/datafusion/scannable_exec.rs @@ -69,6 +69,16 @@ impl DisplayAs for ScannableExec { } impl ExecutionPlan for ScannableExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "ScannableExec" } diff --git a/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs b/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs index 20de93148..06f9ba6d9 100644 --- a/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs +++ b/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs @@ -507,6 +507,16 @@ impl DisplayAs for DuplicatePairsExec { } impl ExecutionPlan for DuplicatePairsExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "DuplicatePairsExec" } diff --git a/rust/lancedb/src/table/datafusion/udtf/vector_query.rs b/rust/lancedb/src/table/datafusion/udtf/vector_query.rs index 543a59589..6b59a623b 100644 --- a/rust/lancedb/src/table/datafusion/udtf/vector_query.rs +++ b/rust/lancedb/src/table/datafusion/udtf/vector_query.rs @@ -373,6 +373,16 @@ impl DisplayAs for VectorDedupExec { } impl ExecutionPlan for VectorDedupExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "VectorDedupExec" } diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 57a046a87..9e1869376 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -20,7 +20,7 @@ use futures::{FutureExt, StreamExt, TryStreamExt}; use lance::dataset::{ MergeInsertBuilder as LanceMergeInsertBuilder, WhenMatched, WhenNotMatchedBySource, }; -use lance_datafusion::spill::spilling_table_provider; +use lance_datafusion::spill::spilling_table_provider_with_job_disk_manager; use serde::{Deserialize, Serialize}; use super::datafusion::scannable_exec::{ScannableExec, ScannableProvider}; @@ -282,6 +282,21 @@ impl MergeInsertBuilder { canonicalize_merge_filter(self.when_not_matched_by_source_delete_filt.take())?; Ok(()) } + + /// The existing columns a matched row takes from `source`: every source + /// column but the join keys, which a match leaves equal. An insert-only + /// merge rewrites none; its new rows get Function outputs from the next + /// refresh, as appended rows do. + pub(crate) fn function_guarded_columns(&self, source: &Fields) -> Vec { + if !self.when_matched_update_all { + return Vec::new(); + } + source + .iter() + .filter(|field| !self.on.iter().any(|key| key == field.name())) + .map(|field| field.name().clone()) + .collect() + } } fn canonicalize_merge_filter(filter: Option) -> Result> { @@ -370,9 +385,10 @@ pub(crate) async fn execute_merge_insert( ) -> Result { params.canonicalize_filters()?; let schema = table.schema().await?; - super::computed_columns::ensure_no_function_bindings_for_mutation( + super::computed_columns::ensure_not_function_bound( schema.as_ref(), "merge_insert", + params.function_guarded_columns(new_data.schema().fields()), )?; // Normalize blob layouts and JSON extension metadata just as on append. // Keep arrow.json text labelled until Lance encodes it as JSONB. @@ -554,10 +570,14 @@ pub(crate) async fn prepare_merge_source( let prefix_rows = prefix.iter().map(|batch| batch.num_rows()).sum(); let chained = futures::stream::iter(prefix.into_iter().map(Ok)).chain(stream); let chained = Box::pin(RecordBatchStreamAdapter::new(schema, chained)); - let spilled = spilling_table_provider(chained, SPILL_MEMORY_LIMIT_BYTES).await?; - let spilled = spilled - .scan(&SessionContext::new().state(), None, &[], None) - .await?; + let ctx = SessionContext::new(); + let spilled = spilling_table_provider_with_job_disk_manager( + chained, + SPILL_MEMORY_LIMIT_BYTES, + ctx.runtime_env().disk_manager.clone(), + ) + .await?; + let spilled = spilled.scan(&ctx.state(), None, &[], None).await?; let plan = Arc::new(RowCountLowerBoundExec::new(spilled, prefix_rows)); Ok(MergeSource::Provider(Arc::new(ScannableProvider::new( plan, @@ -596,6 +616,17 @@ impl ExecutionPlan for RowCountLowerBoundExec { vec![&self.input] } + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } + fn with_new_children( self: Arc, mut children: Vec>, @@ -901,7 +932,10 @@ mod tests { .scan(&SessionContext::new().state(), None, &[], None) .await .unwrap(); - let num_rows = plan.partition_statistics(None).unwrap().num_rows; + let num_rows = datafusion_physical_plan::statistics::StatisticsContext::new() + .compute(plan.as_ref(), &Default::default()) + .unwrap() + .num_rows; let batches: Vec = execute_stream(plan, Arc::new(TaskContext::default())) .unwrap() .try_collect() @@ -1284,6 +1318,87 @@ mod tests { assert_eq!(result.num_deleted_rows, (ROW_COUNT - 1) as u64); assert_eq!(table.count_rows(None).await.unwrap(), 1); } + + fn reader(batch: RecordBatch) -> Box { + let schema = batch.schema(); + Box::new(RecordBatchIterator::new(vec![Ok(batch)], schema)) + } + + /// Inserting rows through a merge is an append: the new rows' Function + /// outputs come from the next refresh, so a binding does not refuse it. + #[tokio::test] + async fn merge_insert_only_is_allowed_on_a_function_table() { + let table = crate::table::computed_columns::test_support::bound_table_from( + arrow_array::record_batch!( + ("id", Int32, [1]), + ("note", Utf8, ["n"]), + ("title", Utf8, ["a"]), + ("body", Utf8, ["b"]), + ("search_text", Utf8, ["a b"]), + ("search_token_count", Int64, [2]) + ) + .unwrap(), + ) + .await; + let mut merge = table.merge_insert(&["id"]); + merge.when_not_matched_insert_all(); + let result = merge + .execute(reader( + arrow_array::record_batch!( + ("id", Int32, [2]), + ("note", Utf8, ["m"]), + ("title", Utf8, ["c"]), + ("body", Utf8, ["d"]) + ) + .unwrap(), + )) + .await + .unwrap(); + assert_eq!(result.num_inserted_rows, 1); + assert_eq!(table.count_rows(None).await.unwrap(), 2); + } + + /// A matched row takes every non-key source column, so the merge is + /// refused only when one of those is a binding's input or output. + #[tokio::test] + async fn merge_update_on_a_function_table_refuses_only_bound_columns() { + let table = crate::table::computed_columns::test_support::bound_table_from( + arrow_array::record_batch!( + ("id", Int32, [1]), + ("note", Utf8, ["n"]), + ("title", Utf8, ["a"]), + ("body", Utf8, ["b"]), + ("search_text", Utf8, ["a b"]), + ("search_token_count", Int64, [2]) + ) + .unwrap(), + ) + .await; + let mut merge = table.merge_insert(&["id"]); + merge.when_matched_update_all(None); + let result = merge + .execute(reader( + arrow_array::record_batch!(("id", Int32, [1]), ("note", Utf8, ["m"])).unwrap(), + )) + .await + .unwrap(); + assert_eq!(result.num_updated_rows, 1); + + let mut merge = table.merge_insert(&["id"]); + merge.when_matched_update_all(None); + let err = merge + .execute(reader( + arrow_array::record_batch!(("id", Int32, [1]), ("title", Utf8, ["z"])).unwrap(), + )) + .await + .unwrap_err(); + assert!( + matches!(&err, crate::Error::InvalidInput { message } + if message.contains("merge_insert of 'title'") + && message.contains("a Function binding reads or writes it")), + "{err:?}" + ); + } } #[cfg(test)] @@ -1751,6 +1866,132 @@ mod lsm_tests { ); } + /// Another process re-initializing the MemWAL retires this process's + /// cached writer: its rows are not read, and the next write opens a + /// writer for the new MemWAL. + /// + /// `disable_rte` refuses while the writer holds rows, so the MemWAL index + /// is dropped through Lance directly, standing in for a write that lands + /// after that check. The writer's rows are lost to the base table either + /// way; what this pins is that they are not served from a directory the + /// index no longer names. + #[tokio::test] + async fn lsm_writer_of_a_retired_mem_wal_is_replaced() { + use lance::index::DatasetIndexExt; + + let dir = tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let conn = connect(uri) + .read_consistency_interval(std::time::Duration::ZERO) + .execute() + .await + .unwrap(); + let table = conn + .create_table("t", id_value_reader(vec![1, 2, 3])) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + lsm_upsert(&table, vec![4, 5]).await; + let retired_dir_id = mem_wal_dir_id(&table).await; + + let mut dataset = lance::Dataset::open(&table.uri().await.unwrap()) + .await + .unwrap(); + dataset + .drop_index(lance_index::mem_wal::MEM_WAL_INDEX_NAME) + .await + .unwrap(); + let other = connect(uri) + .execute() + .await + .unwrap() + .open_table("t") + .execute() + .await + .unwrap(); + other.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + let dir_id = mem_wal_dir_id(&table).await; + assert_ne!(dir_id, retired_dir_id); + + let ids = || async { + let rows = collect_id_value(table.query().execute().await.unwrap()).await; + rows.into_iter().map(|(id, _)| id).collect::>() + }; + assert_eq!(ids().await, vec![1, 2, 3]); + + lsm_upsert(&table, vec![6]).await; + assert_eq!(ids().await, vec![1, 2, 3, 6]); + let native = table.as_native().unwrap(); + assert!( + native + .dataset + .shard_writer() + .read_snapshot(&dir_id) + .await + .unwrap() + .is_some(), + "the write opened a writer for the new MemWAL" + ); + } + + /// `disable_rte` refuses while the MemWAL holds rows the base table does + /// not, since a MemWAL installed later would not read them. + #[tokio::test] + async fn lsm_disable_is_refused_while_rows_are_unmerged() { + let dir = tempdir().unwrap(); + let table = id_value_table(&dir).await; + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + lsm_upsert(&table, vec![4, 5]).await; + + let err = table.disable_rte().await.unwrap_err(); + assert!( + err.to_string() + .contains("not been merged into the base table"), + "unexpected error: {err}" + ); + assert_eq!( + table.get_rte_spec().await.unwrap(), + Some(RTEWriteSpec::unsharded()) + ); + let rows = collect_id_value(table.query().execute().await.unwrap()).await; + assert_eq!( + rows.into_iter().map(|(id, _)| id).collect::>(), + vec![1, 2, 3, 4, 5] + ); + } + + /// Rows another process's writer has acknowledged but not flushed are in + /// its WAL only, and still refuse `disable_rte`. + #[tokio::test] + async fn lsm_disable_is_refused_while_another_writer_holds_rows() { + let dir = tempdir().unwrap(); + let table = id_value_table(&dir).await; + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + lsm_upsert(&table, vec![4, 5]).await; + + let other = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap() + .open_table("t") + .execute() + .await + .unwrap(); + let err = other.disable_rte().await.unwrap_err(); + assert!( + err.to_string().contains("0 SSTable(s) not merged") + && !err.to_string().contains(" 0 WAL entry(ies) not flushed"), + "unexpected error: {err}" + ); + let rows = collect_id_value(table.query().execute().await.unwrap()).await; + assert_eq!( + rows.into_iter().map(|(id, _)| id).collect::>(), + vec![1, 2, 3, 4, 5] + ); + } + #[tokio::test] async fn base_table_adapter_use_rte_false_scans_the_base_only() { use crate::table::datafusion::BaseTableAdapter; @@ -2026,9 +2267,10 @@ mod lsm_tests { /// A spec is replaced by unsetting it and setting the new one. /// - /// `disable_rte` drains the open writer, so the rows it held - /// survive the replacement, and the writer the next write opens builds its - /// MemTables from the new set. + /// The writer the next write opens builds its MemTables from the new set. + /// Unsetting is refused while the MemWAL holds unmerged rows (see + /// `lsm_disable_is_refused_while_rows_are_unmerged`), so nothing is + /// written before the replacement. #[tokio::test] async fn lsm_spec_is_replaced_by_unsetting_it_first() { use crate::index::Index; @@ -2043,13 +2285,11 @@ mod lsm_tests { .unwrap(); let fts_index = table.list_indices().await.unwrap()[0].name.clone(); - // Installed maintaining nothing, then written to: the writer opens with - // no FTS index. + // Installed maintaining nothing. table .enable_rte(RTEWriteSpec::unsharded().with_maintained_indexes(Vec::new())) .await .unwrap(); - upsert_text(&table, vec![(99, "zebra")]).await; // Setting over an installed spec is refused; unset, then set. let err = table @@ -2435,7 +2675,7 @@ mod lsm_tests { } fn training_criteria(&self) -> lance_index::scalar::registry::TrainingCriteria { use lance_index::scalar::registry::{TrainingCriteria, TrainingOrdering}; - TrainingCriteria::new(TrainingOrdering::Values).with_row_id() + TrainingCriteria::new(TrainingOrdering::Values).with_row_addr() } fn validate( &self, @@ -2479,24 +2719,8 @@ mod lsm_tests { &self, ctx: &lance::dataset::mem_wal::index::FlushContext<'_>, ) -> lance_core::Result { - // BTree now trains on row addresses, while Bitmap still takes row IDs. - // These coincide in the flushed generation, which uses physical IDs. - assert!(!ctx.generation()?.dataset.manifest().uses_stable_row_ids()); - let batches = self - .0 - .to_training_batches(ctx.batch_size)? - .into_iter() - .map(|batch| { - assert_eq!(batch.schema().field(1).name(), lance_core::ROW_ADDR); - let schema = Arc::new(Schema::new(vec![ - batch.schema().field(0).clone(), - Field::new(lance_core::ROW_ID, DataType::UInt64, false), - ])); - RecordBatch::try_new(schema, batch.columns().to_vec()) - }) - .collect::, _>>()?; Ok(lance::dataset::mem_wal::index::FlushOutcome::from_batches( - batches, + self.0.to_training_batches(ctx.batch_size)?, )) } } @@ -2583,7 +2807,7 @@ mod lsm_tests { .unwrap() .dataset .shard_writer() - .read_snapshot() + .read_snapshot(&mem_wal_dir_id(&table).await) .await .unwrap() .expect("the merge opened a writer"); @@ -2602,6 +2826,20 @@ mod lsm_tests { assert_sstables_answer_through_region_bitmap(&table, vec![10, 11]).await; } + /// The `dir_id` of the table's current MemWAL, read from storage. + async fn mem_wal_dir_id(table: &Table) -> String { + use lance::dataset::mem_wal::DatasetMemWalExt; + + lance::Dataset::open(&table.uri().await.unwrap()) + .await + .unwrap() + .mem_wal_index_details() + .await + .unwrap() + .expect("the table has a MemWAL") + .dir_id + } + /// The SSTables each shard's manifest publishes. async fn published_sstables(table: &Table) -> Vec { use lance::dataset::mem_wal::ShardManifestStore; @@ -2610,13 +2848,15 @@ mod lsm_tests { let (store, base) = lance_io::object_store::ObjectStore::from_uri(&uri) .await .unwrap(); - let mem_wal = std::path::Path::new(&uri).join("_mem_wal"); + let dir_id = mem_wal_dir_id(table).await; + let mem_wal = std::path::Path::new(&uri) + .join(lance::dataset::mem_wal::util::mem_wal_dir_name(&dir_id)); let mut sstables = Vec::new(); for shard in std::fs::read_dir(&mem_wal).unwrap() { let Ok(shard_id) = shard.unwrap().file_name().to_string_lossy().parse() else { continue; }; - let manifest = ShardManifestStore::new(store.clone(), &base, shard_id, 2) + let manifest = ShardManifestStore::new(store.clone(), &base, &dir_id, shard_id, 2) .latest() .await .unwrap() @@ -2731,7 +2971,7 @@ mod lsm_tests { .unwrap() .dataset .shard_writer() - .read_snapshot() + .read_snapshot(&mem_wal_dir_id(&table).await) .await .unwrap() .expect("the merge opened a writer"); @@ -2767,4 +3007,326 @@ mod lsm_tests { sstables.len() ); } + + #[tokio::test] + async fn lsm_cosine_distance_scale_and_mixed_tier_ordering() { + use arrow::array::{ + FixedSizeListArray, FixedSizeListBuilder, Float32Array, Float32Builder, + }; + use arrow::datatypes::Float32Type; + + use crate::index::Index; + use crate::index::vector::IvfPqIndexBuilder; + use datafusion_physical_plan::{ExecutionPlan, displayable}; + use lance::io::exec::ANNIvfSubIndexExec; + use std::any::Any; + + const DIM: usize = 8; + const N: usize = 256; + + fn normalized_vector(state: &mut u64) -> Vec { + let mut vector = (0..DIM) + .map(|_| { + *state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1); + ((*state >> 32) as u32 as f32 / u32::MAX as f32) * 2.0 - 1.0 + }) + .collect::>(); + let norm = vector.iter().map(|value| value * value).sum::().sqrt(); + vector.iter_mut().for_each(|value| *value /= norm); + vector + } + + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new( + "vec", + DataType::FixedSizeList( + Arc::new(Field::new("item", DataType::Float32, true)), + DIM as i32, + ), + false, + ), + ])); + let make_batch = |rows: Vec<(i64, Vec)>| { + let ids = rows.iter().map(|(id, _)| *id).collect::>(); + let mut vectors = FixedSizeListBuilder::new(Float32Builder::new(), DIM as i32); + for (_, vector) in &rows { + vectors.values().append_slice(vector); + vectors.append(true); + } + RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int64Array::from(ids)), Arc::new(vectors.finish())], + ) + .unwrap() + }; + let first_result = |batches: &[RecordBatch]| { + let batch = &batches[0]; + let id = batch["id"].as_primitive::().value(0); + let distance = batch["_distance"].as_primitive::().value(0); + (id, distance) + }; + + let mut state = 42; + let base_rows = (0..N) + .map(|id| (id as i64, normalized_vector(&mut state))) + .collect::>(); + let query = normalized_vector(&mut state); + + let dir = tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let base = make_batch(base_rows.clone()); + let reader: Box = + Box::new(RecordBatchIterator::new(vec![Ok(base)], schema.clone())); + let table = conn + .create_table("cosine_lsm", reader) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table + .create_index( + &["vec"], + Index::IvfPq( + IvfPqIndexBuilder::default() + .distance_type(crate::DistanceType::Cosine) + .num_partitions(1) + .num_sub_vectors(1), + ), + ) + .name("vec_cosine".to_string()) + .execute() + .await + .unwrap(); + table + .enable_rte( + RTEWriteSpec::unsharded().with_maintained_indexes(vec!["vec_cosine".to_string()]), + ) + .await + .unwrap(); + + let base_only = table + .query() + .nearest_to(query.as_slice()) + .unwrap() + .limit(1) + .use_rte(false) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let (base_id, public_distance) = first_result(&base_only); + + let lsm = table + .query() + .nearest_to(query.as_slice()) + .unwrap() + .limit(1) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let (lsm_id, lsm_distance) = first_result(&lsm); + assert_eq!(lsm_id, base_id); + assert!( + (lsm_distance - public_distance).abs() < 1e-5, + "LSM cosine distance {lsm_distance} did not use the public scale {public_distance}" + ); + + // Add an exact memtable result whose distance lies between the public ANN + // score and its doubled internal score. Correctly normalized plans still + // rank the ANN row first; mixed units would incorrectly rank this row first. + assert!(public_distance > 0.0 && public_distance < 4.0 / 3.0); + let memtable_distance = public_distance * 1.5; + let cosine_similarity = 1.0 - memtable_distance; + let mut orthogonal = normalized_vector(&mut state); + let projection = orthogonal + .iter() + .zip(&query) + .map(|(left, right)| left * right) + .sum::(); + for (value, query_value) in orthogonal.iter_mut().zip(&query) { + *value -= projection * query_value; + } + let norm = orthogonal + .iter() + .map(|value| value * value) + .sum::() + .sqrt(); + orthogonal.iter_mut().for_each(|value| *value /= norm); + let sine = (1.0 - cosine_similarity * cosine_similarity).sqrt(); + let memtable_vector = query + .iter() + .zip(&orthogonal) + .map(|(query_value, orthogonal_value)| { + cosine_similarity * query_value + sine * orthogonal_value + }) + .collect::>(); + + let mut merge = table.merge_insert(&[]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let memtable = make_batch(vec![(N as i64, memtable_vector)]); + merge + .execute( + Box::new(RecordBatchIterator::new(vec![Ok(memtable)], schema.clone())) + as Box, + ) + .await + .unwrap(); + + let mixed = table + .query() + .nearest_to(query.as_slice()) + .unwrap() + .limit(1) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let (mixed_id, mixed_distance) = first_result(&mixed); + assert_eq!( + mixed_id, base_id, + "mixed LSM tiers must compare ANN and exact distances in public units" + ); + assert!((mixed_distance - public_distance).abs() < 1e-5); + + // Re-ingest every base row so the flushed SSTable generation owns a + // complete copy of the dataset. ANN ranking of the rebuilt index is an + // independent approximation, so exact row parity with the base scan is + // not guaranteed. + let mut merge = table.merge_insert(&[]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let upsert_batch = make_batch(base_rows.clone()); + merge + .execute(Box::new(RecordBatchIterator::new( + vec![Ok(upsert_batch)], + schema.clone(), + )) + as Box) + .await + .unwrap(); + assert!( + base_rows.iter().any(|(id, _)| *id == base_id), + "upsert source must still contain the nearest base row" + ); + + table.close_rte_writers().await.unwrap(); + let sstables = published_sstables(&table).await; + assert_eq!(sstables.len(), 1, "expected one published SSTable"); + assert_eq!( + sstables[0].count_rows(None).await.unwrap(), + N + 1, + "published SSTable must contain the complete replacement fixture" + ); + + // The public query sets no explicit refine factor. Because the upsert + // rewrote every base id, a newer generation exists, so the engine must + // auto-refine ANN results over the published SSTable. + let public_query = table.query().nearest_to(query.as_slice()).unwrap().limit(1); + + fn collect_ann_nodes<'a>( + node: &'a dyn ExecutionPlan, + target_uri: &str, + out: &mut Vec<&'a ANNIvfSubIndexExec>, + ) { + // Local datasets may report their path with a different separator on Windows. + if let Some(ann) = (node as &dyn Any).downcast_ref::() + && std::path::Path::new(ann.dataset().uri()) == std::path::Path::new(target_uri) + { + out.push(ann); + } + for child in node.children() { + collect_ann_nodes(child.as_ref(), target_uri, out); + } + } + + let plan = public_query + .create_plan(crate::query::QueryExecutionOptions::default()) + .await + .unwrap(); + let mut ann_nodes = Vec::new(); + collect_ann_nodes(plan.as_ref(), sstables[0].uri(), &mut ann_nodes); + assert!( + !ann_nodes.is_empty(), + "public plan must contain an ANN sub-index over the published SSTable" + ); + assert_eq!( + ann_nodes[0].query().refine_factor, + Some(1), + "engine must auto-refine the SSTable ANN results" + ); + println!( + "RTE LSM public query plan:\n{}", + displayable(plan.as_ref()).indent(true) + ); + + // Execute the same public query. + let published = public_query + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let (published_id, published_distance) = first_result(&published); + assert!( + (0_i64..=N as i64).contains(&published_id), + "SSTable result id {published_id} must belong to the complete 0..={N} replacement fixture" + ); + + // The maintained ANN index may rank near-tied rows differently than + // the base scan, so the durable contract is distance correctness: the + // auto-refined result carries its own stored vector, and the query + // returns the analytical cosine distance of that exact vector. + let expected_distance = { + let published_vec = published[0]["vec"] + .as_any() + .downcast_ref::() + .unwrap() + .values() + .as_any() + .downcast_ref::() + .unwrap(); + // The query is a unit vector, so cosine distance is 1 - cos(q, v). + let dot = (0..DIM) + .map(|index| query[index] * published_vec.value(index)) + .sum::(); + let norm = (0..DIM) + .map(|index| published_vec.value(index) * published_vec.value(index)) + .sum::() + .sqrt(); + 1.0 - dot / norm + }; + assert!( + expected_distance > 0.0 && expected_distance.is_finite(), + "independent cosine oracle is degenerate: {expected_distance}" + ); + assert!( + (published_distance - expected_distance).abs() < 1e-5, + "SSTable ANN distance {published_distance} must match the analytical cosine distance {expected_distance} of its returned vector" + ); + println!( + "sstable_uri={} ann_nodes={} refine_factor={:?} observed_distance={} expected_cosine={}", + sstables[0].uri(), + ann_nodes.len(), + ann_nodes[0].query().refine_factor, + published_distance, + expected_distance, + ); + } } diff --git a/rust/lancedb/src/table/merge/lsm.rs b/rust/lancedb/src/table/merge/lsm.rs index 1596679de..e32b1a289 100644 --- a/rust/lancedb/src/table/merge/lsm.rs +++ b/rust/lancedb/src/table/merge/lsm.rs @@ -30,8 +30,8 @@ use datafusion_physical_plan::SendableRecordBatchStream; use futures::TryStreamExt; use lance::Dataset; use lance::dataset::mem_wal::{ - DatasetMemWalExt, ShardWriter, ShardWriterConfig, evaluate_sharding_spec, - validate_maintained_indexes_with, + DatasetMemWalExt, ShardManifestStore, ShardWriter, ShardWriterConfig, WalTailer, + evaluate_sharding_spec, validate_maintained_indexes_with, }; use lance::index::DatasetIndexExt; use lance_core::datatypes::Schema as LanceSchema; @@ -197,7 +197,9 @@ fn index_name_list(indices: &[IndexConfig]) -> String { /// Remove the [`RTEWriteSpec`] from the table by dropping the MemWAL index. /// /// Any cached shard writers are drained and closed first. Errors if no spec is -/// currently set. +/// currently set, or if the MemWAL still holds rows that have not been merged +/// into the base table: dropping the index would orphan them, since a MemWAL +/// installed later gets a new directory. #[allow(clippy::redundant_pub_crate)] pub(crate) async fn disable_rte(table: &NativeTable) -> Result<()> { table.dataset.ensure_mutable()?; @@ -214,6 +216,9 @@ pub(crate) async fn disable_rte(table: &NativeTable) -> Result<()> { table.dataset.shard_writer().drain_and_close().await?; let mut dataset = (*table.dataset.get().await?).clone(); + if let Some(details) = dataset.mem_wal_index_details().await? { + ensure_mem_wal_merged(&dataset, &details).await?; + } dataset .drop_index(lance_index::mem_wal::MEM_WAL_INDEX_NAME) .await?; @@ -221,6 +226,67 @@ pub(crate) async fn disable_rte(table: &NativeTable) -> Result<()> { Ok(()) } +/// Error if any shard of the MemWAL holds rows the base table does not: an +/// SSTable past the shard's compaction watermark, or a WAL entry past the +/// position its flushed SSTables cover. +/// +/// Reading the WAL tip catches rows a live writer in another process has +/// acknowledged but not flushed. A write that lands after this check is not +/// caught. +async fn ensure_mem_wal_merged(dataset: &Dataset, details: &MemWalIndexDetails) -> Result<()> { + let store = dataset.object_store(None).await?; + let base_path = dataset.branch_location().path; + let scan_batch_size = ShardWriterConfig::default().manifest_scan_batch_size; + + let mut pending = Vec::new(); + for shard_id in dataset.list_mem_wal_latest_shard_ids().await? { + // First occurrence per shard, as Lance's `compacted_generation_for_shard`. + let compacted = details + .compacted_sstables + .iter() + .find(|entry| entry.shard_id == shard_id) + .map_or(0, |entry| entry.generation); + let manifest = ShardManifestStore::new( + store.clone(), + &base_path, + &details.dir_id, + shard_id, + scan_batch_size, + ) + .latest() + .await?; + let (unmerged, flushed_through) = manifest.map_or((0, 0), |manifest| { + let unmerged = manifest + .sstables + .iter() + .filter(|sstable| sstable.generation > compacted) + .count(); + (unmerged, manifest.replay_after_wal_entry_position) + }); + let wal_tip = WalTailer::new(store.clone(), base_path.clone(), &details.dir_id, shard_id) + .next_position() + .await? + .saturating_sub(1); + let unflushed = wal_tip.saturating_sub(flushed_through); + if unmerged > 0 || unflushed > 0 { + pending.push(format!( + "shard {shard_id}: {unmerged} SSTable(s) not merged, {unflushed} WAL entry(ies) not flushed" + )); + } + } + if pending.is_empty() { + return Ok(()); + } + Err(Error::InvalidInput { + message: format!( + "disable_rte: the RTE holds rows that have not been merged into the base \ + table and would be lost if it were removed ({}); disable_rte is only \ + allowed before any rows have been written through the RTE", + pending.join("; ") + ), + }) +} + // ============================================================================= // get_rte_spec // ============================================================================= @@ -351,12 +417,17 @@ impl std::fmt::Debug for ShardWriterCache { } struct ShardWriterEntry { + /// The `dir_id` of the MemWAL the writer was opened for. Another process + /// can drop and re-initialize the MemWAL under this one, leaving the cached + /// writer bound to a directory the index no longer names. + dir_id: String, inner: RwLock>, } impl ShardWriterEntry { fn new(writer: ShardWriter) -> Self { Self { + dir_id: writer.config().dir_id.clone(), inner: RwLock::new(Some(writer)), } } @@ -420,37 +491,57 @@ impl ShardWriterCache { /// Return the cached writer, opening one for `shard_id` with `config` if /// the slot is empty. Errors if a writer is already open for a *different* /// shard — the caller must close it first. + /// + /// A cached writer opened for a MemWAL other than `dir_id` is retired and + /// replaced: the MemWAL it wrote to was dropped by another process, so its + /// rows are no longer part of the table and its commits would be fenced. async fn writer_for_shard( &self, dataset: &Dataset, + dir_id: &str, shard_id: Uuid, config: ShardWriterConfig, ) -> Result> { { let guard = self.slot.read().await; - if let Some((cached, entry)) = guard.as_ref() { + if let Some((cached, entry)) = guard.as_ref() + && entry.dir_id == dir_id + { check_shard_match(*cached, shard_id)?; return Ok(entry.clone()); } } let mut guard = self.slot.write().await; // Re-check: another caller may have opened the writer meanwhile. - if let Some((cached, entry)) = guard.as_ref() { + if let Some((cached, entry)) = guard.as_ref() + && entry.dir_id == dir_id + { check_shard_match(*cached, shard_id)?; return Ok(entry.clone()); } - let writer = dataset + let retired = guard.take(); + let opened = dataset .mem_wal_writer(shard_id, config) .await - .map_err(|e| Error::Runtime { - message: format!( - "merge_insert: failed to open RTE shard writer for shard {}: {}", - shard_id, e - ), - })?; - let entry = Arc::new(ShardWriterEntry::new(writer)); - *guard = Some((shard_id, entry.clone())); - Ok(entry) + .map(|writer| Arc::new(ShardWriterEntry::new(writer))); + if let Ok(entry) = &opened { + *guard = Some((shard_id, entry.clone())); + } + drop(guard); + if let Some((retired_shard, retired)) = retired + && let Err(error) = retired.close().await + { + log::warn!( + "the MemWAL was re-initialized, and the writer this process held for \ + shard {retired_shard} of the retired MemWAL could not be closed: {error}" + ); + } + opened.map_err(|e| Error::Runtime { + message: format!( + "merge_insert: failed to open RTE shard writer for shard {}: {}", + shard_id, e + ), + }) } /// Install `dataset`'s maintained index set on the cached writer, if one is @@ -505,10 +596,12 @@ impl ShardWriterCache { /// Snapshot the cached writer's shard for the RTE read path: its shard id, /// authoritative in-memory manifest, and active + frozen memtable refs. /// Returns `None` when no writer is currently cached (e.g. nothing has been - /// written this session, or the writer was closed). + /// written this session, or the writer was closed), or when the cached + /// writer belongs to a MemWAL other than `dir_id`. #[allow(clippy::redundant_pub_crate)] pub(crate) async fn read_snapshot( &self, + dir_id: &str, ) -> Result< Option<( Uuid, @@ -523,6 +616,10 @@ impl ShardWriterCache { let Some((shard_id, entry)) = cached else { return Ok(None); }; + // A writer for a retired MemWAL holds no rows of the current one. + if entry.dir_id != dir_id { + return Ok(None); + } // Capture memtables before the manifest. If a flush interleaves, dedup // tolerates the same rows appearing in both a memtable and a freshly // flushed generation, but would drop rows present in neither. Manifest @@ -576,6 +673,8 @@ enum LsmMode { #[allow(clippy::redundant_pub_crate)] pub(crate) struct LsmPlan { mode: LsmMode, + /// The `dir_id` of the MemWAL the write targets. + dir_id: String, writer_config_defaults: HashMap, } @@ -644,6 +743,7 @@ pub(crate) async fn lsm_dispatch_decision( let mode = resolve_lsm_mode(&details)?; Ok(LsmDispatch::Lsm(LsmPlan { mode, + dir_id: details.dir_id, writer_config_defaults: details.writer_config_defaults, })) } @@ -745,7 +845,7 @@ pub(crate) async fn execute_lsm_merge_insert( let writer = table .dataset .shard_writer() - .writer_for_shard(dataset.as_ref(), shard_id, config) + .writer_for_shard(dataset.as_ref(), &plan.dir_id, shard_id, config) .await?; writer.put(batches).await?; diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index 2a502b059..657385762 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -6,20 +6,183 @@ //! This module contains the implementation of optimization operations that help //! maintain good performance for LanceDB tables. -use std::sync::Arc; +use std::{ + collections::HashSet, + sync::{Arc, Mutex}, +}; +use arrow_schema::DataType; use chrono::{DateTime, Utc}; use lance::dataset::cleanup::{CleanupPolicyBuilder, RemovalStats}; -use lance::dataset::optimize::{CompactionMetrics, IndexRemapperOptions, compact_files}; -use lance::index::DatasetIndexExt; +use lance::dataset::optimize::{ + CompactionMetrics, CompactionPlan, CompactionPlanner, IndexRemapperOptions, + compact_files_with_planner, plan_compaction, +}; +use lance::index::{DatasetIndexExt, DatasetIndexInternalExt}; +use lance_core::utils::tracing::{DATASET_COMPACTING_EVENT, TRACE_DATASET_EVENTS}; +use lance_index::IndexType; +use lance_index::metrics::NoOpMetricsCollector; use lance_index::optimize::OptimizeOptions; -use log::info; - -pub use chrono::Duration; -pub use lance::dataset::optimize::CompactionOptions; +use log::{debug, info}; use super::NativeTable; -use crate::error::Result; +use crate::error::{Error, Result}; +pub use chrono::Duration; +pub use lance::dataset::optimize::{CompactionMode, CompactionOptions, IndexRemapMode}; + +const MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX: u64 = u32::MAX as u64; + +struct PrecomputedCompactionPlanner { + plan: Mutex>, +} + +impl PrecomputedCompactionPlanner { + fn new(plan: CompactionPlan) -> Self { + Self { + plan: Mutex::new(Some(plan)), + } + } +} + +#[async_trait::async_trait] +impl CompactionPlanner for PrecomputedCompactionPlanner { + async fn plan(&self, dataset: &lance::Dataset) -> lance::Result { + let plan = self + .plan + .lock() + .map_err(|_| lance_core::Error::internal("precomputed compaction plan lock poisoned"))? + .take() + .ok_or_else(|| { + lance_core::Error::internal("precomputed compaction plan was already consumed") + })?; + debug_assert_eq!(dataset.manifest().version, plan.read_version()); + Ok(plan) + } +} + +fn sq_vector_dimension(data_type: &DataType) -> Option { + match data_type { + DataType::FixedSizeList(_, dimension) => Some(*dimension), + DataType::List(field) => match field.data_type() { + DataType::FixedSizeList(_, dimension) => Some(*dimension), + _ => None, + }, + _ => None, + } +} + +fn segment_touches_fragments( + fragment_ids: Option>, + affected_fragments: &HashSet, +) -> bool { + fragment_ids.is_none_or(|fragment_ids| { + fragment_ids + .into_iter() + .any(|fragment| affected_fragments.contains(&(fragment as u64))) + }) +} + +fn oversized_sq_partition( + partition_sizes: impl IntoIterator, + dimension: u64, +) -> Option { + partition_sizes.into_iter().find(|partition_size| { + partition_size + .checked_mul(dimension) + .is_none_or(|child_len| child_len > MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX) + }) +} + +async fn validate_sq_index_remapping( + dataset: &lance::Dataset, + options: &CompactionOptions, + has_custom_remapper: bool, +) -> Result { + let plan = plan_compaction(dataset, options).await?; + if options.defer_index_remap || has_custom_remapper || dataset.manifest().uses_stable_row_ids() + { + return Ok(plan); + } + + if plan.tasks.is_empty() { + return Ok(plan); + } + let affected_fragments: HashSet = plan + .tasks + .iter() + .flat_map(|task| task.fragments.iter().map(|fragment| fragment.id)) + .collect(); + + for segment in dataset.load_indices().await?.iter() { + if !segment_touches_fragments( + segment + .fragment_bitmap + .as_ref() + .map(|fragment_bitmap| fragment_bitmap.iter()), + &affected_fragments, + ) { + continue; + } + let Some(field_id) = segment.fields.first() else { + continue; + }; + let Some(field) = dataset.schema().field_by_id(*field_id) else { + continue; + }; + let data_type = field.data_type(); + let Some(dimension) = sq_vector_dimension(&data_type) else { + continue; + }; + let dimension = u64::try_from(dimension).map_err(|_| Error::InvalidInput { + message: format!( + "SQ index '{}' has an invalid vector dimension of {}", + segment.name, dimension + ), + })?; + + let field_path = dataset.schema().field_path(*field_id)?; + let vector_index = match dataset + .open_vector_index(&field_path, &segment.uuid, &NoOpMetricsCollector) + .await + { + Ok(vector_index) => vector_index, + Err(error) => { + // The default remapper also treats an index it cannot open as + // unusable and drops it, so it cannot reach the SQ take kernel. + debug!( + "Skipping remap preflight for index segment {} because it could not be opened: {}", + segment.uuid, error + ); + continue; + } + }; + if !matches!( + vector_index.index_type(), + IndexType::IvfSq | IndexType::IvfHnswSq + ) { + continue; + } + + let partition_sizes = (0..vector_index.total_partitions()) + .map(|partition_id| vector_index.partition_size(partition_id) as u64); + if let Some(partition_size) = oversized_sq_partition(partition_sizes, dimension) { + let max_partition_size = MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX / dimension; + return Err(Error::InvalidInput { + message: format!( + "Cannot compact table because SQ index '{}' segment {} has a partition with {} vectors of dimension {}. Arrow's fixed-size-list take kernel cannot remap partitions whose child array exceeds {} values. Recreate the index with default IVF partitioning, or enough partitions to keep each partition at or below {} vectors, before compacting.", + segment.name, + segment.uuid, + partition_size, + dimension, + MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX, + max_partition_size, + ), + }); + } + } + + Ok(plan) +} /// Optimize the dataset. /// @@ -69,7 +232,11 @@ pub enum OptimizeAction { /// **WARNING**: This should only be set to true if you can guarantee that no other process is /// currently working on this dataset. Otherwise the dataset could be put into a corrupted state. delete_unverified: Option, + /// Tagged versions are never removed, regardless of their age. + /// /// If true, an error will be returned if there are any old versions that are still tagged. + /// If false or `None` (the default), tagged versions are silently retained and all other + /// old versions are removed. error_if_tagged_old_versions: Option, }, /// Optimize the indices @@ -125,6 +292,12 @@ pub(crate) async fn optimize_indices(table: &NativeTable, options: &OptimizeOpti /// no other process is currently working on this dataset. Otherwise the /// dataset could be put into a corrupted state. /// +/// * `error_if_tagged_old_versions` - Tagged versions are always retained. If +/// this is true, an error is returned when a tagged version is older than the +/// cutoff. Defaults to false (the tagged versions are retained silently), +/// unlike Lance's own default, so that `optimize` does not fail (and skip the +/// steps after pruning) once a tagged version ages past the cutoff. +/// /// This calls into [lance::dataset::Dataset::cleanup_old_versions] and /// returns the result. pub(crate) async fn cleanup_old_versions( @@ -136,7 +309,11 @@ pub(crate) async fn cleanup_old_versions( table.dataset.ensure_mutable()?; let dataset = table.dataset.get().await?; let stats = dataset - .cleanup_old_versions(older_than, delete_unverified, error_if_tagged_old_versions) + .cleanup_old_versions( + older_than, + delete_unverified, + Some(error_if_tagged_old_versions.unwrap_or(false)), + ) .await?; // Computed-column signature sidecars live outside lance's directories; // drop the ones the surviving versions no longer reference. @@ -161,9 +338,8 @@ pub(crate) async fn cleanup_old_versions_before( if let Some(delete_unverified) = delete_unverified { policy = policy.delete_unverified(delete_unverified); } - if let Some(error_if_tagged_old_versions) = error_if_tagged_old_versions { - policy = policy.error_if_tagged_old_versions(error_if_tagged_old_versions); - } + // Tagged versions are retained rather than raising an error unless asked. + policy = policy.error_if_tagged_old_versions(error_if_tagged_old_versions.unwrap_or(false)); let stats = dataset.cleanup_with_policy(policy.build()).await?; // Computed-column signature sidecars live outside lance's directories; // drop the ones the surviving versions no longer reference. @@ -180,7 +356,7 @@ pub(crate) async fn cleanup_old_versions_before( /// This can be run after making several small appends to optimize the table /// for faster reads. /// -/// This calls into [lance::dataset::optimize::compact_files]. +/// This calls into [lance::dataset::optimize::compact_files_with_planner]. pub(crate) async fn compact_files_impl( table: &NativeTable, options: CompactionOptions, @@ -188,7 +364,10 @@ pub(crate) async fn compact_files_impl( ) -> Result { table.dataset.ensure_mutable()?; let mut dataset = (*table.dataset.get().await?).clone(); - let metrics = compact_files(&mut dataset, options, remap_options).await?; + tracing::info!(target: TRACE_DATASET_EVENTS, event=DATASET_COMPACTING_EVENT, uri = dataset.uri()); + let plan = validate_sq_index_remapping(&dataset, &options, remap_options.is_some()).await?; + let planner = PrecomputedCompactionPlanner::new(plan); + let metrics = compact_files_with_planner(&mut dataset, remap_options, &planner).await?; table.dataset.update(dataset); Ok(metrics) } @@ -250,13 +429,14 @@ pub(crate) async fn execute_optimize( #[cfg(test)] mod tests { + use super::{oversized_sq_partition, segment_touches_fragments, sq_vector_dimension}; use arrow_array::{ Array, FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray, }; use arrow_schema::{DataType, Field, Schema}; use lance_arrow::FixedSizeListArrayExt; use rstest::rstest; - use std::sync::Arc; + use std::{collections::HashSet, sync::Arc}; use crate::connect; use crate::database::listing::OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS; @@ -266,6 +446,172 @@ mod tests { use crate::table::{CompactionOptions, OptimizeAction, OptimizeStats}; use futures::TryStreamExt; + /// Regression test for https://github.com/lancedb/lancedb/issues/2866. + #[test] + fn test_detect_oversized_sq_partition() { + const DIMENSION: u64 = 4095; + let safe_size = u32::MAX as u64 / DIMENSION; + + assert_eq!( + oversized_sq_partition([safe_size, safe_size + 1], DIMENSION), + Some(safe_size + 1) + ); + assert_eq!( + oversized_sq_partition([safe_size / 2, safe_size / 2 + 1], DIMENSION), + None + ); + } + + #[test] + fn test_segment_touches_fragments_includes_unknown_coverage() { + let affected_fragments = HashSet::from([7]); + + assert!(segment_touches_fragments( + Some([7_u32]), + &affected_fragments + )); + assert!(!segment_touches_fragments( + Some([8_u32]), + &affected_fragments + )); + assert!(segment_touches_fragments( + None::<[u32; 0]>, + &affected_fragments + )); + } + + #[test] + fn test_sq_vector_dimension_includes_multivectors() { + const DIMENSION: i32 = 4095; + let vector = DataType::FixedSizeList( + Arc::new(Field::new("item", DataType::Float32, false)), + DIMENSION, + ); + let multivector = DataType::List(Arc::new(Field::new("item", vector.clone(), false))); + + assert_eq!(sq_vector_dimension(&vector), Some(DIMENSION)); + assert_eq!(sq_vector_dimension(&multivector), Some(DIMENSION)); + assert_eq!(sq_vector_dimension(&DataType::Float32), None); + } + + #[tokio::test] + async fn test_compact_legacy_vector_index_with_unknown_fragment_coverage() { + use lance::Dataset; + use lance::index::vector::{IndexFileVersion, VectorIndexParams}; + use lance::index::{DatasetIndexExt, DatasetIndexInternalExt}; + use lance_index::IndexType; + use lance_linalg::distance::MetricType; + use lance_table::io::commit::write_manifest_file_to_path; + use object_store::ObjectStoreExt; + + const INDEX_NAME: &str = "legacy_ivf_pq"; + const ROWS: i32 = 128; + const DIMENSION: i32 = 8; + + let tmpdir = tempfile::tempdir().unwrap(); + let conn = connect(tmpdir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let vectors = FixedSizeListArray::try_new_from_values( + Float32Array::from_iter_values((0..ROWS).flat_map(|row| { + (0..DIMENSION).map(move |offset| (row * DIMENSION + offset) as f32) + })), + DIMENSION, + ) + .unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new( + "vector", + vectors.data_type().clone(), + false, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(vectors)]).unwrap(); + let table = conn + .create_table("test_legacy_vector_compact", batch.clone()) + .execute() + .await + .unwrap(); + table.add(batch.clone()).execute().await.unwrap(); + table.add(batch).execute().await.unwrap(); + let mut dataset = (*table.dataset().unwrap().get().await.unwrap()).clone(); + let mut params = VectorIndexParams::ivf_pq(1, 8, 1, MetricType::L2, 10); + params.version(IndexFileVersion::Legacy); + dataset + .create_index( + &["vector"], + IndexType::Vector, + Some(INDEX_NAME.to_string()), + ¶ms, + true, + ) + .await + .unwrap(); + table.dataset().unwrap().update(dataset); + + let dataset = table.dataset().unwrap().get().await.unwrap(); + let mut segments = dataset.load_indices_by_name(INDEX_NAME).await.unwrap(); + assert_eq!(segments.len(), 1); + let original = segments.pop().unwrap(); + let field_path = dataset.schema().field_path(original.fields[0]).unwrap(); + let vector_index = dataset + .open_vector_index( + &field_path, + &original.uuid, + &lance_index::metrics::NoOpMetricsCollector, + ) + .await + .unwrap(); + assert_eq!(vector_index.index_type(), IndexType::IvfPq); + assert_eq!( + vector_index.statistics().unwrap()["index_file_version"], + "Legacy" + ); + let mut legacy = original.clone(); + legacy.fragment_bitmap = None; + let object_store = dataset.object_store(None).await.unwrap(); + let mut manifest = dataset.manifest().clone(); + manifest.index_section = None; + manifest.transaction_section = None; + let manifest_path = dataset.manifest_location().path.clone(); + object_store.inner.delete(&manifest_path).await.unwrap(); + write_manifest_file_to_path( + object_store.as_ref(), + &mut manifest, + Some(vec![legacy]), + &manifest_path, + None, + ) + .await + .unwrap(); + let legacy_dataset = Dataset::open(dataset.uri()).await.unwrap(); + table.dataset().unwrap().update(legacy_dataset); + + let dataset = table.dataset().unwrap().get().await.unwrap(); + let description_error = dataset + .describe_indices(None) + .await + .err() + .expect("legacy coverage should be unknown to index descriptions"); + assert!( + description_error + .to_string() + .contains("Fragment bitmap is required") + ); + + let stats = table + .optimize(OptimizeAction::Compact { + options: CompactionOptions { + target_rows_per_fragment: 1_000, + ..Default::default() + }, + remap_options: None, + }) + .await + .unwrap(); + assert!(stats.compaction.unwrap().fragments_removed > 0); + assert_eq!(table.count_rows(None).await.unwrap(), ROWS as usize * 3); + } + #[tokio::test] async fn test_optimize_compact_simple() { let conn = connect("memory://").execute().await.unwrap(); @@ -511,6 +857,90 @@ mod tests { assert_eq!(all_values, expected); } + #[tokio::test] + async fn test_optimize_prune_retains_tagged_versions() { + let tmpdir = tempfile::tempdir().unwrap(); + let conn = connect(tmpdir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + + let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)])); + let make_batch = |start: i32| { + RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from_iter_values(start..start + 10))], + ) + .unwrap() + }; + + let table = conn + .create_table("test_prune_tagged", make_batch(0)) + .execute() + .await + .unwrap(); + // Tag the first version, then create more versions after it. + table.tags().await.unwrap().create("keep", 1).await.unwrap(); + for i in 1..4 { + table.add(make_batch(i * 10)).execute().await.unwrap(); + } + assert_eq!(table.list_versions().await.unwrap().len(), 4); + + // Explicitly asking for an error still errors, and leaves everything in place. + let err = table + .optimize(OptimizeAction::Prune { + older_than: Some(chrono::Duration::try_days(0).unwrap()), + delete_unverified: Some(true), + error_if_tagged_old_versions: Some(true), + }) + .await + .unwrap_err(); + assert!(err.to_string().contains("tagged version"), "{err}"); + assert_eq!(table.list_versions().await.unwrap().len(), 4); + + // By default, tagged versions are retained and the other old versions are removed. + let stats = table + .optimize(OptimizeAction::Prune { + older_than: Some(chrono::Duration::try_days(0).unwrap()), + delete_unverified: Some(true), + error_if_tagged_old_versions: None, + }) + .await + .unwrap(); + assert_eq!(stats.prune.unwrap().old_versions, 2); + let mut versions = table + .list_versions() + .await + .unwrap() + .into_iter() + .map(|v| v.version) + .collect::>(); + versions.sort(); + assert_eq!(versions, vec![1, 4]); + + // Same through the absolute-cutoff entry point used by the Node binding. + table.add(make_batch(40)).execute().await.unwrap(); + let stats = table + .optimize_prune_before(chrono::Utc::now(), Some(true), None) + .await + .unwrap(); + assert_eq!(stats.prune.unwrap().old_versions, 1); + + // The tagged version is still readable, including its data files. + assert_eq!(table.count_rows(None).await.unwrap(), 50); + table.checkout_tag("keep").await.unwrap(); + let batches = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let rows: usize = batches.iter().map(|b| b.num_rows()).sum(); + assert_eq!(rows, 10); + } + #[tokio::test] async fn test_optimize_index() { let conn = connect("memory://").execute().await.unwrap(); diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index cf70c6626..2f5c75766 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -1,7 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use std::sync::Arc; +use std::{ + collections::{HashSet, VecDeque}, + sync::Arc, +}; mod lsm; @@ -17,15 +20,24 @@ use arrow::array::{AsArray, FixedSizeListBuilder, Float32Builder}; use arrow::datatypes::{Float32Type, UInt8Type}; use arrow_array::Array; use arrow_schema::{DataType, Schema}; -use datafusion_common::{Column, DataFusionError, SchemaError}; -use datafusion_physical_plan::ExecutionPlan; +use datafusion_common::{Column, DataFusionError, ScalarValue, SchemaError}; +use datafusion_expr::Operator; +use datafusion_physical_expr::expressions::{BinaryExpr, Column as PhysicalColumn, Literal}; +use datafusion_physical_plan::PhysicalExpr; use datafusion_physical_plan::projection::ProjectionExec; use datafusion_physical_plan::repartition::RepartitionExec; use datafusion_physical_plan::union::UnionExec; +use datafusion_physical_plan::{ExecutionPlan, replace_children_if_necessary}; use lance::dataset::mem_wal::DatasetMemWalExt; use lance::dataset::scanner::DatasetRecordBatchStream; use lance::dataset::scanner::Scanner; +use lance::index::DatasetIndexInternalExt; +use lance::io::exec::{ANNIvfBatchExec, ANNIvfSubIndexExec}; use lance_datafusion::exec::{analyze_plan as lance_analyze_plan, execute_plan}; +use lance_index::IndexType; +use lance_index::metrics::NoOpMetricsCollector; +use lance_index::vector::DIST_COL; +use lance_linalg::distance::DistanceType as LanceDistanceType; use lance_namespace::LanceNamespace; use lance_namespace::models::{ QueryTableRequest as NsQueryTableRequest, QueryTableRequestColumns, @@ -280,7 +292,13 @@ pub async fn create_plan( let (_, element_type) = lance::index::vector::utils::get_vector_type(schema, &column)?; let is_binary = matches!(element_type, DataType::UInt8); - let top_k = query.base.limit.unwrap_or(DEFAULT_TOP_K) + query.base.offset.unwrap_or(0); + let top_k = query + .base + .limit + .unwrap_or(DEFAULT_TOP_K) + .saturating_add(query.base.offset.unwrap_or(0)) + // Lance allocates candidates from k; no search can return more rows than the table. + .min(ds_ref.count_rows(None).await?.max(1)); if is_binary { let query_vector = arrow::compute::cast(&query_vector, &DataType::UInt8)?; @@ -317,9 +335,18 @@ pub async fn create_plan( // For a batch query, `nearest` already applies k to each query vector. // Adding Scanner's global limit would truncate the combined result to k rows. if !is_batch_query { + let offset = query + .base + .offset + .map(|offset| i64::try_from(offset).unwrap_or(i64::MAX)); scanner.limit( - query.base.limit.map(|limit| limit as i64), - query.base.offset.map(|offset| offset as i64), + // Lance's FTS planner adds limit + offset as i64. + query.base.limit.map(|limit| { + i64::try_from(limit) + .unwrap_or(i64::MAX) + .min(i64::MAX - offset.unwrap_or(0)) + }), + offset, )?; } @@ -394,10 +421,30 @@ pub async fn create_plan( scanner.order_by(Some(order_by.clone()))?; } - scanner + let mut plan = scanner .create_plan() .await - .map_err(|error| enrich_lance_field_not_found(error, schema)) + .map_err(|error| enrich_lance_field_not_found(error, schema))?; + let normalized_l2_indices = normalized_l2_ann_indices(plan.as_ref()).await?; + if !normalized_l2_indices.is_empty() { + // Rebuild only the affected ANN nodes with internal normalized squared-L2 + // bounds. Exact branches keep the public cosine bounds from `plan`. + let internal_plan = if query.lower_bound.is_some() || query.upper_bound.is_some() { + scanner.distance_range( + query.lower_bound.map(|bound| bound / COSINE_ANN_SCALE), + query.upper_bound.map(|bound| bound / COSINE_ANN_SCALE), + ); + scanner + .create_plan() + .await + .map_err(|error| enrich_lance_field_not_found(error, schema))? + } else { + plan.clone() + }; + plan = normalize_ann_branches(plan, internal_plan, &normalized_l2_indices)?; + } + + Ok(plan) } /// Replace DataFusion's top-level field candidates with qualified leaf paths. @@ -489,6 +536,242 @@ fn leaf_field_paths(schema: &Schema) -> Vec { //Helper functions below +const COSINE_ANN_SCALE: f32 = 0.5; + +#[derive(Clone, Copy)] +enum AnnExecRef<'a> { + Single(&'a ANNIvfSubIndexExec), + Batch(&'a ANNIvfBatchExec), +} + +impl<'a> AnnExecRef<'a> { + fn from_plan(plan: &'a dyn ExecutionPlan) -> Option { + if let Some(single) = plan.downcast_ref::() { + return Some(Self::Single(single)); + } + plan.downcast_ref::().map(Self::Batch) + } + + fn query(self) -> &'a lance_index::vector::Query { + match self { + Self::Single(ann) => ann.query(), + Self::Batch(ann) => ann.query(), + } + } + + fn dataset(self) -> &'a Arc { + match self { + Self::Single(ann) => ann.dataset(), + Self::Batch(ann) => ann.dataset(), + } + } + + fn indices(self) -> &'a [lance_table::format::IndexMetadata] { + match self { + Self::Single(ann) => ann.indices(), + Self::Batch(ann) => ann.indices(), + } + } + + fn query_count(self) -> Option { + match self { + Self::Single(_) => None, + Self::Batch(ann) => Some(ann.query_count()), + } + } + + fn same_kind(self, other: Self) -> bool { + matches!( + (self, other), + (Self::Single(_), Self::Single(_)) | (Self::Batch(_), Self::Batch(_)) + ) + } +} + +/// Find ANN index segments whose scores use normalized squared L2 for cosine search. +/// +/// Cosine PQ/SQ/RQ indices normalize their vectors and use squared L2 internally. This +/// preserves ranking, but squared L2 over unit vectors is twice the cosine distance. Flat +/// cosine indices calculate cosine directly, so they are not included. +async fn normalized_l2_ann_indices(plan: &dyn ExecutionPlan) -> Result> { + let mut ann_plans = Vec::new(); + find_ann_plans(plan, &mut ann_plans); + + let mut checked = HashSet::new(); + let mut normalized_l2 = HashSet::new(); + for ann in ann_plans { + if ann.query().metric_type != Some(LanceDistanceType::Cosine) { + continue; + } + for index in ann.indices() { + let uuid = index.uuid.to_string(); + if !checked.insert(uuid.clone()) { + continue; + } + let vector_index = ann + .dataset() + .open_vector_index(&ann.query().column, &index.uuid, &NoOpMetricsCollector) + .await?; + if matches!( + vector_index.index_type(), + IndexType::IvfPq + | IndexType::IvfSq + | IndexType::IvfRq + | IndexType::IvfHnswPq + | IndexType::IvfHnswSq + ) { + normalized_l2.insert(uuid); + } + } + } + Ok(normalized_l2) +} + +/// Normalize affected ANN outputs before their parent plan nodes consume them. +/// +/// This is used by planners that do not support distance ranges, such as the MemWAL +/// LSM planner. The standard scanner path rebuilds a second plan when it also needs +/// to translate range bounds, then calls [`normalize_ann_branches`] directly. +pub(super) async fn normalize_cosine_ann_branches( + plan: Arc, +) -> Result> { + let normalized_l2_indices = normalized_l2_ann_indices(plan.as_ref()).await?; + if normalized_l2_indices.is_empty() { + return Ok(plan); + } + normalize_ann_branches(plan.clone(), plan, &normalized_l2_indices) +} + +fn find_ann_plans<'a>(plan: &'a dyn ExecutionPlan, ann_plans: &mut Vec>) { + if let Some(ann) = AnnExecRef::from_plan(plan) { + ann_plans.push(ann); + return; + } + for child in plan.children() { + find_ann_plans(child.as_ref(), ann_plans); + } +} + +fn collect_ann_plans( + plan: &Arc, + ann_plans: &mut VecDeque>, +) { + if AnnExecRef::from_plan(plan.as_ref()).is_some() { + ann_plans.push_back(plan.clone()); + return; + } + for child in plan.children() { + collect_ann_plans(child, ann_plans); + } +} + +/// Replace normalized-L2 ANN nodes with equivalent nodes that use internal bounds, then +/// convert their output to the public cosine scale before any generic plan node consumes it. +fn normalize_ann_branches( + public_plan: Arc, + internal_plan: Arc, + normalized_l2_indices: &HashSet, +) -> Result> { + let mut internal_ann_plans = VecDeque::new(); + collect_ann_plans(&internal_plan, &mut internal_ann_plans); + let normalized = + replace_ann_branches(public_plan, &mut internal_ann_plans, normalized_l2_indices)?; + if !internal_ann_plans.is_empty() { + return Err(Error::Runtime { + message: "internal and public vector plans contained different ANN branches" + .to_string(), + }); + } + Ok(normalized) +} + +fn replace_ann_branches( + public_plan: Arc, + internal_ann_plans: &mut VecDeque>, + normalized_l2_indices: &HashSet, +) -> Result> { + if let Some(public_ann) = AnnExecRef::from_plan(public_plan.as_ref()) { + let internal_plan = internal_ann_plans + .pop_front() + .ok_or_else(|| Error::Runtime { + message: "internal vector plan was missing an ANN branch".to_string(), + })?; + let internal_ann = + AnnExecRef::from_plan(internal_plan.as_ref()).ok_or_else(|| Error::Runtime { + message: "internal vector plan contained a non-ANN branch where an ANN branch was expected" + .to_string(), + })?; + let same_indices = public_ann + .indices() + .iter() + .map(|index| &index.uuid) + .eq(internal_ann.indices().iter().map(|index| &index.uuid)); + if !public_ann.same_kind(internal_ann) + || public_ann.query_count() != internal_ann.query_count() + || public_ann.query().column != internal_ann.query().column + || public_ann.query().metric_type != internal_ann.query().metric_type + || !same_indices + { + return Err(Error::Runtime { + message: "internal and public vector plans had mismatched ANN branches".to_string(), + }); + } + + let normalized_count = public_ann + .indices() + .iter() + .filter(|index| normalized_l2_indices.contains(&index.uuid.to_string())) + .count(); + if normalized_count == 0 { + return Ok(public_plan); + } + if normalized_count != public_ann.indices().len() { + return Err(Error::Runtime { + message: "one ANN branch mixed public and normalized-L2 distance scales" + .to_string(), + }); + } + return scale_distance_column(internal_plan, COSINE_ANN_SCALE); + } + + let children = public_plan + .children() + .into_iter() + .cloned() + .map(|child| replace_ann_branches(child, internal_ann_plans, normalized_l2_indices)) + .collect::>>()?; + Ok(replace_children_if_necessary(public_plan, children)?) +} + +fn scale_distance_column( + plan: Arc, + scale: f32, +) -> Result> { + let schema = plan.schema(); + if schema.column_with_name(DIST_COL).is_none() { + return Ok(plan); + } + + let expressions: Vec<(Arc, String)> = schema + .fields() + .iter() + .enumerate() + .map(|(index, field)| { + let column: Arc = Arc::new(PhysicalColumn::new(field.name(), index)); + let expression = if field.name() == DIST_COL { + let scale: Arc = + Arc::new(Literal::new(ScalarValue::Float32(Some(scale)))); + Arc::new(BinaryExpr::new(column, Operator::Multiply, scale)) + as Arc + } else { + column + }; + (expression, field.name().clone()) + }) + .collect(); + Ok(Arc::new(ProjectionExec::try_new(expressions, plan)?)) +} + // Take many execution plans and map them into a single plan that adds // a query_index column and unions them. pub(crate) fn create_multi_vector_plan( @@ -671,6 +954,12 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { }); } + let k = match q.limit { + Some(limit) => limit as i32, + None if q.full_text_search.is_some() => DEFAULT_TOP_K as i32, + None => i32::MAX, + }; + let filter = q.filter.as_ref().map(filter_to_sql).transpose()?; let columns = match &q.select { @@ -723,7 +1012,7 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { Ok(NsQueryTableRequest { id: None, // Will be set by caller vector, - k: q.limit.unwrap_or(10) as i32, + k, filter, columns, prefilter: Some(q.prefilter), @@ -1073,6 +1362,54 @@ mod tests { assert!(ns_request.vector.single_vector.as_ref().unwrap().is_empty()); } + #[test] + fn test_convert_to_namespace_query_plain_query_without_limit() { + let any_query = AnyQuery::Query(QueryRequest::default()); + + let ns_request = convert_to_namespace_query(&any_query).unwrap(); + + assert_eq!(ns_request.k, i32::MAX); + } + + #[test] + fn test_convert_to_namespace_query_plain_query_with_explicit_limit() { + let any_query = AnyQuery::Query(QueryRequest { + limit: Some(10), + ..Default::default() + }); + + let ns_request = convert_to_namespace_query(&any_query).unwrap(); + + assert_eq!(ns_request.k, 10); + } + + #[test] + fn test_convert_to_namespace_query_vector_without_limit() { + let query_vector = Arc::new(Float32Array::from(vec![1.0, 2.0, 3.0, 4.0])); + let any_query = AnyQuery::VectorQuery(VectorQueryRequest { + query_vector: vec![query_vector as ArrayRef], + ..Default::default() + }); + + let ns_request = convert_to_namespace_query(&any_query).unwrap(); + + assert_eq!(ns_request.k, 10); + } + + #[test] + fn test_convert_to_namespace_query_fts_without_limit() { + let any_query = AnyQuery::Query(QueryRequest { + full_text_search: Some(lance_index::scalar::FullTextSearchQuery::new( + "hello world".to_string(), + )), + ..Default::default() + }); + + let ns_request = convert_to_namespace_query(&any_query).unwrap(); + + assert_eq!(ns_request.k, 10); + } + #[tokio::test] async fn test_execute_query_local_routing() { use crate::connect; @@ -1553,6 +1890,354 @@ mod tests { "plan should add query_index column, got:\n{display}" ); } + #[rstest::rstest] + #[case::modern(false)] + #[case::legacy(true)] + #[tokio::test] + async fn test_cosine_pq_distance_uses_public_cosine_scale(#[case] legacy: bool) { + use arrow_array::{ + Float32Array, Int32Array, RecordBatch, + types::{Float32Type, Int32Type}, + }; + use arrow_schema::{DataType, Field, Schema}; + + use crate::connect; + use crate::index::{Index, vector::IvfPqIndexBuilder}; + use lance::index::{ + DatasetIndexExt, + vector::{IndexFileVersion, VectorIndexParams}, + }; + + fn normalized_vector(state: &mut u64, dimension: usize) -> Vec { + let mut vector = (0..dimension) + .map(|_| { + *state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1); + ((*state >> 32) as u32 as f32 / u32::MAX as f32) * 2.0 - 1.0 + }) + .collect::>(); + let norm = vector.iter().map(|value| value * value).sum::().sqrt(); + vector.iter_mut().for_each(|value| *value /= norm); + vector + } + + fn distances(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch[DIST_COL] + .as_primitive::() + .values() + .to_vec() + }) + .collect() + } + + let conn = connect("memory://").execute().await.unwrap(); + let dimension = 8; + let num_rows = 256; + let mut state = 42; + let values = (0..num_rows) + .flat_map(|_| normalized_vector(&mut state, dimension)) + .collect::>(); + let query_vector = normalized_vector(&mut state, dimension); + let vectors = Arc::new(fixed_size_list_array(values, dimension as i32)); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("vector", vectors.data_type().clone(), false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from_iter_values(0..num_rows)), vectors], + ) + .unwrap(); + let table = conn + .create_table("test_cosine_pq_distance", batch) + .execute() + .await + .unwrap(); + if legacy { + let mut dataset = (*table.dataset().unwrap().get().await.unwrap()).clone(); + dataset + .create_index( + &["vector"], + IndexType::Vector, + None, + VectorIndexParams::ivf_pq(1, 8, 1, LanceDistanceType::Cosine, 10) + .version(IndexFileVersion::Legacy), + true, + ) + .await + .unwrap(); + table.dataset().unwrap().update(dataset); + } else { + table + .create_index( + &["vector"], + Index::IvfPq( + IvfPqIndexBuilder::default() + .distance_type(crate::DistanceType::Cosine) + .num_partitions(1) + .num_sub_vectors(1), + ), + ) + .execute() + .await + .unwrap(); + } + + let expected_index_version = if legacy { "Legacy" } else { "V3" }; + let index_file_version = { + let dataset = table.dataset().unwrap().get().await.unwrap(); + let metadata = dataset + .load_indices() + .await + .unwrap() + .first() + .unwrap() + .clone(); + let index = dataset + .open_vector_index("vector", &metadata.uuid, &NoOpMetricsCollector) + .await + .unwrap(); + index.statistics().unwrap()["index_file_version"] + .as_str() + .unwrap() + .to_string() + }; + assert_eq!(index_file_version, expected_index_version); + + let plan = table + .dataset() + .unwrap() + .get() + .await + .unwrap() + .scan() + .nearest("vector", &Float32Array::from(query_vector.clone()), 5) + .unwrap() + .create_plan() + .await + .unwrap(); + let mut ann_plans = Vec::new(); + find_ann_plans(plan.as_ref(), &mut ann_plans); + assert!(!ann_plans.is_empty()); + + let approximate = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(5) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let refined = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(5) + .refine_factor(1) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let approximate_distances = distances(&approximate); + let refined_distances = distances(&refined); + assert_eq!(approximate_distances.len(), 5); + assert_eq!(approximate_distances.len(), refined_distances.len()); + for (approximate, refined) in approximate_distances.iter().zip(&refined_distances) { + assert!( + (approximate - refined).abs() < 1e-5, + "approximate cosine distance {approximate} did not use the public scale; refined distance was {refined}" + ); + } + + // Distance range bounds are public cosine distances too. Lance applies them to + // internal ANN scores, so the planner must translate the bounds before execution. + let nearest = approximate_distances[0]; + let ranged = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(1) + .distance_range(Some(nearest - 1e-5), Some(nearest + 1e-5)) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let ranged_distances = distances(&ranged); + assert_eq!(ranged_distances.len(), 1); + assert!((ranged_distances[0] - nearest).abs() < 1e-5); + + if !legacy { + fn batch_distances_by_query( + batches: &[RecordBatch], + query_count: usize, + ) -> Vec> { + let mut distances = vec![Vec::new(); query_count]; + for batch in batches { + let query_index_column = batch["query_index"].as_primitive::(); + let distance_column = batch[DIST_COL].as_primitive::(); + for row in 0..batch.num_rows() { + let query_index = query_index_column.value(row) as usize; + distances[query_index].push(distance_column.value(row)); + } + } + distances + } + + fn sorted(mut values: Vec) -> Vec { + values.sort_by(|left, right| left.partial_cmp(right).unwrap()); + values + } + + let batch_query = table + .vector_search(query_vector.as_slice()) + .unwrap() + .add_query_vector(query_vector.as_slice()) + .unwrap() + .nprobes(1) + .unwrap() + .limit(5); + let batch_plan = batch_query.explain_plan(false).await.unwrap(); + assert!(batch_plan.contains("ANNIvfBatch"), "{batch_plan}"); + let batched = batch_query + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let batched_distances = batch_distances_by_query(&batched, 2); + let expected_distances = sorted(approximate_distances.clone()); + for (query_index, actual) in batched_distances.into_iter().enumerate() { + assert_eq!( + actual.len(), + expected_distances.len(), + "query {query_index} returned the wrong number of rows" + ); + for (actual, expected) in sorted(actual).into_iter().zip(&expected_distances) { + assert!( + (actual - expected).abs() < 1e-5, + "batch distance {actual} for query {query_index} must use single-query public scale {expected}" + ); + } + } + + let batched_ranged = table + .vector_search(query_vector.as_slice()) + .unwrap() + .add_query_vector(query_vector.as_slice()) + .unwrap() + .nprobes(1) + .unwrap() + .limit(1) + .distance_range(None, Some(nearest + 1e-5)) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let batched_ranged_distances = batch_distances_by_query(&batched_ranged, 2); + for (query_index, query_distances) in batched_ranged_distances.into_iter().enumerate() { + assert_eq!( + query_distances.len(), + 1, + "public cosine range must return one hit for query {query_index}" + ); + assert!( + (query_distances[0] - nearest).abs() < 1e-5, + "ranged batch distance {} for query {query_index} must match {nearest}", + query_distances[0] + ); + } + } + + let refined_ranged = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(1) + .refine_factor(1) + .distance_range(None, Some(nearest + 1e-5)) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + distances(&refined_ranged).len(), + 1, + "refinement must not apply public cosine bounds to internal ANN scores" + ); + + let aliased = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(1) + .select(Select::dynamic(&[("aliased_distance", "_distance")])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let batch = &aliased[0]; + let aliased_distance = batch["aliased_distance"] + .as_primitive::() + .value(0); + let public_distance = batch[DIST_COL].as_primitive::().value(0); + assert!( + (aliased_distance - public_distance).abs() < 1e-5, + "distance aliases and auto-projected distances must use the same public scale" + ); + + // Appended rows take an exact fallback branch. Its public range filter must stay + // independent of the translated ANN bounds before both branches are merged. + let mut orthogonal = normalized_vector(&mut state, dimension); + let projection = orthogonal + .iter() + .zip(&query_vector) + .map(|(left, right)| left * right) + .sum::(); + for (value, query_value) in orthogonal.iter_mut().zip(&query_vector) { + *value -= projection * query_value; + } + let norm = orthogonal + .iter() + .map(|value| value * value) + .sum::() + .sqrt(); + orthogonal.iter_mut().for_each(|value| *value /= norm); + let appended_vectors = Arc::new(fixed_size_list_array(orthogonal, dimension as i32)); + let appended = RecordBatch::try_new( + schema, + vec![Arc::new(Int32Array::from(vec![num_rows])), appended_vectors], + ) + .unwrap(); + table.add(appended).execute().await.unwrap(); + + let mixed = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(5) + .distance_range(None, Some(nearest + 1e-5)) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mixed_distances = distances(&mixed); + assert_eq!(mixed_distances.len(), 1); + assert!((mixed_distances[0] - nearest).abs() < 1e-5); + } #[tokio::test] async fn test_create_plan_applies_approx_mode_to_ann_query() { diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 0cc240291..d348a6668 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -120,16 +120,19 @@ pub(super) async fn create_lsm_plan( } else { plain_plan( &ds_ref, + &details, &query, pk_columns.clone(), snapshots, in_memory, - limit, - offset, ) .await? }; + // Normalize cosine ANN arms before LSM merge and sort nodes compare their + // distances with exact SSTable and memtable arms. + let plan = super::normalize_cosine_ann_branches(plan).await?; + // Lance appends the primary-key columns internally for dedup and keeps them in // the output; drop the ones the user did not request so the projection matches. restore_projection(plan, &query, &pk_columns) @@ -300,8 +303,13 @@ async fn build_read_context( let mut snapshots: Vec = Vec::new(); for shard_id in shard_ids { - let manifest_store = - ShardManifestStore::new(store.clone(), &base_path, shard_id, scan_batch_size); + let manifest_store = ShardManifestStore::new( + store.clone(), + &base_path, + &details.dir_id, + shard_id, + scan_batch_size, + ); if let Some(manifest) = manifest_store.latest().await? { snapshots.push(snapshot_from_manifest(shard_id, &manifest, &exclude)); } @@ -320,8 +328,11 @@ async fn build_read_context( // Override the active shard with the cached writer's in-memory view. let mut in_memory: HashMap = HashMap::new(); if !wal_only - && let Some((shard_id, manifest, memtables)) = - table.dataset.shard_writer().read_snapshot().await? + && let Some((shard_id, manifest, memtables)) = table + .dataset + .shard_writer() + .read_snapshot(&details.dir_id) + .await? { if let Some(manifest) = manifest { let snapshot = snapshot_from_manifest(shard_id, &manifest, &exclude); @@ -380,12 +391,14 @@ fn as_i64(value: Option) -> Option { /// scanner's `create_plan`. fn base_scanner( dataset: &Dataset, + dir_id: &str, query: &VectorQueryRequest, pk_columns: Vec, snapshots: Vec, in_memory: HashMap, ) -> Result { - let mut scanner = LsmScanner::new(Arc::new(dataset.clone()), snapshots, pk_columns); + let mut scanner = LsmScanner::new(Arc::new(dataset.clone()), snapshots, pk_columns) + .with_mem_wal_dir_id(dir_id); for (shard_id, memtables) in in_memory { scanner = scanner.with_in_memory_memtables(shard_id, memtables); } @@ -431,15 +444,21 @@ fn enrich_filter_error(error: DataFusionError, schema: &ArrowSchema, context: &s /// The plain scan applies limit and offset inside the planner. async fn plain_plan( dataset: &Dataset, + details: &MemWalIndexDetails, query: &VectorQueryRequest, pk_columns: Vec, snapshots: Vec, in_memory: HashMap, - limit: Option, - offset: Option, ) -> Result> { - let scanner = base_scanner(dataset, query, pk_columns, snapshots, in_memory)? - .limit(as_i64(limit), as_i64(offset))?; + let scanner = base_scanner( + dataset, + &details.dir_id, + query, + pk_columns, + snapshots, + in_memory, + )? + .limit(as_i64(query.base.limit), as_i64(query.base.offset))?; Ok(scanner.create_plan().await?) } @@ -487,10 +506,17 @@ async fn fts_plan( }); } - let scanner = base_scanner(dataset, query, pk_columns, snapshots, in_memory)? - .with_overfetch_factor(LSM_OVERFETCH_FACTOR) - .full_text_search(fts)? - .limit(as_i64(limit), as_i64(offset))?; + let scanner = base_scanner( + dataset, + &details.dir_id, + query, + pk_columns, + snapshots, + in_memory, + )? + .with_overfetch_factor(LSM_OVERFETCH_FACTOR) + .full_text_search(fts)? + .limit(as_i64(limit), as_i64(offset))?; Ok(scanner.create_plan().await?) } @@ -736,10 +762,17 @@ async fn vector_plan( // Guard `k` to at least 1 so a degenerate `limit(0)` is trimmed by `limit` // below rather than rejected by `nearest`. let k = limit.unwrap_or(DEFAULT_TOP_K).max(1); - let mut scanner = base_scanner(dataset, query, pk_columns, snapshots, in_memory)? - .with_overfetch_factor(LSM_OVERFETCH_FACTOR) - .nearest(&column, query_vector.as_ref(), k)? - .distance_metric(distance_type.into()); + let mut scanner = base_scanner( + dataset, + &details.dir_id, + query, + pk_columns, + snapshots, + in_memory, + )? + .with_overfetch_factor(LSM_OVERFETCH_FACTOR) + .nearest(&column, query_vector.as_ref(), k)? + .distance_metric(distance_type.into()); if let Some(nprobes) = query.nprobes { scanner = if query.maximum_nprobes == Some(0) { scanner.minimum_nprobes(nprobes) diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index dc3d68010..c896d6427 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -77,6 +77,7 @@ pub(crate) async fn execute_refresh_column( table: &NativeTable, column: &str, ) -> Result { + crate::require_experimental_functions()?; Ok(execute_refresh_column_with_source(table, column) .await? .result) @@ -300,6 +301,7 @@ pub(crate) async fn execute_refresh_column_async( table: &NativeTable, column: &str, ) -> Result> { + crate::require_experimental_functions()?; // Validate before spawning so bad input is reported by this call rather // than only by the job. table.dataset.ensure_mutable()?; @@ -366,7 +368,8 @@ 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 remote server Job".into(), + message: "registered Function columns are refreshed only by a LanceDB Distributed job" + .into(), }), ComputedColumnKind::Unrecognized { kind } => Err(Error::NotSupported { message: format!( @@ -731,6 +734,10 @@ mod tests { /// must not bake zeros from `a`'s placeholder null. It is refused, and /// names the input, until `a` is filled -- after every append too. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_dependent_refresh_refuses_an_unfilled_input() { let table = table_with("dependent_refresh_order", vec![1, 2, 3]).await; table @@ -766,6 +773,10 @@ mod tests { /// declaration metadata and the dependency check: the recorded inputs /// are matched by name, never re-parsed as SQL. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_dependent_refresh_handles_awkward_column_names() { use arrow_array::{Int32Array, StructArray}; use arrow_schema::{DataType, Field, Fields}; @@ -820,6 +831,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_fills_a_declared_column() { let table = table_with("refresh_fills", vec![1, 2, 3]).await; let declared = declare_doubled(&table).await.unwrap(); @@ -848,6 +863,10 @@ mod tests { /// Values written after the last refresh must be reachable by another one. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_fills_rows_appended_since_the_last_refresh() { let table = table_with("refresh_appended", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -868,6 +887,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_with_nothing_to_fill() { let table = table_with("refresh_noop", vec![1, 2, 3]).await; declare_doubled(&table).await.unwrap(); @@ -884,6 +907,10 @@ mod tests { /// A branch inherits the freshness main recorded: its first refresh /// fills nothing, and only its own appends after that. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_branch_inherits_freshness() { let dir = tempfile::tempdir().unwrap(); let conn = connect(dir.path().to_str().unwrap()) @@ -919,6 +946,10 @@ mod tests { /// A shallow clone inherits the freshness its source recorded. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_shallow_clone_inherits_freshness() { let dir = tempfile::tempdir().unwrap(); let conn = connect(dir.path().to_str().unwrap()) @@ -953,6 +984,10 @@ mod tests { /// settles at once instead of re-selecting the same rows forever: the /// second refresh finds the fragment signed and moves nothing. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_converges_on_a_null_result() { let table = table_with("refresh_null_result", vec![1, 2, 3]).await; let declared = table @@ -976,6 +1011,10 @@ mod tests { /// A filled row whose input moved is recomputed: the update rewrites /// the row into a fragment the stamp never signed, and only that one. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_recomputes_a_row_whose_input_moved() { let table = table_with("refresh_mutation", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1009,6 +1048,10 @@ mod tests { /// Each stamp is a sidecar under `_computed/`; pruning old versions /// removes the sidecars only they referenced, and keeps the current one. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_pruning_drops_the_sidecars_of_pruned_versions() { let dir = tempfile::tempdir().unwrap(); let conn = connect(dir.path().to_str().unwrap()) @@ -1050,6 +1093,10 @@ mod tests { /// Absolute timestamp pruning applies the same computed-column sidecar /// cleanup as duration-based pruning. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_absolute_pruning_drops_the_sidecars_of_pruned_versions() { let dir = tempfile::tempdir().unwrap(); let conn = connect(dir.path().to_str().unwrap()) @@ -1087,6 +1134,10 @@ mod tests { /// A deleted row is never computed and the rows that stay keep their /// values: a delete recomputes nothing and stamps nothing. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_delete_recomputes_nothing() { let table = table_with("refresh_delete", vec![1, 2, 3]).await; declare_doubled(&table).await.unwrap(); @@ -1106,6 +1157,10 @@ mod tests { /// signed ones is fresh: the refresh recomputes nothing and only records /// the new fragment. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_compaction_of_signed_fragments_recomputes_nothing() { let table = table_with("refresh_compact_signed", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1136,6 +1191,10 @@ mod tests { /// refresh keeps the null-fill contract and enrolls what it read from; /// from then on a moved input is recomputed like any other. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_an_unsigned_column_is_enrolled_by_its_first_refresh() { let table = table_with("refresh_legacy", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1188,6 +1247,10 @@ mod tests { /// column as null behind a covering data file. Those rows are still /// unfilled and a later refresh has to reach them. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_update_before_the_first_refresh() { let table = table_with("refresh_update_first", vec![1]).await; declare_doubled(&table).await.unwrap(); @@ -1203,6 +1266,10 @@ mod tests { /// for any of its rows: every live row is recomputed, the moved one /// included. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_compaction_of_an_unsigned_fragment_recomputes_it() { let table = table_with("refresh_mixed", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1236,6 +1303,10 @@ mod tests { /// computed column. Compaction cannot certify it, so the product is /// recomputed and the supplied value replaced. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_raw_append_values_are_not_trusted_after_compaction() { use arrow_array::RecordBatchIterator; use lance::Dataset; @@ -1288,6 +1359,10 @@ mod tests { /// An appended fragment holds no values, so compacting it into a signed /// one leaves the product fresh: only the appended rows are filled. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_compaction_with_an_appended_fragment_fills_only_its_rows() { let table = table_with("refresh_preserves", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1311,6 +1386,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_leaves_deleted_rows_alone() { let table = table_with("refresh_deleted", vec![1, 2, 3, 4]).await; declare_doubled(&table).await.unwrap(); @@ -1325,6 +1404,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_a_constant_expression() { let table = table_with("refresh_constant", vec![1, 2, 3]).await; table @@ -1341,6 +1424,10 @@ mod tests { /// A name needing quotes reaches the evaluator intact: it is carried as a /// projection alias, never spliced into SQL text. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_a_column_whose_name_needs_quoting() { let table = table_with("refresh_quoted", vec![1, 2, 3]).await; table @@ -1362,6 +1449,10 @@ mod tests { /// the probe buffers only until the first gained value and the rest flows /// through write_columns a batch at a time. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_streams_a_multi_batch_fragment() { let values: Vec = (0..20_000).collect(); let table = table_with("refresh_multi_batch", values.clone()).await; @@ -1381,6 +1472,10 @@ mod tests { /// The gate's reproducer: the commit must reuse the configured session, /// or registrations and caches vanish from the handle after a refresh. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_preserves_the_configured_session() { let session = Arc::new(lance::session::Session::default()); let conn = crate::connect("memory://") @@ -1404,6 +1499,10 @@ mod tests { /// The async form's job settles with the fill visible, like /// create_index's execute_async. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_async_job_waits_for_the_fill() { let table = table_with("refresh_async", vec![1, 2, 3]).await; declare_doubled(&table).await.unwrap(); @@ -1426,6 +1525,10 @@ mod tests { /// Bad input is reported by the call, not by the job. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_async_rejects_bad_input_before_spawning() { let table = table_with("refresh_async_bad", vec![1, 2, 3]).await; @@ -1437,6 +1540,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_async_job_reports_success_to_every_waiter() { let table = table_with("refresh_async_waiters", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1449,6 +1556,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_rejects_a_plain_column() { let table = table_with("refresh_plain", vec![1, 2, 3]).await; let err = table.refresh_column("x").await.unwrap_err(); @@ -1456,6 +1567,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_rejects_an_unknown_column() { let table = table_with("refresh_missing", vec![1, 2, 3]).await; let err = table.refresh_column("nope").await.unwrap_err(); @@ -1465,6 +1580,10 @@ mod tests { /// The gate's reproducer: a poison value in a deleted row must not /// abort filling the live rows, since nobody can read it. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_deleted_rows_value_is_never_evaluated() { let table = table_with("refresh_deleted_poison", vec![1, 0]).await; table @@ -1484,6 +1603,10 @@ mod tests { /// input did not move is not: the untouched fragment is never read, so /// its poison input is never reached. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_only_a_moved_rows_value_is_re_evaluated() { let table = table_with("refresh_filled_poison", vec![1, 0]).await; table @@ -1515,6 +1638,10 @@ mod tests { /// The gate's reproducer: the old internal projection alias is an /// ordinary column name; a computed column may use it. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_a_column_named_like_the_old_alias() { let table = table_with("refresh_alias_name", vec![1, 2]).await; table @@ -1537,6 +1664,10 @@ mod tests { /// this pins behaviorally; the memory bound is structural -- the fill /// stream retains no batches at all. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_fills_a_late_gain_fragment() { let values: Vec = (0..20_000).collect(); let table = table_with("refresh_late_gain", values).await; @@ -1562,6 +1693,10 @@ mod tests { /// The gate's reproducer: a nested input declares, refreshes, and guards /// its root against invalidating schema changes. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_nested_input_declares_and_refreshes() { use arrow_array::{Int32Array, StructArray}; use arrow_schema::{DataType, Field, Fields}; @@ -1636,6 +1771,10 @@ mod tests { /// schema_evolution tests); refresh's own check covers a dataset another /// writer left in that state. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_refuses_a_foreign_lsm_state() { use crate::table::RTEWriteSpec; @@ -1666,9 +1805,13 @@ mod tests { assert!(matches!(err, Error::NotSupported { .. })); } - /// After catch-up activation and unset, no spec remains but the catch-up - /// flag still marks retained SSTable rows; refresh refuses on the flag. + /// Rows written through the RTE keep the spec installed, since + /// `disable_rte` refuses while they are unmerged, so refresh refuses. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_refuses_retained_catchup_state() { use crate::table::RTEWriteSpec; @@ -1700,7 +1843,8 @@ mod tests { .when_not_matched_insert_all() .use_rte(true); merge.execute(batch).await.unwrap(); - table.disable_rte().await.unwrap(); + // The RTE holds the written rows, so unsetting it is refused. + table.disable_rte().await.unwrap_err(); super::super::computed_columns::add_foreign_kind(&table, "doubled", "sql").await; let err = table.refresh_column("doubled").await.unwrap_err(); @@ -1713,6 +1857,10 @@ mod tests { /// A declaration of a kind this version cannot evaluate is refused by /// name, rather than mistaken for a plain column or fed to the SQL path. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_rejects_a_kind_it_cannot_evaluate() { let table = table_with("refresh_foreign", vec![1, 2, 3]).await; super::super::computed_columns::add_foreign_kind(&table, "embedding", "udf").await; @@ -1748,6 +1896,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_inherits_and_publishes_blob_output() { use arrow_array::UInt64Array; use lance_arrow::{ @@ -1881,6 +2033,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_inherits_nested_struct_blob_input() { use arrow_array::{Int32Array, StructArray, UInt64Array}; use arrow_schema::{DataType, Field, Fields, Schema}; @@ -1946,6 +2102,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_preserves_list_shape_when_materializing_blob_input() { use arrow_array::{Int32Array, ListArray}; use arrow_buffer::{OffsetBuffer, ScalarBuffer}; @@ -2007,6 +2167,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_inherits_external_blob_input() { use arrow_array::{Int32Array, StringArray, UInt64Array}; use arrow_schema::{DataType, Field, Schema}; diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index c541a9a43..d78fc5102 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -13,6 +13,7 @@ use lance::dataset::transaction::{Operation, Transaction, UpdateMap, UpdateMapEn use lance::dataset::{ColumnAlteration, CommitBuilder, Dataset, NewColumnTransform}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use std::sync::Arc; use super::computed_columns; use super::{BaseTable, NativeTable}; @@ -128,9 +129,12 @@ pub(crate) async fn execute_add_columns( pub(crate) async fn execute_declare( table: &NativeTable, columns: &[(String, String)], + options: computed_columns::ComputedColumnOptions, ) -> Result { use lance::dataset::mem_wal::DatasetMemWalExt; + crate::require_experimental_functions()?; + // An RTE write spec keeps visible rows in tiers refresh cannot reach; // checked against latest committed state, not this handle's snapshot. table.checkout_latest().await?; @@ -157,6 +161,10 @@ pub(crate) async fn execute_declare( }); } let transform = computed_columns::declare(table.schema().await?, columns)?; + let NewColumnTransform::AllNulls(schema) = transform else { + unreachable!("declarations are all-null") + }; + let transform = NewColumnTransform::AllNulls(Arc::new(options.apply_to_schema(&schema)?)); commit_add_columns(table, transform, None).await } @@ -453,96 +461,16 @@ mod tests { use crate::function::FunctionBinding; use crate::query::{ExecutableQuery, QueryBase, Select}; use crate::table::NewColumnTransform; + use crate::table::computed_columns::test_support::{ + bound_table, stamp_bindings, text_features_binding, + }; use crate::table::computed_columns::{ - FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, FUNCTION_BINDINGS_META_KEY, - ensure_supported_function_metadata, function_bindings, function_bindings_metadata, - function_computed_column_metadata, is_declaration_key, + FUNCTION_BINDINGS_META_KEY, ensure_supported_function_metadata, function_bindings, + is_declaration_key, }; use crate::{Error, Table}; use std::collections::HashMap; - /// A table carrying the fixture binding: `title` and `body` are its - /// inputs, `search_text` and `search_token_count` its outputs, `spare` - /// nobody's. Stamped the way the server does it, since no local path - /// declares a binding. - async fn bound_table() -> Table { - let conn = connect("memory://").execute().await.unwrap(); - let batch = record_batch!( - ("title", Utf8, ["a"]), - ("body", Utf8, ["b"]), - ("search_text", Utf8, ["a b"]), - ("search_token_count", Int64, [2]), - ("spare", Int32, [1]) - ) - .unwrap(); - let table = conn.create_table("bound", batch).execute().await.unwrap(); - stamp_bindings(&table, &[text_features_binding("")]).await; - table - } - - /// The fixture binding, its id and output names suffixed so a table can - /// carry more than one. - fn text_features_binding(suffix: &str) -> FunctionBinding { - let raw = include_str!( - "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" - ); - if suffix.is_empty() { - return FunctionBinding::from_json(raw).unwrap(); - } - FunctionBinding::from_json( - &raw.replace("fb_01K3TEXT", &format!("fb_01K3TEXT{suffix}")) - .replace("search_text", &format!("search_text{suffix}")) - .replace("search_token_count", &format!("search_token_count{suffix}")), - ) - .unwrap() - } - - /// Stamp bindings the way the server does it, since no local path - /// declares one: the envelope on the schema, a declaration marker on - /// every output field. - async fn stamp_bindings(table: &Table, bindings: &[FunctionBinding]) { - let native = table.as_native().unwrap(); - let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); - dataset - .update_schema_metadata(vec![( - FUNCTION_BINDINGS_META_KEY.to_string(), - Some(function_bindings_metadata(bindings).unwrap()), - )]) - .await - .unwrap(); - let inputs = ["title".to_string(), "body".to_string()]; - let outputs = bindings - .iter() - .flat_map(|binding| { - let assignment = binding.assignment().map(|assignment| { - ( - assignment.output_name.clone(), - FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, - ) - }); - binding - .outputs() - .iter() - .map(|output| (output.output_name.clone(), output.output_ordinal)) - .chain(assignment) - .map(|(name, ordinal)| { - ( - dataset.schema().field(&name).unwrap().id as u32, - function_computed_column_metadata( - binding.binding_id(), - ordinal, - &inputs, - ), - ) - }) - .collect::>() - }) - .collect::>(); - dataset.replace_field_metadata(outputs).await.unwrap(); - native.dataset.update(dataset); - ensure_supported_function_metadata(&table.schema().await.unwrap()).unwrap(); - } - fn metadata_update(path: &str) -> FieldMetadataUpdate { FieldMetadataUpdate { path: path.into(), @@ -565,12 +493,14 @@ mod tests { .execute() .await .unwrap(); - table - .add_columns() - .computed("derived", "spare * 2") - .execute() - .await - .unwrap(); + if cfg!(feature = "experimental-functions") { + table + .add_columns() + .computed("derived", "spare * 2") + .execute() + .await + .unwrap(); + } table .update_field_metadata(&[metadata_update("eager")]) .await @@ -584,7 +514,10 @@ mod tests { let schema = table.schema().await.unwrap(); ensure_supported_function_metadata(&schema).unwrap(); assert_eq!(function_bindings(&schema).unwrap().len(), 1); - assert!(schema.field_with_name("derived").is_ok()); + assert_eq!( + schema.field_with_name("derived").is_ok(), + cfg!(feature = "experimental-functions") + ); assert!(schema.field_with_name("moved").is_err()); } @@ -652,14 +585,16 @@ mod tests { .await .unwrap_err(), ); - bound( - table - .add_columns() - .computed(column, "1") - .execute() - .await - .unwrap_err(), - ); + if cfg!(feature = "experimental-functions") { + bound( + table + .add_columns() + .computed(column, "1") + .execute() + .await + .unwrap_err(), + ); + } } bound( table diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index cec787ff8..aa325cd7c 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -94,9 +94,10 @@ pub(crate) async fn execute_update( // 1. Snapshot the current dataset let dataset = table.dataset.get().await?; crate::materialized_view::ensure_not_a_view(&table.name, &dataset.schema().metadata, "update")?; - super::computed_columns::ensure_no_function_bindings_for_mutation( + super::computed_columns::ensure_not_function_bound( &arrow_schema::Schema::from(dataset.schema()), "update", + update.columns.iter().map(|(name, _)| name.as_str()), )?; super::computed_columns::ensure_not_written( &arrow_schema::Schema::from(dataset.schema()), @@ -445,4 +446,27 @@ mod tests { tbl.update().column("i", "i+1").execute().await.unwrap(); assert_eq!(0, tbl.count_rows(Some("i == 0".to_string())).await.unwrap()); } + + /// A Function binding protects only the columns it reads or writes; any + /// other column updates as on a plain table. + #[tokio::test] + async fn update_on_a_function_table_refuses_only_bound_columns() { + let table = crate::table::computed_columns::test_support::bound_table().await; + let result = table.update().column("spare", "7").execute().await.unwrap(); + assert_eq!(result.rows_updated, 1); + for column in ["title", "search_text"] { + let err = table + .update() + .column(column, "'x'") + .execute() + .await + .unwrap_err(); + assert!( + matches!(&err, crate::Error::InvalidInput { message } + if message.contains(&format!("update of '{column}'")) + && message.contains("a Function binding reads or writes it")), + "{column}: {err:?}" + ); + } + } } diff --git a/rust/lancedb/src/utils/mod.rs b/rust/lancedb/src/utils/mod.rs index 20f209f2e..ebf3f697b 100644 --- a/rust/lancedb/src/utils/mod.rs +++ b/rust/lancedb/src/utils/mod.rs @@ -686,7 +686,9 @@ impl Stream for TimeoutStream { match &mut self.state { TimeoutState::NotStarted { timeout } => { if timeout.is_zero() { - return std::task::Poll::Ready(Some(Err(Self::timeout_error(timeout)))); + let err = Self::timeout_error(timeout); + self.state = TimeoutState::Completed; + return std::task::Poll::Ready(Some(Err(err))); } let deadline = Box::pin(tokio::time::sleep(*timeout)); self.state = TimeoutState::Started { @@ -1159,6 +1161,8 @@ mod tests { .to_string() .contains("Query timeout") ); + assert!(timeout_stream.next().await.is_none()); + assert!(timeout_stream.next().await.is_none()); } #[tokio::test] @@ -1178,6 +1182,8 @@ mod tests { let result = timeout_stream.next().await.unwrap(); assert!(result.is_err()); assert!(result.unwrap_err().to_string().contains("Query timeout")); + assert!(timeout_stream.next().await.is_none()); + assert!(timeout_stream.next().await.is_none()); } #[tokio::test] diff --git a/rust/lancedb/tests/blob_integration.rs b/rust/lancedb/tests/blob_integration.rs index 8559a0e43..0a4240038 100644 --- a/rust/lancedb/tests/blob_integration.rs +++ b/rust/lancedb/tests/blob_integration.rs @@ -947,12 +947,15 @@ async fn fetch_blobs_rejects_unknown_column() -> Result<()> { Ok(()) } +#[rstest::rstest] +#[case("2.0")] +#[case("2.1")] #[tokio::test] -async fn fetch_blobs_rejects_legacy_v1_blob_column() -> Result<()> { +async fn fetch_blob_apis_read_legacy_v1_blob_column(#[case] storage_version: &str) -> Result<()> { let tmp = tempdir().unwrap(); // Legacy v1 blob columns are only writable at file version <= 2.1. let db = connect(tmp.path().to_str().unwrap()) - .storage_options([(OPT_NEW_TABLE_STORAGE_VERSION, "2.1")]) + .storage_options([(OPT_NEW_TABLE_STORAGE_VERSION, storage_version)]) .execute() .await?; let legacy = Field::new("image", DataType::LargeBinary, true).with_metadata( @@ -963,9 +966,62 @@ async fn fetch_blobs_rejects_legacy_v1_blob_column() -> Result<()> { legacy, ])); let table = db.create_empty_table("t", schema).execute().await?; + table + .add(binary_input_batch( + &[1, 2, 3, 4], + &[Some(b"abcdef"), None, Some(b""), Some(b"uvwxyz")], + )) + .execute() + .await?; - let err = table.fetch_blobs("image", &[0]).await.unwrap_err(); - assert!(err.to_string().contains("legacy blob column")); + assert!(!supports_blob_v2(storage_format_version(&table).await)); + assert_eq!(table.blob_columns().await?, vec!["image"]); + + let pairs = collect_id_rowid(&table).await?; + let by_id = |want: i64| pairs.iter().find(|(id, _)| *id == want).unwrap().1; + let row_ids = [by_id(4), by_id(2), by_id(1), by_id(3), by_id(4)]; + let expected: [Option<&[u8]>; 5] = [ + Some(b"uvwxyz"), + None, + Some(b"abcdef"), + Some(b""), + Some(b"uvwxyz"), + ]; + let bytes = table.fetch_blobs("image", &row_ids).await?; + assert_eq!(bytes.iter().collect::>(), expected); + + let files = table.fetch_blob_files("image", &row_ids).await?; + assert_eq!(files.len(), expected.len()); + for (file, payload) in files.iter().zip(expected) { + match payload { + Some(payload) => { + let file = file.as_ref().unwrap(); + assert_eq!(file.size(), payload.len() as u64); + assert_eq!(file.read().await?.as_ref(), payload); + } + None => assert!(file.is_none()), + } + } + assert_eq!( + files[2].as_ref().unwrap().read_range(1..4).await?.as_ref(), + b"bcd" + ); + + let ranges = table + .fetch_blob_ranges( + "image", + [ + BlobRangeRequest::new(by_id(4), 1, 3), + BlobRangeRequest::new(by_id(2), 0, 0), + BlobRangeRequest::new(by_id(1), 2, 3), + BlobRangeRequest::new(by_id(3), 0, 0), + BlobRangeRequest::new(by_id(4), 0, 2), + ], + ) + .await?; + let expected_ranges: [Option<&[u8]>; 5] = + [Some(b"vwx"), None, Some(b"cde"), Some(b""), Some(b"uv")]; + assert_eq!(ranges.iter().collect::>(), expected_ranges); Ok(()) } @@ -1406,7 +1462,7 @@ async fn v1_blob_descriptors(table: &Table) -> Result Result>)>> { let pairs = sorted_id_rowid(table).await?; let row_ids: Vec = pairs.iter().map(|(_, row_id)| *row_id).collect(); diff --git a/rust/lancedb/tests/datafusion_blob_schema.rs b/rust/lancedb/tests/datafusion_blob_schema.rs new file mode 100644 index 000000000..d51c182f6 --- /dev/null +++ b/rust/lancedb/tests/datafusion_blob_schema.rs @@ -0,0 +1,636 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::Arc; + +use arrow_array::{ + Array, ArrayRef, Int64Array, LargeBinaryArray, ListArray, RecordBatch, StringArray, + StructArray, UInt64Array, cast::AsArray, +}; +use arrow_buffer::{NullBuffer, OffsetBuffer}; +use arrow_schema::{DataType, Field, Schema}; +use arrow_select::concat::concat_batches; +use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_catalog::TableProvider; +use lance_core::{ROW_ADDR, ROW_ID}; +use lance_index::scalar::FullTextSearchQuery; +use lancedb::{ + Table, blob, connect, + database::listing::OPT_NEW_TABLE_STORAGE_VERSION, + table::datafusion::{BaseTableAdapter, BlobSchema}, +}; +use tempfile::{TempDir, tempdir}; + +async fn empty_table(fields: Vec) -> (TempDir, Table) { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = db + .create_empty_table("docs", Arc::new(Schema::new(fields))) + .execute() + .await + .unwrap(); + (tmp, table) +} + +async fn register(ctx: &SessionContext, table: &Table, mode: BlobSchema) { + let adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode); + ctx.deregister_table("docs").unwrap(); + ctx.register_table("docs", Arc::new(adapter)).unwrap(); +} + +async fn sql(ctx: &SessionContext, query: &str) -> RecordBatch { + let batches = ctx.sql(query).await.unwrap().collect().await.unwrap(); + concat_batches(&batches[0].schema(), &batches).unwrap() +} + +async fn planning_error(ctx: &SessionContext, query: &str) -> String { + let error = match ctx.sql(query).await { + Ok(df) => df.create_physical_plan().await.unwrap_err(), + Err(error) => error, + }; + error.to_string() +} + +async fn row_ids(ctx: &SessionContext, table: &Table) -> Vec { + let reader = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID]) + .unwrap(); + ctx.register_table("read_docs", Arc::new(reader)).unwrap(); + sql(ctx, "SELECT _rowid FROM read_docs ORDER BY id") + .await + .column(0) + .as_primitive::() + .values() + .to_vec() +} + +#[tokio::test] +async fn write_mode_inserts_blobs_nulls_omitted_and_reordered_columns() { + let (_tmp, table) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Write).await; + for query in [ + "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", + "INSERT INTO docs VALUES (2, NULL)", + "INSERT INTO docs (id) VALUES (3)", + "INSERT INTO docs SELECT 4, named_struct('data', X'', 'uri', NULL)", + "INSERT INTO docs (payload, id) SELECT named_struct('data', X'627965', 'uri', NULL), 5", + ] { + sql(&ctx, query).await; + } + let ids = row_ids(&ctx, &table).await; + assert_eq!( + table.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![ + Some(b"hi".as_slice()), + None, + None, + Some(b"".as_slice()), + Some(b"bye".as_slice()) + ]) + ); + let batch = sql(&ctx, "SELECT id, payload.size FROM read_docs ORDER BY id").await; + assert_eq!( + batch + .column(1) + .as_primitive::(), + &UInt64Array::from(vec![Some(2), None, None, Some(0), Some(3)]) + ); + assert_eq!( + sql(&ctx, "SELECT count(payload) FROM read_docs") + .await + .column(0) + .as_primitive::() + .value(0), + 3 + ); +} + +#[tokio::test] +async fn write_mode_inserts_two_blobs_in_explicit_column_order() { + let (_tmp, table) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + blob("thumbnail", true), + ]) + .await; + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Write).await; + for query in [ + "INSERT INTO docs (thumbnail, id, payload) SELECT named_struct('data', X'', 'uri', NULL), 1, named_struct('data', X'6869', 'uri', NULL)", + "INSERT INTO docs (id) VALUES (2)", + "INSERT INTO docs VALUES (3, NULL, NULL)", + ] { + sql(&ctx, query).await; + } + let ids = row_ids(&ctx, &table).await; + assert_eq!( + table.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None, None]) + ); + assert_eq!( + table.fetch_blobs("thumbnail", &ids).await.unwrap(), + LargeBinaryArray::from(vec![Some(b"".as_slice()), None, None]) + ); +} + +#[tokio::test] +async fn write_mode_rejects_blob_reads_before_execution_and_supports_scalar_self_insert() { + let (_tmp, table) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Write).await; + sql( + &ctx, + "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", + ) + .await; + sql(&ctx, "INSERT INTO docs VALUES (2, NULL)").await; + let system_adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID, lance_core::ROW_ADDR]) + .unwrap() + .with_blob_schema(BlobSchema::Read); + ctx.register_table("system_docs", Arc::new(system_adapter)) + .unwrap(); + assert_eq!( + sql( + &ctx, + "SELECT id, _rowid, _rowaddr FROM system_docs WHERE id > 0" + ) + .await + .num_rows(), + 2 + ); + for query in [ + "SELECT * FROM docs", + "SELECT payload FROM docs", + "SELECT payload.size FROM docs", + "SELECT payload.data FROM docs", + "SELECT count(payload) FROM docs", + "SELECT id FROM docs WHERE payload IS NULL", + "SELECT id FROM docs WHERE payload.size = 0", + "INSERT INTO docs SELECT id, payload FROM docs", + ] { + let error = planning_error(&ctx, query).await; + assert!( + error.contains("Blob v2 scans require BlobSchema::Read"), + "{query}: {error}" + ); + assert_eq!(table.count_rows(None).await.unwrap(), 2); + } + assert_eq!( + sql(&ctx, "SELECT count(*) FROM docs WHERE id > 0") + .await + .column(0) + .as_primitive::() + .value(0), + 2 + ); + assert_eq!( + sql(&ctx, "SELECT id FROM docs WHERE id = 1") + .await + .num_rows(), + 1 + ); + sql(&ctx, "INSERT INTO docs (id) SELECT id + 100 FROM docs").await; + let ids = row_ids(&ctx, &table).await; + assert_eq!(ids.len(), 4); + assert_eq!( + table.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None, None, None]) + ); +} + +fn blob_inputs(values: Vec>) -> ArrayRef { + let data = LargeBinaryArray::from(values); + let DataType::Struct(fields) = blob("clip", true).data_type().clone() else { + unreachable!() + }; + let len = data.len(); + let nulls = data.nulls().cloned(); + Arc::new(StructArray::new( + fields, + vec![ + Arc::new(data), + Arc::new(StringArray::new_null(len)), + Arc::new(UInt64Array::new_null(len)), + Arc::new(UInt64Array::new_null(len)), + ], + nulls, + )) +} + +#[tokio::test] +async fn nested_blob_projections_require_a_read_adapter() { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let fields = vec![ + Arc::new(Field::new("note", DataType::Utf8, true)), + Arc::new(blob("clip", true)), + ]; + let extra = StructArray::new( + fields.clone().into(), + vec![ + Arc::new(StringArray::from(vec![Some("a"), Some("b"), None])), + blob_inputs(vec![Some(b"hi"), None, Some(b"")]), + ], + Some(NullBuffer::from(vec![true, true, false])), + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("extra", DataType::Struct(fields.into()), true), + ])), + vec![Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(extra)], + ) + .unwrap(); + let table = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Write).await; + // DataFusion requests the same whole parent struct for extra.note and + // extra.clip. Neither can satisfy the writer's advertised scan schema. + for query in [ + "SELECT extra.note FROM docs ORDER BY id", + "SELECT count(extra.note) FROM docs", + "SELECT extra.note || 'x' FROM docs", + "SELECT row_number() OVER (ORDER BY extra.note) FROM docs", + "SELECT extra FROM docs", + "SELECT extra.clip FROM docs", + "SELECT extra.clip.size FROM docs", + "SELECT count(extra.clip) FROM docs", + ] { + let error = planning_error(&ctx, query).await; + assert!( + error.contains("Blob v2 scans require BlobSchema::Read"), + "{query}: {error}" + ); + } + let explain = sql(&ctx, "EXPLAIN SELECT id FROM docs WHERE extra.note = 'a'").await; + let explain = explain + .column(1) + .as_string::() + .iter() + .flatten() + .collect::>() + .join("\n"); + assert!(explain.contains("full_filters=["), "{explain}"); + assert!(!explain.contains("FilterExec"), "{explain}"); + assert_eq!( + sql(&ctx, "SELECT id FROM docs WHERE extra.note = 'a'") + .await + .num_rows(), + 1 + ); + register(&ctx, &table, BlobSchema::Read).await; + let batch = sql(&ctx, "SELECT extra.note FROM docs ORDER BY id").await; + assert_eq!( + batch.column(0).as_string::(), + &StringArray::from(vec![Some("a"), Some("b"), None]) + ); + assert_eq!( + sql(&ctx, "SELECT count(extra.note) FROM docs") + .await + .column(0) + .as_primitive::() + .value(0), + 2 + ); + assert_eq!( + sql(&ctx, "SELECT extra.note FROM docs WHERE extra.note = 'a'") + .await + .num_rows(), + 1 + ); + let reader = Arc::new( + BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(), + ); + let plan = reader.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), reader.schema()); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert!( + batches + .iter() + .all(|batch| batch.schema() == reader.schema()) + ); + let schema = reader.schema(); + ctx.register_table("read_docs", reader).unwrap(); + assert_eq!(sql(&ctx, "SELECT * FROM read_docs").await.schema(), schema); + assert_eq!( + sql(&ctx, "SELECT extra.clip.size FROM read_docs ORDER BY id") + .await + .column(0) + .as_primitive::(), + &UInt64Array::from(vec![Some(2), None, None]) + ); +} + +#[tokio::test] +async fn list_descriptors_match_declared_schema_and_cannot_be_scanned_in_write_mode() { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let list = ListArray::new( + Arc::new(blob("item", true)), + OffsetBuffer::from_lengths([1, 2]), + blob_inputs(vec![Some(b"hi"), None, Some(b"")]), + None, + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "payloads", + list.data_type().clone(), + true, + )])), + vec![Arc::new(list)], + ) + .unwrap(); + let table = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new(); + let reader = Arc::new( + BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(), + ); + let plan = reader.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), reader.schema()); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert!( + batches + .iter() + .all(|batch| batch.schema() == reader.schema()) + ); + ctx.register_table("docs", reader).unwrap(); + assert_eq!( + sql(&ctx, "SELECT count(payloads) FROM docs") + .await + .column(0) + .as_primitive::() + .value(0), + 2 + ); + register(&ctx, &table, BlobSchema::Write).await; + assert!( + planning_error(&ctx, "SELECT payloads FROM docs") + .await + .contains("Blob v2 scans require BlobSchema::Read") + ); + assert_eq!( + sql(&ctx, "SELECT count(*) FROM docs") + .await + .column(0) + .as_primitive::() + .value(0), + 2 + ); +} + +#[tokio::test] +async fn tables_without_blobs_support_inserts_and_full_scans_in_both_modes() { + let (_tmp, table) = empty_table(vec![Field::new("id", DataType::Int64, false)]).await; + let ctx = SessionContext::new(); + for (mode, id) in [(BlobSchema::Read, 1), (BlobSchema::Write, 2)] { + register(&ctx, &table, mode).await; + sql(&ctx, &format!("INSERT INTO docs VALUES ({id})")).await; + let provider = ctx.table_provider("docs").await.unwrap(); + let plan = provider.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), provider.schema()); + assert_eq!( + sql(&ctx, "SELECT * FROM docs").await.num_rows(), + id as usize + ); + } +} + +#[tokio::test] +async fn read_mode_rejects_null_and_omitted_blob_inserts_without_writing() { + let (_tmp, table) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Read).await; + for query in [ + "INSERT INTO docs VALUES (2, NULL)", + "INSERT INTO docs (id) VALUES (3)", + ] { + let error = planning_error(&ctx, query).await; + assert!( + error.contains("SQL INSERT into Blob v2 tables requires BlobSchema::Write"), + "{query}: {error}" + ); + assert_eq!(table.count_rows(None).await.unwrap(), 0); + } +} + +#[tokio::test] +async fn write_mode_inserts_exclude_read_only_builder_columns() { + for mode_first in [false, true] { + for system_first in [false, true] { + let (_tmp, table) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + Field::new("text", DataType::Utf8, true), + blob("payload", true), + ]) + .await; + let mut adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(); + if mode_first { + adapter = adapter.with_blob_schema(BlobSchema::Write); + } + let fts = FullTextSearchQuery::new("hello".into()); + adapter = if system_first { + adapter + .with_system_columns(&[ROW_ID, ROW_ADDR]) + .unwrap() + .with_fts_query(fts) + } else { + adapter + .with_fts_query(fts) + .with_system_columns(&[ROW_ID, ROW_ADDR]) + .unwrap() + }; + let writer = adapter.with_blob_schema(BlobSchema::Write); + let ctx = SessionContext::new(); + ctx.register_table("docs", Arc::new(writer)).unwrap(); + sql( + &ctx, + "INSERT INTO docs SELECT 1, 'hello', named_struct('data', X'6869', 'uri', NULL)", + ) + .await; + sql(&ctx, "INSERT INTO docs (text, id) VALUES ('hello', 2)").await; + let ids = row_ids(&ctx, &table).await; + assert_eq!( + table.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None]) + ); + } + } +} + +#[tokio::test] +async fn legacy_blob_write_mode_rejects_descriptor_scans_and_keeps_scalar_scans() { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .storage_options([(OPT_NEW_TABLE_STORAGE_VERSION, "2.1")]) + .execute() + .await + .unwrap(); + let legacy = Field::new("payload", DataType::LargeBinary, true).with_metadata( + std::collections::HashMap::from([("lance-encoding:blob".into(), "true".into())]), + ); + let table = db + .create_empty_table( + "docs", + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + legacy, + ])), + ) + .execute() + .await + .unwrap(); + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Write).await; + sql(&ctx, "INSERT INTO docs VALUES (1, X'6869')").await; + let writer = ctx.table_provider("docs").await.unwrap(); + assert_eq!(writer.schema().field(1).data_type(), &DataType::LargeBinary); + let error = writer + .scan(&ctx.state(), None, &[], None) + .await + .unwrap_err(); + assert!( + error.to_string().contains("Scan schema mismatch"), + "{error}" + ); + assert!(!error.to_string().contains("Blob v2"), "{error}"); + let plan = writer + .scan(&ctx.state(), Some(&vec![0]), &[], None) + .await + .unwrap(); + assert_eq!( + plan.schema(), + Arc::new(writer.schema().project(&[0]).unwrap()) + ); + assert_eq!( + sql(&ctx, "SELECT id + 1 FROM docs WHERE id = 1") + .await + .column(0) + .as_primitive::() + .value(0), + 2 + ); + assert_eq!( + sql(&ctx, "SELECT count(*) FROM docs") + .await + .column(0) + .as_primitive::() + .value(0), + 1 + ); + register(&ctx, &table, BlobSchema::Read).await; + let reader = ctx.table_provider("docs").await.unwrap(); + let plan = reader.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), reader.schema()); + let DataType::Struct(fields) = reader.schema().field(1).data_type().clone() else { + panic!("expected a legacy descriptor"); + }; + assert_eq!(fields.len(), 2); + assert!(fields.find("position").is_some()); + assert!(fields.find("size").is_some()); + assert_eq!(sql(&ctx, "SELECT * FROM docs").await.num_rows(), 1); +} + +#[tokio::test] +async fn copying_non_null_descriptors_between_tables_commits_no_rows() { + let (_tmp, source) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_batch_size(1) + .with_target_partitions(1), + ); + register(&ctx, &source, BlobSchema::Write).await; + sql( + &ctx, + "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", + ) + .await; + sql(&ctx, "INSERT INTO docs VALUES (2, NULL)").await; + register(&ctx, &source, BlobSchema::Read).await; + let (_dest_tmp, destination) = empty_table( + source + .schema() + .await + .unwrap() + .fields() + .iter() + .map(|f| f.as_ref().clone()) + .collect(), + ) + .await; + let writer = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write); + ctx.register_table("destination", Arc::new(writer)).unwrap(); + let version = destination.version().await.unwrap(); + // The null row is valid and reaches the writer before the non-null + // descriptor. Even if it is written to a fragment, it must not be committed. + let plan = ctx + .sql("INSERT INTO destination SELECT id, payload FROM docs ORDER BY id DESC") + .await + .unwrap() + .create_physical_plan() + .await + .unwrap(); + let error = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap_err(); + assert!(error.to_string().contains("blob"), "{error}"); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + assert_eq!(destination.version().await.unwrap(), version); + sql( + &ctx, + "INSERT INTO destination SELECT id, payload FROM docs WHERE payload IS NULL", + ) + .await; + let ids = row_ids(&ctx, &destination).await; + assert_eq!(ids.len(), 1); + assert_eq!( + destination.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![None::<&[u8]>]) + ); +} diff --git a/rust/lancedb/tests/doc_storage_examples.rs b/rust/lancedb/tests/doc_storage_examples.rs new file mode 100644 index 000000000..dd3acc597 --- /dev/null +++ b/rust/lancedb/tests/doc_storage_examples.rs @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::ops::Range; +use std::sync::Arc; + +use arrow_array::{ + ArrayRef, BinaryArray, Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, +}; + +fn wide_rows(ids: Range) -> anyhow::Result> { + let payload = [b'x'; 1016]; + let batch = RecordBatch::try_from_iter(vec![ + ( + "id", + Arc::new(Int64Array::from_iter_values(ids.clone())) as ArrayRef, + ), + ( + "payload", + Arc::new(BinaryArray::from_iter_values( + ids.map(|_| payload.as_slice()), + )) as ArrayRef, + ), + ])?; + let schema = batch.schema(); + Ok(Box::new(RecordBatchIterator::new( + std::iter::once(Ok(batch)), + schema, + ))) +} + +async fn tune_compaction(table: &lancedb::Table) -> lancedb::Result<()> { + // --8<-- [start:storage_compaction_tuning] + use lancedb::table::{CompactionOptions, OptimizeAction}; + + let desired_fragment_bytes: usize = 64 * 1024; + let average_row_bytes: usize = 1024; // Estimate from representative rows. + let options = CompactionOptions { + target_rows_per_fragment: (desired_fragment_bytes / average_row_bytes).max(1), + batch_size: Some(16), + num_threads: Some(1), + ..Default::default() + }; + table + .optimize(OptimizeAction::Compact { + options, + remap_options: None, + }) + .await?; + // --8<-- [end:storage_compaction_tuning] + Ok(()) +} + +#[tokio::test] +async fn compaction_tuning() -> anyhow::Result<()> { + let directory = tempfile::tempdir()?; + let db = lancedb::connect(directory.path().to_str().unwrap()) + .execute() + .await?; + let table = db + .create_table("compaction_tuning", wide_rows(0..32)?) + .execute() + .await?; + table.add(wide_rows(32..64)?).execute().await?; + assert_eq!(table.stats().await?.fragment_stats.num_fragments, 2); + + tune_compaction(&table).await?; + assert_eq!(table.stats().await?.fragment_stats.num_fragments, 1); + assert_eq!(table.count_rows(None).await?, 64); + + table.add(wide_rows(64..65)?).execute().await?; + tune_compaction(&table).await?; + assert_eq!(table.stats().await?.fragment_stats.num_fragments, 2); + assert_eq!(table.count_rows(None).await?, 65); + Ok(()) +} diff --git a/rust/lancedb/tests/experimental_functions.rs b/rust/lancedb/tests/experimental_functions.rs new file mode 100644 index 000000000..f7cd022e3 --- /dev/null +++ b/rust/lancedb/tests/experimental_functions.rs @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +#![cfg(not(feature = "experimental-functions"))] +#![recursion_limit = "256"] + +use std::collections::HashMap; + +use arrow_array::record_batch; +use futures::TryStreamExt; +use lancedb::materialized_view::{ + DEFINITION_META_KEY, definition_metadata_from_sql, prepare_declaration, +}; +use lancedb::table::NewColumnTransform; +use lancedb::table::computed_columns::{ + COMPUTED_COLUMN_META_KEY, EXPRESSION_META_KEY, INPUTS_META_KEY, KIND_META_KEY, computed_columns, +}; +use lancedb::{Error, MaterializedView, Result, connect}; + +fn assert_disabled(result: Result) { + match result { + Err(Error::NotSupported { message }) => { + assert!(message.contains("experimental-functions"), "{message}"); + } + _ => panic!("expected the experimental-functions feature error"), + } +} + +#[tokio::test] +async fn computed_operations_fail_before_mutation_or_job_creation() { + let db = connect("memory://").execute().await.unwrap(); + let table = db + .create_table("source", record_batch!(("x", Int32, [1, 2])).unwrap()) + .execute() + .await + .unwrap(); + let version = table.version().await.unwrap(); + assert_disabled( + table + .add_columns() + .computed("doubled", "x * 2") + .execute() + .await, + ); + assert_disabled(table.refresh_column("x").await); + assert_disabled(table.refresh_column_async("x").await); + assert_eq!(table.version().await.unwrap(), version); + assert_eq!(table.schema().await.unwrap().fields().len(), 1); + + // The eager SQL transform remains an ordinary schema-evolution operation. + table + .add_columns() + .transform(NewColumnTransform::SqlExpressions(vec![( + "eager".into(), + "x * 2".into(), + )])) + .execute() + .await + .unwrap(); + assert_eq!( + table + .count_rows(Some("eager = x * 2".into())) + .await + .unwrap(), + 2 + ); +} + +#[tokio::test] +async fn existing_computed_metadata_remains_readable_and_protected() { + let db = connect("memory://").execute().await.unwrap(); + let table = db + .create_table( + "source", + record_batch!(("x", Int32, [1, 2]), ("doubled", Int32, [2, 4])).unwrap(), + ) + .execute() + .await + .unwrap(); + // Model a table previously written by an enabled build, without enabling + // the feature in this test binary through Cargo feature unification. + let wrapper = table.dataset().unwrap(); + let mut dataset = wrapper.get().await.unwrap().as_ref().clone(); + let field_id = dataset.schema().field("doubled").unwrap().id as u32; + dataset + .replace_field_metadata(vec![( + field_id, + HashMap::from([ + (COMPUTED_COLUMN_META_KEY.into(), "true".into()), + (KIND_META_KEY.into(), "sql".into()), + (EXPRESSION_META_KEY.into(), "x * 2".into()), + (INPUTS_META_KEY.into(), "[\"x\"]".into()), + ]), + )]) + .await + .unwrap(); + wrapper.update(dataset); + let version = table.version().await.unwrap(); + assert_eq!(computed_columns(&table.schema().await.unwrap()).len(), 1); + assert_eq!( + table + .count_rows(Some("doubled = x * 2".into())) + .await + .unwrap(), + 2 + ); + assert_disabled(table.refresh_column("doubled").await); + assert_disabled(table.refresh_column_async("doubled").await); + assert!( + table + .update() + .column("doubled", "42") + .execute() + .await + .is_err() + ); + assert!(table.drop_columns(&["x"]).await.is_err()); + assert_eq!(table.version().await.unwrap(), version); + table.drop_columns(&["doubled"]).await.unwrap(); +} + +#[tokio::test] +async fn views_cannot_be_created_or_refreshed_but_existing_data_is_accessible() { + let db = connect("memory://").execute().await.unwrap(); + let source = db + .create_table("source", record_batch!(("x", Int32, [1, 2])).unwrap()) + .execute() + .await + .unwrap(); + for with_no_data in [false, true] { + assert_disabled( + db.create_materialized_view("blocked", "source") + .with_no_data(with_no_data) + .execute() + .await, + ); + assert_disabled( + db.create_materialized_view("blocked", "source") + .with_no_data(with_no_data) + .execute_async() + .await, + ); + } + let prepared = prepare_declaration(&source, None, None, None) + .await + .unwrap(); + assert_disabled(prepared.clone().create("blocked").await); + assert_disabled(prepared.create_in(&[], "blocked").await); + assert!(matches!( + db.open_table("blocked").execute().await, + Err(Error::TableNotFound { .. }) + )); + + let table = db + .create_table("existing", record_batch!(("x", Int32, [1, 2])).unwrap()) + .execute() + .await + .unwrap(); + let wrapper = table.dataset().unwrap(); + let mut dataset = wrapper.get().await.unwrap().as_ref().clone(); + dataset + .update_schema_metadata(vec![( + DEFINITION_META_KEY.into(), + Some(definition_metadata_from_sql("SELECT x FROM source")), + )]) + .await + .unwrap(); + wrapper.update(dataset); + let version = table.version().await.unwrap(); + let view = MaterializedView::from_table(table.clone()).await.unwrap(); + assert_disabled(view.refresh().execute().await); + assert_disabled(view.refresh().execute_async().await); + assert_eq!(table.version().await.unwrap(), version); + assert_eq!(view.table().count_rows(None).await.unwrap(), 2); + assert_eq!( + db.open_materialized_view("existing") + .await + .unwrap() + .definition_sql(), + "SELECT x FROM source" + ); + assert_eq!( + db.list_materialized_views(Default::default()) + .try_collect::>() + .await + .unwrap(), + vec!["existing"] + ); + assert!( + table + .add(record_batch!(("x", Int32, [3])).unwrap()) + .execute() + .await + .is_err() + ); + assert!(table.delete("true").await.is_err()); + db.drop_materialized_view("existing", &[]).await.unwrap(); +} diff --git a/rust/lancedb/tests/nullable_struct_merge.rs b/rust/lancedb/tests/nullable_struct_merge.rs new file mode 100644 index 000000000..c245b1c2c --- /dev/null +++ b/rust/lancedb/tests/nullable_struct_merge.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::Arc; + +use arrow_array::{Array, ArrayRef, BooleanArray, Int32Array, RecordBatch, StructArray}; +use arrow_buffer::NullBuffer; +use arrow_schema::{DataType, Field, Schema}; +use lance_arrow::RecordBatchExt; + +#[test] +fn merge_nullable_struct_with_sliced_boolean_child() { + let left_struct = StructArray::new( + vec![Field::new("id", DataType::Int32, false)].into(), + vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as ArrayRef], + None, + ); + + // BooleanArray retains its offset when sliced. The merged child bitmap must + // cover that offset as well as the four visible rows. + let boolean_child: ArrayRef = Arc::new(BooleanArray::from_iter((0..1030).map(|index| { + if index == 1027 { + None + } else { + Some(index % 2 == 1) + } + }))); + let boolean_child = boolean_child.slice(1025, 4); + assert_eq!(boolean_child.offset(), 1025); + let right_struct = StructArray::new( + vec![Field::new("flag", DataType::Boolean, true)].into(), + vec![boolean_child], + Some(NullBuffer::from(vec![true, false, true, true])), + ); + + let left_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "nested", + left_struct.data_type().clone(), + true, + )])), + vec![Arc::new(left_struct)], + ) + .unwrap(); + let right_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "nested", + right_struct.data_type().clone(), + true, + )])), + vec![Arc::new(right_struct)], + ) + .unwrap(); + + let merged = left_batch.merge(&right_batch).unwrap(); + let nested = merged.column_by_name("nested").unwrap(); + let nested = nested.as_any().downcast_ref::().unwrap(); + let flag = nested.column_by_name("flag").unwrap(); + let flag = flag.as_any().downcast_ref::().unwrap(); + assert_eq!( + flag.iter().collect::>(), + vec![Some(true), None, None, Some(false)] + ); +} diff --git a/rust/lancedb/tests/registered_scalar_plugin.rs b/rust/lancedb/tests/registered_scalar_plugin.rs new file mode 100644 index 000000000..2f5620cc8 --- /dev/null +++ b/rust/lancedb/tests/registered_scalar_plugin.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use arrow_array::{RecordBatchIterator, record_batch}; +use lance::{Dataset, index::DatasetIndexExt}; +use lance_index::scalar::ScalarIndexParams; +use lancedb::index::IndexType; + +// MinHashLSH is a registered scalar plugin without a LanceDB IndexType variant. +// It exercises the same metadata-only fallback as a downstream plugin. +#[tokio::test] +async fn list_registered_scalar_plugin_with_its_type_name() { + let directory = tempfile::tempdir().unwrap(); + let batch = record_batch!(( + "value", + Utf8, + ["alpha beta", "beta gamma", "gamma delta", "delta alpha"] + )) + .unwrap(); + let mut dataset = Dataset::write( + RecordBatchIterator::new([Ok(batch.clone())], batch.schema()), + directory.path().join("test.lance").to_str().unwrap(), + None, + ) + .await + .unwrap(); + dataset + .create_index_builder( + &["value"], + lance_index::IndexType::Scalar, + &ScalarIndexParams::new("minhashlsh".into()), + ) + .name("profile".into()) + .train(false) + .await + .unwrap(); + + let connection = lancedb::connect(directory.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = connection.open_table("test").execute().await.unwrap(); + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + assert_eq!(indices[0].name, "profile"); + assert_eq!( + indices[0].index_type, + IndexType::Custom("MinHashLsh".into()) + ); + assert_eq!(indices[0].index_type.to_string(), "MinHashLsh"); + assert_eq!(indices[0].columns, ["value"]); + assert!( + indices[0] + .type_url + .as_deref() + .unwrap() + .ends_with("MinHashLshIndexDetails") + ); + let statistics = table.index_stats("profile").await.unwrap().unwrap(); + assert_eq!( + statistics.index_type, + IndexType::Custom("MinHashLsh".into()) + ); + assert_eq!(statistics.num_indexed_rows, 0); + assert_eq!(statistics.num_unindexed_rows, 4); +}