From c136022c7b8645d5ce0d0b5db8a21e8587b6b2c9 Mon Sep 17 00:00:00 2001 From: Shu Chen Date: Thu, 19 Nov 2026 14:18:10 -0500 Subject: [PATCH 01/18] ci: pin third-party GitHub Actions to full commit SHAs (#4922) Pin every remaining third-party action reference in `.github/` to a full 40-character commit SHA, with the intended version in a trailing comment (`uses: owner/action@ # vX.Y.Z`), following the pins already in `cli.yml`, `typos.yml` and `make-release-commit.yml`. Fixes #3293. 53 references across 13 files change, covering 16 actions, including the branch refs called out in the issue (`dtolnay/rust-toolchain@master`, `@stable`) and `pypa/gh-action-pypi-publish@release/v1`. Each SHA is the commit its current tag or branch resolves to today, so the code that runs is unchanged. Comments name the most specific tag on that commit (for example `v2.9.3` for `Swatinem/rust-cache@v2`); where no such tag exists, they keep the original ref (`v1` for `srvaroa/labeler` and `rui314/setup-mold`, `v3` for `addnab/docker-run-action`, `stable`/`master` for `dtolnay/rust-toolchain`). The `stable` branch of `dtolnay/rust-toolchain` defaults its `toolchain` input to `stable`, so pinning its SHA keeps the `nodejs.yml` step that passes no toolchain on stable. GitHub-maintained `actions/*` references are left on their tags, as in the existing pins. Keeping SHAs current through Dependabot is the sibling issue and is not part of this change. Validation: - No third-party `uses:` reference in `.github/` is left without a 40-character SHA (53 before, 0 after). - For all 23 distinct third-party pins in `.github/`, `git ls-remote` against the upstream repository confirms the SHA is the commit that the commented tag or branch points to. A deliberately altered SHA and a reverted tag ref were both caught. - `pre-commit run` on the changed files passes (check-yaml, end-of-file, trailing whitespace, typos). - actionlint 1.7.12 reports the same 35 findings on `main` and on this branch, all of them existing ones (custom runner labels and composite actions under `workflows/`). It reports none for this change. --- .../workflows/build_linux_wheel/action.yml | 4 +-- .github/workflows/build_mac_wheel/action.yml | 2 +- .../workflows/build_windows_wheel/action.yml | 2 +- .github/workflows/cargo-publish.yml | 4 +-- .../codex-update-lance-dependency.yml | 2 +- .github/workflows/dev.yml | 4 +-- .github/workflows/docs.yml | 2 +- .github/workflows/gh-release.yml | 4 +-- .github/workflows/nodejs.yml | 20 ++++++------ .github/workflows/npm-publish.yml | 18 +++++------ .github/workflows/pypi-publish.yml | 4 +-- .github/workflows/python.yml | 8 ++--- .github/workflows/rust.yml | 32 +++++++++---------- 13 files changed, 53 insertions(+), 53 deletions(-) diff --git a/.github/workflows/build_linux_wheel/action.yml b/.github/workflows/build_linux_wheel/action.yml index 44ce82ee5..51cd20ab0 100644 --- a/.github/workflows/build_linux_wheel/action.yml +++ b/.github/workflows/build_linux_wheel/action.yml @@ -54,7 +54,7 @@ runs: grep '^name = ' python/pyproject.toml - name: Build x86_64 Manylinux wheel if: ${{ inputs.arm-build == 'false' }} - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: build @@ -72,7 +72,7 @@ runs: /usr/local/bin/protoc --version - name: Build Arm Manylinux Wheel if: ${{ inputs.arm-build == 'true' }} - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: build diff --git a/.github/workflows/build_mac_wheel/action.yml b/.github/workflows/build_mac_wheel/action.yml index 727cd190c..ba7b7b1c5 100644 --- a/.github/workflows/build_mac_wheel/action.yml +++ b/.github/workflows/build_mac_wheel/action.yml @@ -14,7 +14,7 @@ runs: steps: - uses: ./.github/actions/setup-protoc - name: Build wheel - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: command: build maturin-version: "1.12.4" diff --git a/.github/workflows/build_windows_wheel/action.yml b/.github/workflows/build_windows_wheel/action.yml index 3d92d818a..0d061ac59 100644 --- a/.github/workflows/build_windows_wheel/action.yml +++ b/.github/workflows/build_windows_wheel/action.yml @@ -17,7 +17,7 @@ runs: run: git config --global core.longpaths true - uses: ./.github/actions/setup-protoc - name: Build wheel - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: command: build maturin-version: "1.12.4" diff --git a/.github/workflows/cargo-publish.yml b/.github/workflows/cargo-publish.yml index 052fb1876..83593307b 100644 --- a/.github/workflows/cargo-publish.yml +++ b/.github/workflows/cargo-publish.yml @@ -25,14 +25,14 @@ jobs: if: startsWith(github.ref, 'refs/tags/v') steps: - uses: actions/checkout@v6 - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: rust - name: Install dependencies run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rust-lang/crates-io-auth-action@v1 + - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 id: auth - name: Publish the package run: | diff --git a/.github/workflows/codex-update-lance-dependency.yml b/.github/workflows/codex-update-lance-dependency.yml index 79ef84364..ef59213bd 100644 --- a/.github/workflows/codex-update-lance-dependency.yml +++ b/.github/workflows/codex-update-lance-dependency.yml @@ -44,7 +44,7 @@ jobs: run: npm install -g @openai/codex - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: toolchain: stable components: clippy, rustfmt diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index eac4cc4fc..64a6971e6 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -18,7 +18,7 @@ jobs: name: Label PR runs-on: ubuntu-latest steps: - - uses: srvaroa/labeler@v1 + - uses: srvaroa/labeler@9c29ad1ef33d169f9ef33c52722faf47a566bcf3 # v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} commitlint: @@ -30,7 +30,7 @@ jobs: - uses: actions/setup-node@v6 with: node-version: "24" - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 # These rules are disabled because Github will always ensure there diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index fb3fb1d6a..3dc4dab56 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -47,7 +47,7 @@ jobs: python-version: "3.10" cache: "pip" cache-dependency-path: "docs/requirements.txt" - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - name: Build Python working-directory: python run: | diff --git a/.github/workflows/gh-release.yml b/.github/workflows/gh-release.yml index bbaade34c..eedf8450c 100644 --- a/.github/workflows/gh-release.yml +++ b/.github/workflows/gh-release.yml @@ -77,7 +77,7 @@ jobs: echo "from_tag=$FROM_TAG" >> $GITHUB_OUTPUT - name: Create Release Notes id: release_notes - uses: mikepenz/release-changelog-builder-action@v4 + uses: mikepenz/release-changelog-builder-action@32e3c96f29a6532607f638797455e9e98cfc703d # v4.2.2 with: configuration: .github/release_notes.json toTag: ${{ steps.extract_version.outputs.tag }} @@ -85,7 +85,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Create GH release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2 with: # Marking betas as pre-releases keeps them from taking the "Latest" # badge on the releases page. diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 4d28ca4a1..9a21786d2 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -42,7 +42,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -52,14 +52,14 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: components: rustfmt, clippy - name: Install dependencies run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -98,7 +98,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -110,7 +110,7 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -188,7 +188,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -196,7 +196,7 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Same crate, profile and target as the `linux` job above, so reuse # its cache: rust-cache keys on the job id by default, and this job @@ -249,7 +249,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -259,11 +259,11 @@ jobs: cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml # Use the same pinned compiler for cache selection and the native build. - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: cache: false rustflags: "" - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index ac95b5a47..6de291c7d 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -167,7 +167,7 @@ jobs: # Cargo also checks out Lance test fixtures below its git cache path. run: git config --global core.longpaths true - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup node @@ -178,7 +178,7 @@ jobs: cache: pnpm cache-dependency-path: nodejs/pnpm-lock.yaml - name: Install - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable if: ${{ !matrix.settings.docker }} with: toolchain: stable @@ -194,7 +194,7 @@ jobs: # re-runs regardless, since the local crate changes every time, so the # win is larger on the non-LTO jobs than here. - name: Cache cargo (native builds) - uses: Swatinem/rust-cache@v2 + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: ${{ !matrix.settings.docker }} with: # The release profile and per-target dirs differ from what the test @@ -216,7 +216,7 @@ jobs: # that built these artifacts -- safe, since cargo fingerprints the real # one; a base-image bump just costs one cold build. - name: Cache cargo (docker builds) - uses: Swatinem/rust-cache@v2 + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: ${{ matrix.settings.docker }} with: key: docker-${{ matrix.settings.target }} @@ -225,17 +225,17 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - name: Install Zig - uses: mlugg/setup-zig@v2 + uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 if: ${{ contains(matrix.settings.target, 'musl') }} with: version: 0.14.1 - name: Install cargo-zigbuild - uses: taiki-e/install-action@v2 + uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3 if: ${{ contains(matrix.settings.target, 'musl') }} with: tool: cargo-zigbuild - name: Build in docker - uses: addnab/docker-run-action@v3 + uses: addnab/docker-run-action@4f65fabd2431ebc8d299f8e5a018d79a769ae185 # v3 if: ${{ matrix.settings.docker }} with: image: ${{ matrix.settings.docker }} @@ -352,7 +352,7 @@ jobs: steps: - uses: actions/checkout@v6 - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup Node.js 24 for install @@ -404,7 +404,7 @@ jobs: steps: - uses: actions/checkout@v6 - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup node diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 8730e220d..304e96857 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -184,7 +184,7 @@ jobs: with: python-version: "3.12" - name: Build sdist - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: sdist @@ -311,7 +311,7 @@ jobs: # `docker://ghcr.io/:` image reference that GHA tries to pull. - name: Publish to PyPI if: steps.choose_repo.outputs.repo == 'pypi' - uses: pypa/gh-action-pypi-publish@release/v1 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: packages-dir: target/wheels/ report-failure: diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index e208ac7cd..62da9cf6e 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -112,7 +112,7 @@ jobs: # `pip install -e .` builds the extension with maturin, which is most of # this job's ~33 minutes. It had no Rust cache, so every dependency was # recompiled from scratch on every run. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -198,7 +198,7 @@ jobs: python-version: "3.13" # maturin runs cargo natively on macOS (docker is Linux-only), so the host # target dir is cacheable. This job had no Rust cache. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -236,7 +236,7 @@ jobs: # maturin runs cargo natively on Windows (docker is Linux-only), so the # host target dir is cacheable. This job had no Rust cache at all and so # rebuilt every dependency from scratch on every run. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. The repo sits at # GitHub's cache cap, so per-PR saves just evict main's entries. @@ -271,7 +271,7 @@ jobs: python-version: "3.10" # As with Doctest, `pip install -e .` compiles the extension and this job # had no Rust cache, which is most of its ~37 minutes. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 636c1a7bf..b3805b422 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -42,7 +42,7 @@ jobs: timeout-minutes: 15 steps: - uses: actions/checkout@v6 - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 - name: Read the pinned Lance tag id: lance run: | @@ -108,10 +108,10 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -135,7 +135,7 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v6 - - uses: EmbarkStudios/cargo-deny-action@v2 + - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 with: command: check advisories bans licenses sources @@ -151,7 +151,7 @@ jobs: - uses: actions/checkout@v6 # Building without a lock file often requires the latest Rust version since downstream # dependencies may have updated their minimum Rust version. - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: toolchain: "stable" # The explicit cache below runs after lock removal and only saves on main. @@ -159,8 +159,8 @@ jobs: # Remove cargo.lock to force a fresh build - name: Remove Cargo.lock run: rm -f Cargo.lock - - uses: rui314/setup-mold@v1 - - uses: Swatinem/rust-cache@v2 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -208,7 +208,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -218,7 +218,7 @@ jobs: run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rui314/setup-mold@v1 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 - name: Make Swap run: | swapfile=/swapfile @@ -280,7 +280,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Remote tests use a different feature graph from the main Linux # job. Cache downloads, but build into a fresh target directory. @@ -290,7 +290,7 @@ jobs: run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rui314/setup-mold@v1 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 - name: Run remote tests run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests @@ -317,7 +317,7 @@ jobs: python-version: "3.13" - name: CPU features run: sysctl -a | grep cpu - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # PyO3 caches the interpreter library path; runner images can differ. key: ${{ matrix.mac-runner }}-python-${{ steps.python.outputs.python-version }} @@ -358,7 +358,7 @@ jobs: run: git config --global core.longpaths true - name: Set target run: rustup target add ${{ matrix.target }} - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -397,7 +397,7 @@ jobs: run: git config --global core.longpaths true - name: Set target run: rustup target add aarch64-pc-windows-msvc - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -437,10 +437,10 @@ jobs: sudo apt update sudo apt install -y protobuf-compiler libssl-dev - name: Install ${{ matrix.msrv }} - uses: dtolnay/rust-toolchain@master + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master with: toolchain: ${{ matrix.msrv }} - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes From 7d33f7ba9442715e0b00cec8f70a1374b0647149 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 19 Nov 2026 11:25:27 -0800 Subject: [PATCH 02/18] ci: prioritize Rust security updates in dependabot config (#5100) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Dependabot wasn't getting security fixes in, and its Rust PRs were failing CI: - Security updates were disabled for the repo, so ~170 open alerts never got a PR. (Now enabled in repo settings; not part of this diff.) - The `pip` entry for `/python` never touched `uv.lock`, so Python had no Dependabot PRs at all. - With `versioning-strategy: lockfile-only`, breaking bumps such as reqwest 0.12 → 0.13 (#4781), tokenizers 0.19 → 0.23 (#4905), sha2 (#4230) and base64 (#4229) write a `Cargo.lock` that the `Cargo.toml` requirements don't allow. Every `--locked` build then fails before compiling. The priority is Rust, which is statically linked into the shipped binaries. Python and npm deps are resolved in users' environments, so those are best effort. | Entry | Version updates | Security updates | |---|---|---| | cargo `/` | weekly, minor/patch, one group | grouped | | uv `/python` (was `pip`) | monthly, minor/patch, one group | grouped | | npm `/nodejs`, `/nodejs/examples` | monthly, minor/patch, one group | grouped | | docs, docs tests, `/java` | off | grouped | Breaking bumps are excluded with `allow.update-types`, which the docs say applies only to version updates. An `ignore` rule would also suppress security updates. `dependency-type: all` keeps transitive dependencies in scope for security fixes, which also means the weekly cargo PR now bumps transitive crates within their allowed ranges. A security fix that's only available as a breaking bump will still produce a failing PR and need a manual `Cargo.toml` change. ## Merge Risk **Door:** two-way; config only. **Blast Radius:** Dependabot PRs. Config errors only surface after merge, on Dependabot's next run. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .github/dependabot.yml | 165 ++++++++++++++++++++++++++++++----------- 1 file changed, 120 insertions(+), 45 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d625b0698..4f5ff4bd4 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,70 +1,145 @@ version: 2 -# Scope: the root Cargo workspace, which produces the Rust binaries we -# ship to users (the Node.js and Python native extensions). The -# `rust/lancedb` library crate shares the same lockfile; its consumers -# pick their own dependency versions, but bumping transitive deps here -# keeps the binaries we ship current. +# Every entry uses `versioning-strategy: lockfile-only`: bump the lockfile, +# never widen or raise the version requirements in manifests. Those ranges are +# our library consumers' constraints, not ours. +# +# Because of that, version updates are limited to minor and patch bumps. +# A semver-breaking bump (including 0.x minor bumps such as 0.12 -> 0.13) +# can't be satisfied without editing a manifest, so Dependabot would produce a +# lockfile that fails `cargo --locked` and every CI job. We do those by hand. +# This is done with `allow` rather than `ignore` because `allow.update-types` +# only filters version updates; an `ignore` rule would also suppress security +# updates. `dependency-type: all` matters for the same reason: `allow` does +# apply to security updates otherwise, and most advisories are in transitive +# dependencies. +# +# Security updates are grouped so advisories that land together become one PR. +# They ignore `schedule` and `cooldown` and are opened as soon as an advisory +# is published. updates: + # Highest priority: the root Cargo workspace is statically linked into the + # Node.js and Python native extensions we ship, so users can't patch these + # themselves. Weekly updates keep the lockfile close to current, so security + # fixes are usually small patch bumps. - package-ecosystem: cargo directory: / schedule: interval: weekly - open-pull-requests-limit: 10 - # Only update Cargo.lock, never widen/raise the version requirements in - # Cargo.toml. The goal is keeping the lockfile (and the binaries we ship) - # current on security fixes, not forcing our library's consumers onto - # newer minimum versions. + day: wednesday + cooldown: + default-days: 2 versioning-strategy: lockfile-only - groups: - # The arrow-rs and datafusion crates are released in lockstep and have to - # move together, so keep them in one PR instead of one per sub-crate. - # Listed first: a dependency joins the first group it matches. - arrow-datafusion: - patterns: - - arrow - - arrow-* - - parquet - - parquet-* - - datafusion - - datafusion-* - - object_store - rust-minor-patch: + allow: + - dependency-type: all update-types: - - minor - - patch + - version-update:semver-minor + - version-update:semver-patch + groups: + cargo: + applies-to: version-updates + patterns: + - "*" + cargo-security: + applies-to: security-updates + patterns: + - "*" - - package-ecosystem: pip + # Python and Node.js dependencies are resolved in the user's own environment, + # so these lockfiles only affect our dev/test setup. Lower priority: monthly. + - package-ecosystem: uv directory: /python schedule: - interval: weekly - # Only update uv.lock, never widen version requirements in pyproject.toml. + interval: monthly + cooldown: + default-days: 2 versioning-strategy: lockfile-only + allow: + - dependency-type: all + update-types: + - version-update:semver-minor + - version-update:semver-patch groups: - python-deps: + python: + applies-to: version-updates patterns: - "*" - - # The npm ecosystem covers pnpm lockfiles. There are two separate installs: - # the bindings themselves and the examples, which have their own lockfile. - # As with cargo and pip above, only bump the lockfile — the version ranges - # in package.json are our consumers' constraints, not ours. - - package-ecosystem: npm - directory: /nodejs - schedule: - interval: weekly - versioning-strategy: lockfile-only - groups: - nodejs-deps: + python-security: + applies-to: security-updates patterns: - "*" - package-ecosystem: npm - directory: /nodejs/examples + directories: + - /nodejs + - /nodejs/examples schedule: - interval: weekly + interval: monthly + cooldown: + default-days: 2 versioning-strategy: lockfile-only + allow: + - dependency-type: all + update-types: + - version-update:semver-minor + - version-update:semver-patch groups: - nodejs-examples-deps: + nodejs: + applies-to: version-updates + patterns: + - "*" + nodejs-security: + applies-to: security-updates + patterns: + - "*" + + # Docs, docs tests, and Java. Security updates scan these lockfiles whether or + # not they're listed here; these entries only exist to group those PRs. + # `open-pull-requests-limit: 0` turns off version updates. + - package-ecosystem: cargo + directory: /docs/web-tests/rs + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-cargo-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: npm + directories: + - /docs/web-tests/ts + - /docs/web-tests/blob-v2/ts + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-npm-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: pip + directories: + - /docs + - /docs/web-tests/blob-v2/py + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-pip-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: maven + directory: /java + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + maven-security: + applies-to: security-updates patterns: - "*" From 3e712f5105a77a210ba4ff0c172fa6c84fe7fc13 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 19 Nov 2026 11:25:46 -0800 Subject: [PATCH 03/18] fix: bump blob v2 docs test to lancedb 0.42.0-beta.20 (#5102) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary The blob v2 TypeScript docs test pinned `@lancedb/lancedb` `0.41.0-beta.8`, which pulls `@huggingface/transformers` 3.0.2 and `sharp` 0.33.5. Aikido flags that `sharp` with 2 critical and 1 high advisory. Bumping to `0.42.0-beta.20` brings transformers 4.3.2 and `sharp` 0.35.5, matching what the `nodejs` package already ships. The stable `0.41.0` still uses transformers 3.0.2, so it doesn't fix this. ## Evidence `npm install --package-lock-only` reports `found 0 vulnerabilities`, and `npm test` passes 4/4 locally against `0.42.0-beta.20`. ## Merge Risk **Door:** two-way; only a docs test lockfile changes. **Blast Radius:** none (docs test only, not run in PR CI). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- docs/web-tests/blob-v2/ts/package-lock.json | 872 +++++++++++--------- docs/web-tests/blob-v2/ts/package.json | 2 +- 2 files changed, 468 insertions(+), 406 deletions(-) diff --git a/docs/web-tests/blob-v2/ts/package-lock.json b/docs/web-tests/blob-v2/ts/package-lock.json index 9426f2b18..914855656 100644 --- a/docs/web-tests/blob-v2/ts/package-lock.json +++ b/docs/web-tests/blob-v2/ts/package-lock.json @@ -8,95 +8,126 @@ "name": "lancedb-blob-v2-docs", "version": "0.0.0", "dependencies": { - "@lancedb/lancedb": "0.41.0-beta.8", + "@lancedb/lancedb": "0.42.0-beta.20", "apache-arrow": "21.2.0" + }, + "engines": { + "node": ">=22.6.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", + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.5.13.tgz", + "integrity": "sha512-jM17MqFily1iyT/1LD3r5w8/CZiyapVB0+7vOw48PfVtzyKsXStmHE4jVTyDAD05Tqv3un1xrS9ILUU1ugQAYQ==", "optional": true, "engines": { "node": ">=18" } }, + "node_modules/@huggingface/tokenizers": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz", + "integrity": "sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==", + "optional": true + }, "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", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-4.3.2.tgz", + "integrity": "sha512-V3+dqf3iWlRYJ9I9GreM3zGQd0lAXnnoPeddmkOQYWAEE4l/+Fi6p7tx/qVUJlKQgLXGim2W76rTOzz+eC0i7g==", "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" + "@huggingface/jinja": "^0.5.10", + "@huggingface/tokenizers": "^0.2.0", + "onnxruntime-node": "1.30.0", + "onnxruntime-web": "1.31.0-dev.20260914-8d85527a0", + "sharp": "^0.35.4" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "optional": true, + "engines": { + "node": ">=18" } }, "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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", "cpu": [ "arm64" ], - "license": "Apache-2.0", "optional": true, "os": [ "darwin" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.0.4" + "@img/sharp-libvips-darwin-arm64": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", "cpu": [ "x64" ], - "license": "Apache-2.0", "optional": true, "os": [ "darwin" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.0.4" + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", "cpu": [ "arm64" ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "darwin" @@ -106,13 +137,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", "cpu": [ "x64" ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "darwin" @@ -122,16 +152,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", "cpu": [ "arm" ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -141,16 +167,42 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", "cpu": [ "arm64" ], - "libc": [ - "glibc" + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -160,16 +212,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -179,16 +227,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", "cpu": [ "x64" ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -198,16 +242,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", "cpu": [ "arm64" ], - "libc": [ - "musl" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -217,16 +257,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", "cpu": [ "x64" ], - "libc": [ - "musl" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -236,234 +272,268 @@ } }, "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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", "cpu": [ "arm" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.0.5" + "@img/sharp-libvips-linux-arm": "1.3.4" } }, "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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.0.4" + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.0.4" + "@img/sharp-libvips-linux-s390x": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", "cpu": [ "x64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.0.4" + "@img/sharp-libvips-linux-x64": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", "cpu": [ "arm64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" + "@img/sharp-libvips-linuxmusl-arm64": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", "cpu": [ "x64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.0.4" + "@img/sharp-libvips-linuxmusl-x64": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", "cpu": [ "wasm32" ], - "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", "optional": true, "dependencies": { - "@emnapi/runtime": "^1.2.0" + "@img/sharp-wasm32": "0.35.5" }, "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", "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" + "node": "^20.9.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", "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" + "node": ">=20.9.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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb/-/lancedb-0.42.0-beta.20.tgz", + "integrity": "sha512-sPccnvQbxgybSu3nypRKXtbWE1pa90imQuOnxNQ1w68pz6KFISereKYp9o0HtukMqJWYfrezetYJPG+uC3KprA==", "cpu": [ "x64", "arm64" ], - "license": "Apache-2.0", "os": [ "darwin", "linux", @@ -477,14 +547,14 @@ "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", + "@huggingface/transformers": "4.3.2", + "@lancedb/lancedb-darwin-arm64": "0.42.0-beta.20", + "@lancedb/lancedb-linux-arm64-gnu": "0.42.0-beta.20", + "@lancedb/lancedb-linux-arm64-musl": "0.42.0-beta.20", + "@lancedb/lancedb-linux-x64-gnu": "0.42.0-beta.20", + "@lancedb/lancedb-linux-x64-musl": "0.42.0-beta.20", + "@lancedb/lancedb-win32-arm64-msvc": "0.42.0-beta.20", + "@lancedb/lancedb-win32-x64-msvc": "0.42.0-beta.20", "openai": "4.29.2" }, "peerDependencies": { @@ -498,13 +568,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-darwin-arm64/-/lancedb-darwin-arm64-0.42.0-beta.20.tgz", + "integrity": "sha512-UbIQknmvPdkHAn/2fXE41YDXXyZKoBjeW3TTpWMY9CdcBr6zOEvoL6hIcfIZ7ToN5B8kLePo6Vigc6SOY+Bt4w==", "cpu": [ "arm64" ], - "license": "Apache-2.0", "optional": true, "os": [ "darwin" @@ -514,16 +583,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-gnu/-/lancedb-linux-arm64-gnu-0.42.0-beta.20.tgz", + "integrity": "sha512-Pkn9fjIsYu5h4grzbCp+X7HT/byHd4N0/BFpvN4oRW703kjkwp9QzwSyRRvXEtgywv47diJu2W0cl8+8su5XtQ==", "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -533,16 +598,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-musl/-/lancedb-linux-arm64-musl-0.42.0-beta.20.tgz", + "integrity": "sha512-A2fKIET4p1r1geWFX5omLCtjg03c8V42QQJPtCUjuX9sG9EXcNM6tHQSSJj3En/7T4N5gSlSzS3dcy4ciYEVYQ==", "cpu": [ "arm64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -552,16 +613,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-gnu/-/lancedb-linux-x64-gnu-0.42.0-beta.20.tgz", + "integrity": "sha512-s7/l3mlktGM1tsfVT0Ioso+B+adG/Ke4sAOEPdbGtIoGRauswov6lzCBmgMnNhV13Q2lniMmnAJR6rGC4Vtg/A==", "cpu": [ "x64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -571,16 +628,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-musl/-/lancedb-linux-x64-musl-0.42.0-beta.20.tgz", + "integrity": "sha512-2YgGQjV5AqacKXC1IDJwR/WYOPJk34PuUvo1iy4d+hOdaIy+r7vQLYUy1nFx4uYx7kLCfV/cuuq6V7OkzGkx7Q==", "cpu": [ "x64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -590,13 +643,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-arm64-msvc/-/lancedb-win32-arm64-msvc-0.42.0-beta.20.tgz", + "integrity": "sha512-VGRLcDBGtYZEw/GJAOfDJX3ad36+sWP+lQrKmnNzzHAOs4MATLcbVk50zbqRbs6ukGBc784yM0ycnKy31TbN1w==", "cpu": [ "arm64" ], - "license": "Apache-2.0", "optional": true, "os": [ "win32" @@ -606,13 +658,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-x64-msvc/-/lancedb-win32-x64-msvc-0.42.0-beta.20.tgz", + "integrity": "sha512-eXoK1x9Ie2E2X/eYowGo2Daqve8zwLG8pvHexwCTzLLvVFM/o7iTK0WvSRXO9/9O4uhAsAGXBzH4I52ZY3kqqw==", "cpu": [ "x64" ], - "license": "Apache-2.0", "optional": true, "os": [ "win32" @@ -634,35 +685,30 @@ "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" @@ -672,28 +718,24 @@ "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": { @@ -729,6 +771,15 @@ "node": ">=6.5" } }, + "node_modules/adm-zip": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.1.tgz", + "integrity": "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==", + "optional": true, + "engines": { + "node": ">=14.0" + } + }, "node_modules/agentkeepalive": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", @@ -794,61 +845,6 @@ "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", @@ -872,6 +868,40 @@ "node": "*" } }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "optional": true, + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "optional": true, + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -886,7 +916,6 @@ "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" @@ -967,6 +996,18 @@ "node": ">= 0.4" } }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/event-target-shim": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", @@ -1080,6 +1121,37 @@ "node": ">= 0.4" } }, + "node_modules/global-agent": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-4.1.7.tgz", + "integrity": "sha512-pxaZqdsMwPA4i7TuRKpDUONm2xGRjvYdRoidCQz7VleUKVuUfh/4p5Q3QDTGrpAE5Kz5TxxcZ+uqEgTkoKRNtg==", + "optional": true, + "dependencies": { + "globalthis": "^1.0.2", + "matcher": "^4.0.0", + "semver": "^7.3.5", + "serialize-error": "^8.1.0" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "optional": true, + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -1097,9 +1169,20 @@ "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-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "optional": true, + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/has-symbols": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", @@ -1152,13 +1235,6 @@ "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", @@ -1176,9 +1252,23 @@ "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/matcher": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-4.0.0.tgz", + "integrity": "sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==", + "optional": true, + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -1224,29 +1314,6 @@ "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", @@ -1296,19 +1363,26 @@ } } }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, "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", + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.30.0.tgz", + "integrity": "sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==", "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==", + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.30.0.tgz", + "integrity": "sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==", "hasInstallScript": true, - "license": "MIT", "optional": true, "os": [ "win32", @@ -1316,37 +1390,29 @@ "linux" ], "dependencies": { - "onnxruntime-common": "1.19.2", - "tar": "^7.0.1" + "adm-zip": "^0.6.0", + "global-agent": "^4.1.3", + "onnxruntime-common": "1.30.0" } }, "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", + "version": "1.31.0-dev.20260914-8d85527a0", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.31.0-dev.20260914-8d85527a0.tgz", + "integrity": "sha512-Iy7rtadoBgxS/LLvDr3QW38DB1PNXRnr0GJMcL0TAt7c9qjgVQl83UlGCVyeAnK2InpmW8Uc3PL8XIuqtDeF6g==", "optional": true, "dependencies": { - "flatbuffers": "^1.12.0", + "flatbuffers": "^25.1.24", "guid-typescript": "^1.0.9", "long": "^5.2.3", - "onnxruntime-common": "1.20.0-dev.20241016-2b8fc5529b", + "onnxruntime-common": "1.31.0-dev.20260911-2a43ec07e", "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", + "version": "1.31.0-dev.20260911-2a43ec07e", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.0-dev.20260911-2a43ec07e.tgz", + "integrity": "sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==", "optional": true }, "node_modules/openai": { @@ -1391,7 +1457,6 @@ "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": { @@ -1399,7 +1464,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", @@ -1425,10 +1489,9 @@ "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", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "optional": true, "bin": { "semver": "bin/semver.js" @@ -1437,71 +1500,68 @@ "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", + "node_modules/serialize-error": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-8.1.0.tgz", + "integrity": "sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==", "optional": true, "dependencies": { - "color": "^4.2.3", - "detect-libc": "^2.0.3", - "semver": "^7.6.3" + "type-fest": "^0.20.2" }, "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "optional": true, + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.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" + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" }, - "engines": { - "node": ">=18" + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, "node_modules/tr46": { @@ -1517,6 +1577,18 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/undici-types": { "version": "7.24.6", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", @@ -1550,16 +1622,6 @@ "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 index f39495edd..17daaeab0 100644 --- a/docs/web-tests/blob-v2/ts/package.json +++ b/docs/web-tests/blob-v2/ts/package.json @@ -10,7 +10,7 @@ "node": ">=22.6.0" }, "dependencies": { - "@lancedb/lancedb": "0.41.0-beta.8", + "@lancedb/lancedb": "0.42.0-beta.20", "apache-arrow": "21.2.0" } } From 4ac2728e73d5b47b69d7052b3c0e023a5d58a7b1 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 19 Nov 2026 14:42:22 -0800 Subject: [PATCH 04/18] ci: scope workflow permissions and drop unverified downloads (#5103) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Fixes four high-severity Aikido findings in CI and the Dockerfile. - **Workflow permissions:** `npm-publish.yml` and `codex-update-lance-dependency.yml` now set `permissions: {}` at the workflow level and grant permissions per job. - `npm-publish`: only `publish` gets `id-token: write` (npm provenance). Nothing in the workflow needed `contents: write`, so every job is now read-only. - `codex-update-lance-dependency`: keeps `contents: write`, because the branch is pushed with the checkout token. It drops `pull-requests: write` and `actions: read`, because all `gh` calls use `ROBOT_TOKEN`. - **license-header-check:** replaces `curl .../master/install.sh | bash` with `go install …@v1.5.0`. Go verifies the module against sum.golang.org, so we don't maintain a hash ourselves. Go is preinstalled on `ubuntu-latest`. - **Dockerfile:** drops the rustup `curl | sh` along with `build-essential`, `protoc`, and `git`, and runs as a non-root `lancedb` user. `lancedb` installs from prebuilt `manylinux_2_28` wheels, and the toolchain was only needed for the tantivy FTS support removed in #3282. Alternatives considered for the Dockerfile, in case we want Rust in the image: - `COPY --from=rust:-slim-bookworm@sha256:…` to copy the toolchain from the official image, pinned by digest. - Download `rustup-init` from `static.rust-lang.org` and check it against the published `.sha256`. Neither seemed worth it for an image that only runs `pip install lancedb`. ## Evidence - In a clean Python 3.12 venv, `pip install --only-binary :all: lancedb` installed 0.41.0, and building an FTS index and querying it worked. Docker wasn't available, so the image itself wasn't built. - Running `license-header-checker` v1.5.0 installed via `go install` over `rust/` reports `license_ok: 258 files`. - This PR runs both the `npm-publish` dry run and `license-header-check`, because both workflows' path filters include their own files. ## Merge Risk **Door:** two-way; CI config and an example Dockerfile only. **Blast Radius:** release automation. If `npm publish` or the Codex bump job needs a permission I removed, it will fail on the next tag or dispatch, and restoring that one permission fixes it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../codex-update-lance-dependency.yml | 8 ++--- .github/workflows/license-header-check.yml | 5 ++-- .github/workflows/npm-publish.yml | 12 ++++++-- dockerfiles/Dockerfile | 29 ++++--------------- 4 files changed, 21 insertions(+), 33 deletions(-) diff --git a/.github/workflows/codex-update-lance-dependency.yml b/.github/workflows/codex-update-lance-dependency.yml index ef59213bd..1d1890efb 100644 --- a/.github/workflows/codex-update-lance-dependency.yml +++ b/.github/workflows/codex-update-lance-dependency.yml @@ -16,14 +16,14 @@ on: default: "" type: string -permissions: - contents: write - pull-requests: write - actions: read +permissions: {} jobs: update: runs-on: ubuntu-latest + permissions: + # Pushes the branch with the checkout token. PR creation uses ROBOT_TOKEN. + contents: write steps: - name: Show inputs run: | diff --git a/.github/workflows/license-header-check.yml b/.github/workflows/license-header-check.yml index 8b8510b58..904eea2c4 100644 --- a/.github/workflows/license-header-check.yml +++ b/.github/workflows/license-header-check.yml @@ -21,11 +21,10 @@ jobs: steps: - name: Check out code uses: actions/checkout@v6 + # `go install` at a fixed version is verified against the Go checksum database. - name: Install license-header-checker - working-directory: /tmp run: | - curl -s https://raw.githubusercontent.com/lluissm/license-header-checker/master/install.sh | bash - mv /tmp/bin/license-header-checker /usr/local/bin/ + GOBIN=/usr/local/bin go install github.com/lluissm/license-header-checker/cmd/license-header-checker@v1.5.0 - name: Check license headers (rust) run: license-header-checker -a -v ./rust/license_header.txt ./ rs && [[ -z `git status -s` ]] - name: Check license headers (python) diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 6de291c7d..fbaa43201 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -4,9 +4,7 @@ env: MACOSX_DEPLOYMENT_TARGET: '10.13' CARGO_INCREMENTAL: '0' -permissions: - contents: write - id-token: write +permissions: {} on: push: @@ -33,6 +31,8 @@ concurrency: jobs: build-lancedb: + permissions: + contents: read strategy: fail-fast: false matrix: @@ -326,6 +326,8 @@ jobs: nodejs/dist/* !nodejs/dist/*.node test-lancedb: + permissions: + contents: read name: "Test: ${{ matrix.settings.target }} - node@${{ matrix.node }}" needs: - build-lancedb @@ -394,6 +396,10 @@ jobs: run: node_modules/.bin/jest --verbose publish: name: Publish + permissions: + contents: read + # npm provenance + id-token: write runs-on: ubuntu-latest defaults: run: diff --git a/dockerfiles/Dockerfile b/dockerfiles/Dockerfile index 1c223b9b8..d8cafa690 100644 --- a/dockerfiles/Dockerfile +++ b/dockerfiles/Dockerfile @@ -1,27 +1,10 @@ -# Simple base dockerfile that supports basic dependencies required to run lance with FTS and Hybrid Search +# Simple base dockerfile for running LanceDB, including FTS and Hybrid Search # Usage: docker build -t lancedb:latest -f Dockerfile . FROM python:3.12-slim-bookworm -# Install build dependencies in a single layer -RUN apt-get update && \ - apt-get install -y --no-install-recommends \ - curl \ - build-essential \ - protobuf-compiler \ - git \ - ca-certificates && \ - apt-get clean && \ - rm -rf /var/lib/apt/lists/* - -# Install Rust (pinned installer, non-interactive) -RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal - -# Set the environment variable for Rust -ENV PATH="/root/.cargo/bin:${PATH}" - -# Verify installations -RUN python --version && \ - rustc --version && \ - protoc --version - +# lancedb ships prebuilt manylinux wheels, so no Rust or C toolchain is needed. RUN pip install --no-cache-dir lancedb + +RUN useradd --create-home --uid 1000 lancedb +USER lancedb +WORKDIR /home/lancedb From a9be4525a046c7b6356087adaf8fbe658995ddba Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:20:34 +0800 Subject: [PATCH 05/18] fix(python): accept optional discard_weight in split_hash (#5116) ### Problem `PermutationBuilder.split_hash()` raises `TypeError` when `discard_weight` is omitted because the Python wrapper forwards `None` while the PyO3 binding requires `u64`. The `_lancedb.pyi` stub also disagrees with the native signature: it omits `split_names` and types `discard_weight` as non-optional. ### Behavior The native binding accepts an optional `discard_weight` and treats omitted/`None` as `0`, so `split_hash(..., split_names=[...])` works without passing a discard weight. The stub now matches the binding. A regression test verifies that omitting `discard_weight` assigns every row exactly like explicit `0`. Fixes OSS-2856. --- python/python/lancedb/_lancedb.pyi | 7 ++++- python/python/tests/test_permutation.py | 35 +++++++++++++++++++++++++ python/src/permutation.rs | 5 ++-- 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 54b9f8083..5a89f100b 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1280,7 +1280,12 @@ class AsyncPermutationBuilder: seed: Optional[int] = None, ) -> "AsyncPermutationBuilder": ... def split_hash( - self, columns: List[str], split_weights: List[int], *, discard_weight: int = 0 + self, + columns: List[str], + split_weights: List[int], + *, + discard_weight: Optional[int] = None, + split_names: Optional[List[str]] = None, ) -> "AsyncPermutationBuilder": ... def split_sequential( self, diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 46d6493ed..165172622 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -275,6 +275,41 @@ def test_split_hash(mem_db): assert data["split_id"] == data2["split_id"] # Should be identical +def test_split_hash_default_discard_weight_matches_zero(mem_db): + """Omitting discard_weight must assign every row like discard_weight=0.""" + tbl = mem_db.create_table( + "test_table", + pa.table( + { + "id": range(100), + "category": (["A", "B", "C"] * 34)[:100], + "value": range(100), + } + ), + ) + + default = ( + permutation_builder(tbl) + .split_hash(["category"], [1, 1], split_names=["train", "test"]) + .execute() + ) + explicit_zero = ( + permutation_builder(tbl) + .split_hash( + ["category"], [1, 1], discard_weight=0, split_names=["train", "test"] + ) + .execute() + ) + + default_data = default.search(None).to_arrow().to_pydict() + explicit_data = explicit_zero.search(None).to_arrow().to_pydict() + assert default.count_rows() == 100 + assert default.count_rows() == explicit_zero.count_rows() + assert dict(zip(default_data["row_id"], default_data["split_id"])) == dict( + zip(explicit_data["row_id"], explicit_data["split_id"]) + ) + + def test_split_hash_with_discard(mem_db): """Test hash-based splitting with discard weight.""" tbl = mem_db.create_table( diff --git a/python/src/permutation.rs b/python/src/permutation.rs index 4e07d439e..9cb4da247 100644 --- a/python/src/permutation.rs +++ b/python/src/permutation.rs @@ -123,14 +123,15 @@ impl PyAsyncPermutationBuilder { }) } - #[pyo3(signature = (columns, split_weights, *, discard_weight=0, split_names=None))] + #[pyo3(signature = (columns, split_weights, *, discard_weight=None, split_names=None))] pub fn split_hash( slf: PyRefMut<'_, Self>, columns: Vec, split_weights: Vec, - discard_weight: u64, + discard_weight: Option, split_names: Option>, ) -> PyResult { + let discard_weight = discard_weight.unwrap_or(0); slf.modify(|builder| { builder.with_split_strategy( SplitStrategy::Hash { From 5e9b17b639dd4d1e10e4206f5354a9d8de0b0a0e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:21:27 +0800 Subject: [PATCH 06/18] feat(python): make native tables and connections picklable (#5114) ## Summary Adds `__getstate__`/`__setstate__` to native `LanceTable` and `LanceDBConnection` so a PyTorch `Dataset` that keeps both can cross `spawn` and `forkserver` worker boundaries. `Permutation` and `StreamingDataset` now delegate to the same table state representation while retaining compatibility with older pickle payloads. ## Pickle contract - Reconnects from the serialized connection and preserves the table name, namespace path, explicit storage overrides, location, index-cache setting, managed versioning and pushdown routing. - Standard mode reopens at latest; `checkout(version)` remains pinned to the resolved branch/version; branch handles preserve their branch. Cross-branch tag checkout records the actual live branch. - `read_consistency_interval=timedelta(0)` remains distinct from `None`. - `memory://` tables keep the existing Arrow snapshot export/rebuild behavior. - `Session` and unreconstructable custom namespace clients fail at `pickle.dumps` with an explicit `TypeError`; declared namespace configurations reconstruct, including an omitted properties map. - Namespace storage options keep caller-only overrides layered over the live provider, with vended values winning conflicts. Caller options survive refresh, refreshed credentials replace old vended values, an explicit provider remains selected on open, and an empty provider response stays empty rather than restoring an expired seed. - Declared Python namespace connections reopen through their connection provider instead of turning the reconstructed client into an explicit table provider. ## Verification - Fresh binding build with `uv run --extra tests --extra dev maturin develop --extras tests,dev`. - End-to-end `DataLoader` holding `self._db` and `self._table`: spawn and forkserver passed. - `test_namespace.py`: 90 passed; `test_table.py` + `test_db.py` + `test_permutation.py`: 700 passed, 17 skipped. - Focused namespace provider/pickle regressions: passed, including caller-only and vended keys after a declared-namespace refresh. - Rust `test_namespace_connection_with_storage_options` and `test_manifest_enabled_vend_input_storage_options`: passed. - `cargo clippy -p lancedb --features remote --tests --examples`, `cargo fmt --check`, exact CI Pyright (0 errors/0 warnings), and Ruff passed. - DataLoader Workers documentation updated; Vale reports 0 findings. ## Scope Does not change the fork hard-error policy, #3851, or direct `LanceNamespaceDBConnection` pickling. It does not claim changes to the existing namespace dir `index_cache_size` behavior. This supersedes the earlier draft #3486, which only moved the table-state portion. --- docs/web/training/data-loading.mdx | 23 +- python/python/lancedb/db.py | 31 +- python/python/lancedb/namespace.py | 5 +- python/python/lancedb/permutation.py | 29 +- python/python/lancedb/table.py | 175 ++++++++++- python/python/tests/test_db.py | 24 ++ python/python/tests/test_namespace.py | 420 +++++++++++++++++++++++++ python/python/tests/test_table.py | 123 ++++++++ python/python/tests/test_torch.py | 41 +++ rust/lancedb/src/connection.rs | 69 ++++ rust/lancedb/src/database/namespace.rs | 36 ++- rust/lancedb/src/table.rs | 96 +++++- 12 files changed, 1027 insertions(+), 45 deletions(-) diff --git a/docs/web/training/data-loading.mdx b/docs/web/training/data-loading.mdx index 1e4989cf9..2a3250105 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -217,12 +217,23 @@ dataloader = torch.utils.data.DataLoader( ``` -By default, `StreamingDataset` serializes enough table state to reopen the -table in each worker. Remote LanceDB Enterprise tables (`db://...`) work the -same way: workers reopen the table from the pickled connection state. -Replace the URI, API key, region and endpoint below with your deployment -details. In application code, load credentials from environment variables -or a secrets manager: +By default, `StreamingDataset` and `Permutation` pickle the native table's +reopen state, including its connection, table identity, open options and +explicit storage overrides. A standard-mode handle reopens at the latest +version; `checkout(version)` and branch-scoped handles keep their pinned +version and branch. `memory://` tables are exported as an Arrow snapshot, so +workers see the data as of pickling; an in-memory connection by itself is not +picklable. + +Connections opened with a `Session` cannot be pickled. For a Session-backed +table, pass a picklable `connection_factory` to +`Permutation.with_connection_factory` or `StreamingDataset(connection_factory=...)` +so each worker creates its own connection and Session. + +Remote LanceDB Enterprise tables (`db://...`) work the same way: workers +reopen the table from the pickled connection state. Replace the URI, API key, +region and endpoint below with your deployment details. In application code, +load credentials from environment variables or a secrets manager: ```py Python icon=Python diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 86001ef10..aa1d73b29 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1936,11 +1936,40 @@ class LanceDBConnection(DBConnection): "manifest_enabled": self._manifest_enabled, "namespace_client_properties": self._namespace_client_properties, "read_consistency_interval_seconds": ( - rci.total_seconds() if rci else None + rci.total_seconds() if rci is not None else None ), } ) + def _pickle_state(self) -> str: + """Serialize this connection for pickle-based workers.""" + if self._session is not None: + raise TypeError( + "Cannot pickle a LanceDBConnection created with a Session; " + "Session objects are not serializable. Create the Session in " + "each worker process instead." + ) + if self.uri.startswith("memory://"): + raise TypeError( + "Cannot pickle an in-memory LanceDBConnection because its tables " + "exist only in this process. Pickle a LanceTable instead to " + "export its data, or connect to a persistent URI." + ) + return self.serialize() + + def __getstate__(self) -> dict[str, str]: + return {"serialized": self._pickle_state()} + + def __setstate__(self, state: dict[str, str]) -> None: + from . import deserialize_conn + + connection = deserialize_conn(state["serialized"], for_worker=True) + if not isinstance(connection, LanceDBConnection): + raise TypeError( + "Serialized connection did not reconstruct a LanceDBConnection" + ) + self.__dict__.update(connection.__dict__) + async def _async_get_table_names(self, start_after: Optional[str], limit: int): conn = AsyncConnection(await lancedb_connect(self.uri)) return await conn.table_names(start_after=start_after, limit=limit) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 463536619..1de49d935 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -584,7 +584,7 @@ class LanceNamespaceDBConnection(DBConnection): "storage_options": self.storage_options or None, "read_consistency_interval_seconds": ( self.read_consistency_interval.total_seconds() - if self.read_consistency_interval + if self.read_consistency_interval is not None else None ), } @@ -668,6 +668,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, namespace_client=self._namespace_client, pushdown_operations=self._namespace_client_pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, @@ -706,6 +707,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, namespace_client=self._namespace_client, pushdown_operations=self._namespace_client_pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, @@ -1132,6 +1134,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, location=table_uri, namespace_client=namespace_client, managed_versioning=managed_versioning, diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index a6f584f8a..c8e6f84e0 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -410,6 +410,8 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]: from .remote.table import RemoteTable if isinstance(table, RemoteTable): + # RemoteTable already owns its reopen state; keep the table object so + # pickle delegates to its __getstate__ without duplicating the fields. return { "kind": "remote", "table": table, @@ -418,20 +420,15 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]: if not isinstance(table, LanceTable): raise ValueError(f"Cannot pickle table of type {type(table)!r}") - base_uri = table._conn.uri - if base_uri.startswith("memory://"): + state = table.__getstate__() + if state.get("kind") == "memory": return { "kind": "memory", - "name": table.name, - "data": table.to_arrow(), + "state": state, } - return { - "kind": "local", - "name": table.name, - "uri": base_uri, - "namespace": table._namespace_path, - "storage_options": table._conn.storage_options, + "kind": "lance", + "state": state, } @@ -444,13 +441,25 @@ def _drop_base_version(permutation_data: pa.Table) -> pa.Table: return permutation_data.replace_schema_metadata(metadata) +def _lance_table_from_pickle_state(state: dict[str, Any]) -> LanceTable: + table = LanceTable.__new__(LanceTable) + table.__setstate__(state) + return table + + def _table_from_pickle_state(state: dict[str, Any]) -> Table: from . import connect kind = state["kind"] if kind == "remote": return state["table"] + if kind == "lance": + return _lance_table_from_pickle_state(state["state"]) if kind == "memory": + if "state" in state: + return _lance_table_from_pickle_state(state["state"]) + # Backward compatibility for pickles written before tables carried + # their own state. return connect("memory://").create_table(state["name"], state["data"]) if kind == "local": db = connect(state["uri"], storage_options=state["storage_options"]) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ff014396c..ea9dee024 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -299,7 +299,7 @@ def _maybe_add_fts_error_note( if TYPE_CHECKING: - from .db import LanceDBConnection + from .db import DBConnection, LanceDBConnection from ._lancedb import ( Table as LanceDBTable, OptimizeStats, @@ -4191,7 +4191,10 @@ class LanceTable(Table): namespace_path = [] self._conn = connection self._namespace_path = namespace_path + self._storage_options = storage_options + self._index_cache_size = index_cache_size self._location = location # Store location for use in _dataset_path + self._managed_versioning = managed_versioning self._namespace_client = namespace_client self._pushdown_operations = pushdown_operations or set() # When the connection built the namespace client natively (e.g. an @@ -4218,6 +4221,154 @@ class LanceTable(Table): ) # Take queries read the pushdown set from the inner table. self._table._pushdown_operations = self._pushdown_operations + # These coordinates live on the Python wrapper: the native table only + # reports its current branch and version, not whether it is pinned. + self._branch = self._table.current_branch() + self._checkout_version: Optional[int] = None + + def _pickle_connection_state(self) -> str: + """Serialize the connection, rejecting state a worker cannot recreate.""" + connection = self._conn + namespace_client = getattr(connection, "_namespace_client", None) + namespace_impl = getattr(connection, "_namespace_client_impl", None) + if namespace_client is not None and namespace_impl is None: + raise TypeError( + f"Cannot pickle LanceTable {self.name!r} backed by a namespace " + "connection whose custom namespace_client cannot be " + "reconstructed. Connect through connect_namespace(impl, " + "properties) or provide a picklable worker-side namespace " + "connection instead." + ) + + pickle_state = getattr(connection, "_pickle_state", None) + if pickle_state is not None: + return pickle_state() + + session = getattr(connection, "session", None) + if session is not None: + raise TypeError( + "Cannot pickle a LanceTable whose connection was created with a " + "Session; Session objects are not serializable. Create the " + "Session in each worker process instead." + ) + return connection.serialize() + + def _namespace_client_for_pickle(self) -> Optional[Any]: + """Keep a table-level namespace client only when pickle can carry it.""" + namespace_client = self._namespace_client + if namespace_client is None: + return None + if namespace_client is getattr(self._conn, "_namespace_client", None): + # The serialized connection rebuilds its own namespace client. + return None + if namespace_client is getattr(self._conn, "_cached_namespace_client", None): + # Local manifest-mode connections cache their namespace client here. + return None + + import pickle + + try: + pickle.dumps(namespace_client) + except Exception as error: + raise TypeError( + f"Cannot pickle LanceTable {self.name!r}: its custom " + f"namespace_client ({type(namespace_client).__name__}) is not " + "serializable. Reopen the table in the worker through a " + "picklable namespace connection instead." + ) from error + return namespace_client + + @classmethod + def _open_from_pickle_state( + cls, connection: "DBConnection", state: dict[str, Any] + ) -> "LanceTable": + """Reopen a table from the state returned by ``__getstate__``.""" + async_connection = getattr(connection, "_conn", None) + if async_connection is None: + async_connection = connection._inner + + # Only a table-level explicit client travels in the state. A connection + # namespace client must reopen through its own provider path so caller + # storage options keep their layering; passing the reconstructed client + # here would turn it into an explicit table provider. + namespace_client = state.get("namespace_client") + + async_table = LOOP.run( + async_connection.open_table( + state["name"], + namespace_path=state["namespace_path"], + storage_options=state["storage_options"], + index_cache_size=state["index_cache_size"], + location=state["location"], + namespace_client=namespace_client, + managed_versioning=state["managed_versioning"], + ) + ) + table = cls( + connection, + state["name"], + namespace_path=state["namespace_path"], + storage_options=state["storage_options"], + index_cache_size=state["index_cache_size"], + location=state["location"], + namespace_client=namespace_client, + managed_versioning=state["managed_versioning"], + pushdown_operations=state["pushdown_operations"], + route_pushdown_to_rust=state["route_pushdown_to_rust"], + _async=async_table, + ) + + version = state["checkout_version"] + if state["branch"] is not None: + table = table.branches.checkout(state["branch"], version) + elif version is not None: + table.checkout(version) + return table + + def __getstate__(self) -> dict[str, Any]: + """Return a process-independent state for pickle-based workers.""" + if self._conn.uri.startswith("memory://"): + # In-memory databases cannot be reopened by name in another process. + # Keep the established behavior of exporting the visible table. + return {"kind": "memory", "name": self.name, "data": self.to_arrow()} + + # The native handle is authoritative: a tag checkout can move this + # wrapper onto another branch, so never trust the branch captured at + # construction time. + self._branch = self.current_branch() + return { + "kind": "lance", + "connection_state": self._pickle_connection_state(), + "name": self.name, + "namespace_path": list(self._namespace_path), + # Only caller-supplied overrides are safe to replay. Namespace-provided + # initial options may contain rotating credentials and must be fetched + # again by the reopened connection's storage-options provider. + "storage_options": self._storage_options, + "index_cache_size": self._index_cache_size, + "location": self._location, + "namespace_client": self._namespace_client_for_pickle(), + "managed_versioning": self._managed_versioning, + "pushdown_operations": set(self._pushdown_operations), + "route_pushdown_to_rust": self._route_pushdown_to_rust, + "branch": self._branch, + "checkout_version": self._checkout_version, + } + + def __setstate__(self, state: dict[str, Any]) -> None: + """Rebuild a table from ``__getstate__`` in the current process.""" + if state.get("kind") == "memory": + from . import connect + + rebuilt = connect("memory://").create_table(state["name"], state["data"]) + self.__dict__.update(rebuilt.__dict__) + return + + from . import deserialize_conn + + connection = deserialize_conn(state["connection_state"], for_worker=True) + reopened = type(self)._open_from_pickle_state(connection, state) + self.__dict__.update(reopened.__dict__) @property def name(self) -> str: @@ -4456,18 +4607,23 @@ class LanceTable(Table): def _wrap_branch_handle( self, async_table: "AsyncTable", version: Optional[int] = None ) -> "LanceTable": - # version is unused locally: the pin already lives on async_table and a - # local handle is not reopened via a serialized connection. - return LanceTable( + table = LanceTable( self._conn, async_table.name, namespace_path=self._namespace_path, + storage_options=self._storage_options, + index_cache_size=self._index_cache_size, namespace_client=self._namespace_client, + managed_versioning=self._managed_versioning, pushdown_operations=self._pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, location=self._location, _async=async_table, ) + # The native handle knows its branch but not whether this wrapper is a + # pinned branch version, so carry that coordinate explicitly. + table._checkout_version = version + return table def checkout(self, version: Union[int, str]): """Checkout a version of the table. This is an in-place operation. @@ -4506,6 +4662,8 @@ class LanceTable(Table): 0 [1.1, 0.9] vector """ LOOP.run(self._table.checkout(version)) + self._checkout_version = self.version + self._branch = self.current_branch() def checkout_latest(self): """Checkout the latest version of the table. This is an in-place operation. @@ -4514,6 +4672,8 @@ class LanceTable(Table): version of the table. """ LOOP.run(self._table.checkout_latest()) + self._checkout_version = None + self._branch = self.current_branch() def restore(self, version: Optional[Union[int, str]] = None): """Restore a version of the table. This is an in-place operation. @@ -4562,6 +4722,8 @@ class LanceTable(Table): if version is not None: LOOP.run(self._table.checkout(version)) LOOP.run(self._table.restore()) + self._checkout_version = None + self._branch = self.current_branch() def count_rows(self, filter: Optional[str] = None) -> int: return LOOP.run(self._table.count_rows(filter)) @@ -5651,7 +5813,9 @@ class LanceTable(Table): self = cls.__new__(cls) self._conn = db self._namespace_path = namespace_path + self._index_cache_size = None self._location = location + self._managed_versioning = None self._namespace_client = namespace_client self._pushdown_operations = pushdown_operations or set() self._route_pushdown_to_rust = route_pushdown_to_rust @@ -5679,6 +5843,7 @@ class LanceTable(Table): enable_v2_manifest_paths ).lower() + self._storage_options = storage_options self._table = LOOP.run( self._conn._conn.create_table( name, @@ -5695,6 +5860,8 @@ class LanceTable(Table): namespace_client=namespace_client, ) ) + self._branch = self._table.current_branch() + self._checkout_version = None return self def delete(self, where: Union[str, Expr]) -> DeleteResult: diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 80a98bc18..fa09a9e19 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -4,6 +4,7 @@ import contextlib import inspect +import pickle import re import sys from datetime import timedelta @@ -69,6 +70,29 @@ def test_basic(tmp_path): assert db.open_table("test").name == db["test"].name +def test_lance_db_connection_pickle_roundtrip(tmp_path): + interval = timedelta(seconds=2) + db = lancedb.connect(tmp_path, read_consistency_interval=interval) + db.create_table("pickle_conn", pa.table({"id": [1, 2]})) + + restored = pickle.loads(pickle.dumps(db)) + + assert restored.uri == str(tmp_path) + assert restored.read_consistency_interval == interval + assert restored.open_table("pickle_conn").to_arrow()["id"].to_pylist() == [1, 2] + + +def test_lance_db_connection_pickle_preserves_zero_read_consistency(tmp_path): + db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) + table = db.create_table("pickle_zero", pa.table({"id": [1]})) + + restored_db, restored_table = pickle.loads(pickle.dumps((db, table))) + lancedb.connect(tmp_path).open_table("pickle_zero").add(pa.table({"id": [2]})) + + assert restored_db.read_consistency_interval == timedelta(0) + assert restored_table.to_arrow()["id"].to_pylist() == [1, 2] + + def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeypatch): from lancedb.background_loop import LOOP diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index b4ca746b0..c965618cd 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -6,6 +6,8 @@ import tempfile import shutil import importlib +import asyncio +import pickle import warnings import http.server import json @@ -16,6 +18,7 @@ import copy import pyarrow as pa import lancedb from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError +from lance_namespace import DescribeTableResponse from utils import start_server_thread from lancedb.listing import AsyncListing, Listing from lancedb.index import FTS @@ -35,6 +38,37 @@ PUSHDOWN_DATA = pa.table( ) +class _RefreshNamespaceWithExpiringOptions(LanceNamespace): + def __init__(self, root): + self.root = root + + def namespace_id(self): + return f"refresh-test:{self.root}" + + def describe_table(self, request): + from pathlib import Path + + return DescribeTableResponse( + location=str(Path(self.root) / "t.lance"), + storage_options={"vended": "fresh", "expires_at_millis": "1"}, + ) + + +class _DeclaredNamespaceWithoutProperties(LanceNamespace): + root = None + + def __init__(self): + from lance.namespace import DirectoryNamespace + + self.client = DirectoryNamespace(root=self.root) + + def namespace_id(self): + return self.client.namespace_id() + + def describe_table(self, request): + return self.client.describe_table(request) + + @pytest.mark.asyncio @pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]]) async def test_custom_namespace_table_exists_uses_namespace_api(table_id): @@ -56,6 +90,70 @@ async def test_custom_namespace_table_exists_uses_namespace_api(table_id): assert await adb.table_exists(table_id) is (table_id != ["missing"]) +def test_table_pickle_rejects_custom_namespace_connection(tmp_path): + pytest.importorskip("lance") + from lance.namespace import DirectoryNamespace + + lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table( + "t", [{"id": 1}] + ) + + class UnserializableNamespace(LanceNamespace): + def __init__(self, root): + from threading import Lock + + self.client = DirectoryNamespace(root=str(root)) + self.lock = Lock() + + def namespace_id(self): + return self.client.namespace_id() + + def describe_table(self, request): + return self.client.describe_table(request) + + db = LanceNamespaceDBConnection(UnserializableNamespace(tmp_path)) + table = db.open_table("t") + + with pytest.raises(TypeError, match="namespace"): + pickle.dumps(table) + + +def test_declared_namespace_pickle_keeps_caller_options_after_refresh(tmp_path): + lancedb.connect(tmp_path).create_table("t", [{"id": 1}]) + db = lancedb.connect_namespace( + f"{__name__}._RefreshNamespaceWithExpiringOptions", {"root": str(tmp_path)} + ) + table = db.open_table("t", storage_options={"caller_only": "keep"}) + + restored = pickle.loads(pickle.dumps(table)) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_only"] == "keep" + assert options["vended"] == "fresh" + + +def test_table_pickle_allows_declared_namespace_without_properties(tmp_path): + pytest.importorskip("lance") + + lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table( + "t", [{"id": 1}] + ) + _DeclaredNamespaceWithoutProperties.root = str(tmp_path) + try: + impl = f"{__name__}._DeclaredNamespaceWithoutProperties" + db = LanceNamespaceDBConnection( + _DeclaredNamespaceWithoutProperties(), namespace_client_impl=impl + ) + table = db.open_table("t") + + restored = pickle.loads(pickle.dumps(table)) + + assert restored.to_arrow()["id"].to_pylist() == [1] + finally: + _DeclaredNamespaceWithoutProperties.root = None + + class TestNamespaceCreateTableOptions: @pytest.mark.parametrize("version", ["legacy", "stable"]) @pytest.mark.parametrize("empty", [False, True]) @@ -309,6 +407,328 @@ def paginated_rest_namespace(): thread.join() +def test_rest_namespace_table_pickle_keeps_live_storage_options(tmp_path): + from time import time + + local = lancedb.connect(tmp_path) + local.create_table("t", [{"id": 1}]) + location = str(tmp_path / "t.lance") + ipc = _ipc_file(pa.table({"id": [42]})) + seen = [] + current_options = { + "block_size": "4096", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + seen.append(path) + if path.endswith("/describe"): + body = json.dumps( + {"location": location, "storage_options": current_options} + ).encode() + content_type = "application/json" + elif path.endswith("/query"): + body = ipc + content_type = "application/vnd.apache.arrow.file" + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", + {"uri": f"http://127.0.0.1:{server.server_port}"}, + namespace_client_pushdown_operations=["QueryTable"], + ) + table = db.open_table("t") + restored = pickle.loads(pickle.dumps(table)) + + seen.clear() + assert restored.search().limit(1).to_list() == [{"id": 42}] + assert seen == ["/v1/table/t/query"] + + current_options = { + "block_size": "8192", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + } + assert table.latest_storage_options()["block_size"] == "8192" + assert restored.latest_storage_options()["block_size"] == "8192" + finally: + server.shutdown() + thread.join() + + +def test_rest_namespace_create_empty_refresh_does_not_restore_expired_seed(tmp_path): + from time import time + + location = str(tmp_path / "t.lance") + current_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if not (path.endswith("/declare") or path.endswith("/describe")): + self.send_error(404) + return + body = json.dumps( + {"location": location, "storage_options": current_options} + ).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", {"uri": f"http://127.0.0.1:{server.server_port}"} + ) + table = db.create_table("t", [{"id": 1}]) + payload = pickle.dumps(table) + assert b"short-lived" not in payload + restored = pickle.loads(payload) + + current_options = {} + assert table.latest_storage_options() == {} + assert restored.latest_storage_options() == {} + finally: + server.shutdown() + thread.join() + + +@pytest.mark.parametrize("entrypoint", ["create", "open"]) +def test_rest_namespace_pickle_layers_caller_storage_options(tmp_path, entrypoint): + from time import time + + location = str(tmp_path / "t.lance") + caller_options = {"caller_option": "kept", "conflict": "caller"} + vended_options = { + "vended_1": "old", + "conflict": "vended", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if path.endswith("/declare") or path.endswith("/describe"): + body = json.dumps( + {"location": location, "storage_options": vended_options} + ).encode() + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", + {"uri": f"http://127.0.0.1:{server.server_port}"}, + ) + if entrypoint == "create": + table = db.create_table( + "t", [{"id": 1}], storage_options=caller_options + ) + else: + db.create_table("t", [{"id": 1}]) + table = db.open_table("t", storage_options=caller_options) + restored = pickle.loads(pickle.dumps(table)) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_option"] == "kept" + assert options["conflict"] == "vended" + + vended_options.update( + { + "vended_2": "new", + "conflict": "vended-new", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + } + ) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_option"] == "kept" + assert options["vended_2"] == "new" + assert options["conflict"] == "vended-new" + finally: + server.shutdown() + thread.join() + + +def test_namespace_open_uses_explicit_storage_options_provider(tmp_path): + from time import time + + from lancedb._lancedb import connect_namespace as connect_namespace_inner + from lancedb.db import AsyncConnection + + location = str(tmp_path / "t.lance") + seed_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if not (path.endswith("/declare") or path.endswith("/describe")): + self.send_error(404) + return + result = {"location": location, "storage_options": seed_options} + body = json.dumps(result).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + class ExplicitClient(LanceNamespace): + calls = 0 + + def namespace_id(self): + return "explicit-storage-options-provider" + + def describe_table(self, request): + self.calls += 1 + return DescribeTableResponse( + location=location, + storage_options={ + "explicit_provider": "fresh", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + }, + ) + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + properties = {"uri": f"http://127.0.0.1:{server.server_port}"} + db = lancedb.connect_namespace("rest", properties) + db.create_table("t", [{"id": 1}]) + + async def check(): + connection = AsyncConnection( + connect_namespace_inner("rest", properties) + ) + client = ExplicitClient() + table = await connection.open_table("t", namespace_client=client) + options = await table.latest_storage_options() + assert client.calls > 0 + assert options["explicit_provider"] == "fresh" + + asyncio.run(check()) + finally: + server.shutdown() + thread.join() + + +def test_namespace_create_without_seed_uses_connection_provider(tmp_path): + from time import time + + from lancedb._lancedb import connect_namespace as connect_namespace_inner + from lancedb.db import AsyncConnection + + location = str(tmp_path / "t.lance") + seed_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + result = {"location": location} + if path.endswith("/describe"): + result["storage_options"] = seed_options + elif not path.endswith("/declare"): + self.send_error(404) + return + body = json.dumps(result).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + class ExplicitClient(LanceNamespace): + calls = 0 + + def namespace_id(self): + return "explicit-storage-options-provider" + + def describe_table(self, request): + self.calls += 1 + return DescribeTableResponse( + location=location, + storage_options={ + "explicit_provider": "fresh", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + }, + ) + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + properties = {"uri": f"http://127.0.0.1:{server.server_port}"} + + async def check(): + connection = AsyncConnection( + connect_namespace_inner("rest", properties) + ) + client = ExplicitClient() + table = await connection.create_table( + "t", [{"id": 1}], namespace_client=client + ) + options = await table.latest_storage_options() + assert client.calls == 0 + assert options["vended_seed"] == "short-lived" + + asyncio.run(check()) + finally: + server.shutdown() + thread.join() + + @pytest.mark.asyncio @pytest.mark.parametrize("namespace_path", [[], ["n"]]) async def test_rest_namespace_table_names_collects_pages( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 90ae62d1b..e999390a1 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6,6 +6,7 @@ import ctypes import gc import json import os +import pickle import sys import threading import warnings @@ -1228,6 +1229,128 @@ def test_list_versions_timestamp_precision_remote(): assert versions[0]["timestamp"].microsecond == 274000 +def test_lance_table_is_picklable(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_table", pa.table({"id": [1, 2, 3]})) + payload = pickle.dumps(table) + + # A standard-mode handle must reopen at latest, not freeze the version that + # happened to be current when pickle.dumps ran. + tmp_db.open_table("pickle_table").add(pa.table({"id": [4]})) + + restored = pickle.loads(payload) + assert restored.name == "pickle_table" + assert restored.count_rows() == 4 + assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3, 4] + + +def test_lance_table_pickle_preserves_checkout(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_checkout", pa.table({"id": [1]})) + table.add(pa.table({"id": [2]})) + table.checkout(1) + payload = pickle.dumps(table) + + tmp_db.open_table("pickle_checkout").add(pa.table({"id": [3]})) + + restored = pickle.loads(payload) + assert restored.version == 1 + assert restored.to_arrow()["id"].to_pylist() == [1] + + restored.checkout_latest() + assert restored.version == 3 + assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3] + + +def test_lance_table_pickle_preserves_cross_branch_tag_checkout(tmp_path): + db = lancedb.connect(tmp_path) + main = db.create_table("pickle_tag_branch", pa.table({"id": [0]})) + branch = main.branches.create("exp") + branch.add(pa.table({"id": [1]})) + branch.tags.create("exp_tag", branch.version) + + # Advance main independently, then resolve a tag that points into exp. + main.add(pa.table({"id": [9]})) + main.checkout("exp_tag") + assert main.current_branch() == "exp" + assert main.version == 2 + assert main.to_arrow()["id"].to_pylist() == [0, 1] + + restored = pickle.loads(pickle.dumps(main)) + assert restored.current_branch() == "exp" + assert restored.version == 2 + assert restored.to_arrow()["id"].to_pylist() == [0, 1] + + +def test_lance_table_pickle_preserves_branch_and_version(tmp_path): + db = lancedb.connect(tmp_path) + main = db.create_table("pickle_branch", pa.table({"id": [0]})) + branch = main.branches.create("exp") + branch.add(pa.table({"id": [1]})) + branch_version = branch.version + + branch_payload = pickle.dumps(branch) + pinned = db.open_table("pickle_branch", branch="exp", version=branch_version) + pinned_payload = pickle.dumps(pinned) + + db.open_table("pickle_branch", branch="exp").add(pa.table({"id": [2]})) + + restored_branch = pickle.loads(branch_payload) + assert restored_branch.current_branch() == "exp" + assert restored_branch.to_arrow()["id"].to_pylist() == [0, 1, 2] + + restored_pinned = pickle.loads(pinned_payload) + assert restored_pinned.current_branch() == "exp" + assert restored_pinned.version == branch_version + assert restored_pinned.to_arrow()["id"].to_pylist() == [0, 1] + assert main.count_rows() == 1 + + +def test_lance_table_pickle_memory_uses_arrow_snapshot(mem_db: DBConnection): + table = mem_db.create_table("pickle_memory", pa.table({"id": [1, 2]})) + payload = pickle.dumps(table) + + table.add(pa.table({"id": [3]})) + + restored = pickle.loads(payload) + assert restored.name == "pickle_memory" + assert restored.to_arrow()["id"].to_pylist() == [1, 2] + + +def test_memory_connection_pickle_requires_a_table_snapshot(mem_db: DBConnection): + with pytest.raises(TypeError, match="in-memory LanceDBConnection"): + pickle.dumps(mem_db) + + +def test_pickle_rejects_session_backed_connection(tmp_path): + db = lancedb.connect(tmp_path, session=lancedb.Session()) + table = db.create_table("pickle_session", pa.table({"id": [1]})) + + with pytest.raises(TypeError, match="Session"): + pickle.dumps(db) + with pytest.raises(TypeError, match="Session"): + pickle.dumps(table) + + +def test_pickle_rejects_custom_namespace_client(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_custom_ns", pa.table({"id": [1]})) + table._namespace_client = threading.Lock() + + with pytest.raises(TypeError, match="namespace_client"): + pickle.dumps(table) + + +def test_lance_table_pickle_preserves_namespace_path(tmp_path): + pytest.importorskip("lance") + db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) + db.create_namespace(["ns1"]) + table = db.create_table("pickle_ns", pa.table({"id": [1]}), namespace_path=["ns1"]) + + restored = pickle.loads(pickle.dumps(table)) + + assert restored.namespace == ["ns1"] + assert restored.count_rows() == 1 + assert restored._conn._namespace_client_properties == {"root": str(tmp_path)} + + def test_versioning(mem_db: DBConnection): table = mem_db.create_table( "test", diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py index befa3c10f..1cc6500bd 100644 --- a/python/python/tests/test_torch.py +++ b/python/python/tests/test_torch.py @@ -135,6 +135,23 @@ def _open_native_table(uri: str, table_name: str): return lancedb.connect(uri).open_table(table_name) +class _DatasetHoldingConnectionAndTable(torch.utils.data.Dataset): + """User-style Dataset that keeps both the connection and table.""" + + def __init__(self, db, table): + self._db = db + self._table = table + + def __len__(self): + return self._table.count_rows() + + def __getitem__(self, index): + row = self._table.take_offsets([index]).to_arrow().to_pylist()[0] + # Touch the connection too, so workers prove both objects were restored. + row["db_uri"] = self._db.uri + return row + + def test_table_dataloader(mem_db): table = mem_db.create_table("test_table", pa.table({"a": range(1000)})) dataloader = torch.utils.data.DataLoader( @@ -229,6 +246,30 @@ def test_permutation_with_memory_base_is_picklable(mem_db): assert restored.__getitems__([0, 10, 49]) == [{"a": 0}, {"a": 10}, {"a": 49}] +@pytest.mark.parametrize("start_method", ["spawn", "forkserver"]) +def test_dataset_with_connection_and_table_dataloader(tmp_path, start_method): + if start_method not in mp.get_all_start_methods(): + pytest.skip(f"{start_method} start method is not available") + + db = lancedb.connect(tmp_path) + table = db.create_table("test_table", pa.table({"a": range(20)})) + dataset = _DatasetHoldingConnectionAndTable(db, table) + + dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=4, + num_workers=2, + multiprocessing_context=start_method, + ) + + seen = [] + expected_uri = str(tmp_path) + for batch in dataloader: + seen.extend(batch["a"].tolist()) + assert all(uri == expected_uri for uri in batch["db_uri"]) + assert sorted(seen) == list(range(20)) + + def test_permutation_dataloader_multiprocessing(tmp_db): """Using a Permutation with a PyTorch DataLoader that has num_workers > 0 must work end-to-end. Each worker process gets a pickled copy of the diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index bbefc3ca8..db6aa2ba8 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -90,6 +90,75 @@ fn set_storage_options_provider( store_params.storage_options_accessor = Some(Arc::new(accessor)); } +/// Preserve caller-supplied options across provider refreshes. +/// +/// Namespace providers return a fresh credential map and replace the accessor +/// cache, so a plain initial-options accessor would drop caller-only settings +/// after the first refresh. This wrapper merges the caller options into every +/// provider result, with provider values winning overlapping keys. +#[derive(Debug)] +pub(crate) struct LayeredStorageOptionsProvider { + caller_options: HashMap, + inner: Arc, +} + +impl LayeredStorageOptionsProvider { + pub(crate) fn new( + caller_options: HashMap, + inner: Arc, + ) -> Self { + Self { + caller_options, + inner, + } + } + + fn layer( + &self, + mut options: Option>, + ) -> Option> { + let mut merged = self.caller_options.clone(); + match options.take() { + Some(options) => { + merged.extend(options); + Some(merged) + } + None if merged.is_empty() => None, + None => Some(merged), + } + } +} + +#[async_trait::async_trait] +impl StorageOptionsProvider for LayeredStorageOptionsProvider { + async fn fetch_storage_options(&self) -> lance_core::Result>> { + Ok(self.layer(self.inner.fetch_storage_options().await?)) + } + + async fn force_fetch_storage_options( + &self, + ) -> lance_core::Result>> { + Ok(self.layer(self.inner.force_fetch_storage_options().await?)) + } + + fn provider_id(&self) -> String { + use std::hash::{Hash, Hasher}; + + let mut entries: Vec<_> = self.caller_options.iter().collect(); + entries.sort_by_key(|(key, _)| *key); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for (key, value) in entries { + key.hash(&mut hasher); + value.hash(&mut hasher); + } + format!( + "layered(caller_options={:x},{})", + hasher.finish(), + self.inner.provider_id() + ) + } +} + /// A builder for configuring a [`Connection::table_names`] operation pub struct TableNamesBuilder { parent: Arc, diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index 4e61710ff..d603a878b 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -9,7 +9,10 @@ use std::sync::{Arc, Mutex}; use async_trait::async_trait; use lance::io::commit::namespace_manifest::LanceNamespaceExternalManifestStore; -use lance_io::object_store::{ObjectStoreParams, StorageOptionsAccessor}; +use lance_io::object_store::{ + LanceNamespaceStorageOptionsProvider, ObjectStoreParams, StorageOptionsAccessor, + StorageOptionsProvider, +}; use lance_namespace::{ LanceNamespace, error::{ErrorCode, NamespaceError}, @@ -25,7 +28,9 @@ use lance_table::io::commit::CommitHandler; use lance_table::io::commit::external_manifest::ExternalManifestCommitHandler; use crate::blob::ensure_blob_storage_version; -use crate::connection::NamespaceClientPushdownOperation; +use crate::connection::{ + LayeredStorageOptionsProvider, NamespaceClientPushdownOperation, merge_storage_options, +}; use crate::database::ReadConsistency; use crate::database::listing::{NewTableConfig, take_request_creation_overrides}; use crate::database::read_freshness::{ @@ -465,13 +470,29 @@ impl Database for LanceNamespaceDatabase { params.mode = WriteMode::Overwrite; } - // Set up storage options if provided + // Set up storage options if provided. Namespace options take + // precedence for overlapping keys, but must not discard caller-only + // options supplied with the create request. + let store_params = params + .store_params + .get_or_insert_with(ObjectStoreParams::default); + let caller_storage_options = store_params.storage_options().cloned().unwrap_or_default(); if let Some(storage_opts) = initial_storage_options { - let store_params = params - .store_params - .get_or_insert_with(ObjectStoreParams::default); + merge_storage_options(store_params, storage_opts); + } + if let Some(initial_options) = store_params + .storage_options() + .cloned() + .filter(|options| !options.is_empty()) + { + let namespace_provider: Arc = Arc::new( + LanceNamespaceStorageOptionsProvider::new(self.namespace.clone(), table_id.clone()), + ); + let provider: Arc = Arc::new( + LayeredStorageOptionsProvider::new(caller_storage_options, namespace_provider), + ); store_params.storage_options_accessor = Some(Arc::new( - StorageOptionsAccessor::with_static_options(storage_opts), + StorageOptionsAccessor::with_initial_and_provider(initial_options, provider), )); } @@ -618,6 +639,7 @@ mod tests { use arrow_array::{Int32Array, RecordBatch, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; + use lance_io::object_store::StorageOptionsAccessor; use tempfile::tempdir; #[derive(Debug)] diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 775261bb5..4d663649e 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -29,7 +29,9 @@ use lance::index::scalar::load_segment_params; use lance::io::{ObjectStoreParams, WrappingObjectStore}; use lance_datafusion::utils::StreamingWriteSource; use lance_index::IndexCriteria; -use lance_io::object_store::{LanceNamespaceStorageOptionsProvider, StorageOptionsAccessor}; +use lance_io::object_store::{ + LanceNamespaceStorageOptionsProvider, StorageOptionsAccessor, StorageOptionsProvider, +}; pub use query::AnyQuery; use lance::io::commit::namespace_manifest::LanceNamespaceExternalManifestStore; @@ -49,7 +51,7 @@ use std::format; use std::path::Path; use std::sync::Arc; -use crate::connection::NamespaceClientPushdownOperation; +use crate::connection::{LayeredStorageOptionsProvider, NamespaceClientPushdownOperation}; use crate::DistanceType; use crate::blob::BlobRangeRequest; @@ -3679,7 +3681,7 @@ impl NativeTable { } // patch the params if we have a write store wrapper - let params = match write_store_wrapper.clone() { + let mut params = match write_store_wrapper.clone() { Some(wrapper) => params.patch_with_store_wrapper(wrapper)?, None => params, }; @@ -3690,9 +3692,49 @@ impl NativeTable { // Use DatasetBuilder::from_namespace which automatically fetches location // and storage options from the namespace - let builder = DatasetBuilder::from_namespace(namespace_client.clone(), table_id) - .await - .map_err(|e| map_namespace_lance_error(e, name))?; + let mut builder = + DatasetBuilder::from_namespace(namespace_client.clone(), table_id.clone()) + .await + .map_err(|e| map_namespace_lance_error(e, name))?; + + // A caller-supplied read-params accessor replaces the namespace-backed + // accessor in with_read_params. Preserve an explicit provider/accessor; + // only layer static caller options onto the live namespace provider so + // refresh keeps working and namespace values retain their precedence. + if let Some(mut store_options) = params.store_options.take() { + if let Some(accessor) = store_options.get_accessor() { + if accessor.provider().is_some() { + builder = builder.with_store_params(store_options); + } else { + let caller_options = accessor + .initial_storage_options() + .cloned() + .unwrap_or_default(); + let namespace_provider: Arc = + Arc::new(LanceNamespaceStorageOptionsProvider::new( + namespace_client.clone(), + table_id, + )); + let provider: Arc = + Arc::new(LayeredStorageOptionsProvider::new( + caller_options.clone(), + namespace_provider, + )); + let accessor = if caller_options.is_empty() { + Arc::new(StorageOptionsAccessor::with_provider(provider)) + } else { + Arc::new(StorageOptionsAccessor::with_initial_and_provider( + caller_options, + provider, + )) + }; + store_options.storage_options_accessor = Some(accessor); + builder = builder.with_store_params(store_options); + } + } else { + builder = builder.with_store_params(store_options); + } + } let dataset = builder .with_read_params(params) @@ -3901,10 +3943,9 @@ impl NativeTable { table_id.push(name.to_string()); // Set up storage options provider from namespace - let storage_options_provider = Arc::new(LanceNamespaceStorageOptionsProvider::new( - namespace_client.clone(), - table_id, - )); + let namespace_provider: Arc = Arc::new( + LanceNamespaceStorageOptionsProvider::new(namespace_client.clone(), table_id), + ); // Start with provided params or defaults let mut params = params.unwrap_or_default(); @@ -3914,17 +3955,40 @@ impl NativeTable { params.session = Some(sess); } - // Ensure store_params exists and set the storage options provider + // Ensure store_params exists and preserve an already-layered provider + // from create_table, or attach the namespace provider to the caller's + // initial options for other callers. let store_params = params .store_params .get_or_insert_with(ObjectStoreParams::default); - let accessor = match store_params.storage_options().cloned() { - Some(options) => { - StorageOptionsAccessor::with_initial_and_provider(options, storage_options_provider) + let accessor = match store_params.storage_options_accessor.take() { + Some(existing) + if existing.provider().is_some() + && existing.initial_storage_options().is_some() => + { + existing } - None => StorageOptionsAccessor::with_provider(storage_options_provider), + Some(existing) => { + let options = existing + .initial_storage_options() + .cloned() + .unwrap_or_default(); + let provider: Arc = Arc::new( + LayeredStorageOptionsProvider::new(options.clone(), namespace_provider), + ); + if options.is_empty() { + Arc::new(StorageOptionsAccessor::with_provider(provider)) + } else { + Arc::new(StorageOptionsAccessor::with_initial_and_provider( + options, provider, + )) + } + } + None => Arc::new(StorageOptionsAccessor::with_provider(Arc::new( + LayeredStorageOptionsProvider::new(HashMap::new(), namespace_provider), + ))), }; - store_params.storage_options_accessor = Some(Arc::new(accessor)); + store_params.storage_options_accessor = Some(accessor); // Patch the params if we have a write store wrapper let params = match write_store_wrapper.clone() { From 28e9ebb3ddda2cafac6f861919375ca31e91fb4a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:22:12 +0800 Subject: [PATCH 07/18] fix(python): reject unsupported fragment constraints (#5120) `with_fragments()` / `fragment_ids()` were only honored by the embedded plain-scan blob Pandas path. Every other sync, async, and remote terminal could silently ignore the selection and scan the full table, and async query conversions plus FTS `count_rows()` could drop the constraint before execution. This change makes unsupported paths fail with `NotImplementedError` before I/O, preserves fragment state across async Standard/Vector/FTS/Hybrid conversions, and keeps the supported embedded blob `to_pandas()` behavior unchanged. The FTS `count_rows()` sync and async entry points now reject fragment constraints explicitly. Refs OSS-2859 --- python/python/lancedb/query.py | 205 ++++++++++++++++---- python/python/tests/test_hybrid_query.py | 25 +++ python/python/tests/test_query.py | 231 +++++++++++++++++++++++ python/python/tests/test_remote_db.py | 30 +++ 4 files changed, 456 insertions(+), 35 deletions(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index dee2a480d..60fab3b8e 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -273,6 +273,24 @@ def _query_needs_lance_scanner(builder: Any) -> bool: ) +def _raise_unsupported_fragment_constraints( + fragments: Optional[Any], + fragment_ids: Optional[List[int]], + *, + operation: str, +) -> None: + """Reject fragment selection where execution would silently scan everything.""" + if fragments is None and fragment_ids is None: + return + raise NotImplementedError( + "with_fragments() and fragment_ids() are only supported for embedded " + "plain-scan blob queries executed through to_pandas(). " + f"{operation} would ignore the fragment selection and scan the full " + "table. Remove the fragment constraint, or use table.to_lance() with " + "a Lance scanner for this query shape." + ) + + def _query_is_plain_scan(query: Query) -> bool: return ( query.vector is None @@ -1686,11 +1704,19 @@ class LanceQueryBuilder(ABC): return self._user_requested_row_id() or self._blob_auto_row_id_enabled() def _query_for_scan(self, blob_sources: Optional[dict[str, str]] = None) -> Query: + self._ensure_fragment_constraints_supported("this query") query = self.to_query_object() if self._scan_needs_row_id() or blob_sources: query.with_row_id = True return query + def _ensure_fragment_constraints_supported(self, operation: str) -> None: + _raise_unsupported_fragment_constraints( + self._fragments, + self._fragment_ids, + operation=operation, + ) + def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool: if blob_mode != "bytes": return False @@ -1826,12 +1852,51 @@ class LanceQueryBuilder(ABC): return self def with_fragments(self, fragments: Any) -> Self: - """Set the Lance fragments to scan for plain scanner-backed queries.""" + """Restrict an embedded plain-scan blob query to the given Lance fragments. + + Fragment selection is supported only when ``to_pandas()`` uses the + embedded Lance plain-scan path: the table is an embedded, non-memory + Lance dataset, the query is a plain scan (no vector, full-text, take, + postfilter, or ordering), and the selected output includes a blob + column. Other terminals and remote tables raise ``NotImplementedError`` + before scanning instead of silently scanning the full table. + Blob-specific ``to_pandas()`` fallbacks keep their existing validation + errors. + + Parameters + ---------- + fragments : list[lance.Fragment] + Fragments from ``table.to_lance().get_fragments()``. Pass fragments + from the same dataset snapshot. + + Returns + ------- + LanceQueryBuilder + The LanceQueryBuilder object. + """ self._fragments = fragments return self def fragment_ids(self, fragment_ids: List[int]) -> Self: - """Set the Lance fragment ids to scan for plain scanner-backed queries.""" + """Restrict an embedded plain-scan blob query to the given fragment ids. + + Fragment selection uses the same supported ``to_pandas()`` path as + ``with_fragments()``. On that path, an empty list selects no rows and + missing ids raise ``ValueError``. Other terminals and remote tables + raise ``NotImplementedError`` before scanning instead of silently + scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep + their existing validation errors. + + Parameters + ---------- + fragment_ids : list[int] + Fragment ids from ``table.to_lance().get_fragments()``. + + Returns + ------- + LanceQueryBuilder + The LanceQueryBuilder object. + """ self._fragment_ids = fragment_ids return self @@ -1887,6 +1952,7 @@ class LanceQueryBuilder(ABC): ------- plan : str """ # noqa: E501 + self._ensure_fragment_constraints_supported("explain_plan()") return self._table._explain_plan(self.to_query_object(), verbose=verbose) def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self: @@ -1961,6 +2027,7 @@ class LanceQueryBuilder(ABC): plan : str The physical query execution plan with runtime metrics. """ + self._ensure_fragment_constraints_supported("analyze_plan()") return self._table._analyze_plan( self.to_query_object(), distributed_metrics=distributed_metrics ) @@ -2629,6 +2696,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): For example, ``table.search("gripper closed", query_type="fts",`` ``operator="AND").where("active = true").count_rows()``. """ + self._ensure_fragment_constraints_supported("count_rows()") self._table._ensure_no_legacy_fts_index() query = self._table._table._sync_query_to_async(self.to_query_object()) assert isinstance(query, AsyncFTSQuery) @@ -3522,6 +3590,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): def _create_query_builders(self): """Set up and configure the vector and FTS query builders.""" + self._ensure_fragment_constraints_supported("this hybrid query") vector_query, fts_query = self._validate_query( self._query, self._vector, self._text ) @@ -3640,6 +3709,19 @@ class AsyncQueryBase(object): def _user_requested_row_id(self) -> bool: return self._with_row_id is True + def _ensure_fragment_constraints_supported(self, operation: str) -> None: + _raise_unsupported_fragment_constraints( + self._fragments, + self._fragment_ids, + operation=operation, + ) + + def _inherit_fragment_constraints(self, query: Any) -> Any: + """Carry a fragment selection across an async query conversion.""" + query._fragments = self._fragments + query._fragment_ids = self._fragment_ids + return query + def _blob_auto_row_id_enabled(self) -> bool: return self._blob_auto_row_id @@ -3750,15 +3832,30 @@ class AsyncQueryBase(object): return self def with_fragments(self, fragments: Any) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragments. + """Restrict an embedded plain-scan blob query to the given Lance fragments. + + Fragment selection is supported only when ``to_pandas()`` uses the + embedded Lance plain-scan path: the table is an embedded, non-memory + Lance dataset, the query is a plain scan (no vector, full-text, take, + postfilter, or ordering), and the selected output includes a blob + column. The constraint is preserved when converting between async + query types. Other terminals and remote tables raise + ``NotImplementedError`` before scanning instead of silently scanning + the full table. Blob-specific ``to_pandas()`` fallbacks keep their + existing validation errors. """ self._fragments = fragments return self def fragment_ids(self, fragment_ids: List[int]) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragment ids. + """Restrict an embedded plain-scan blob query to the given fragment ids. + + Fragment selection uses the same supported ``to_pandas()`` path as + ``with_fragments()``. On that path, an empty list selects no rows and + missing ids raise ``ValueError``. Other terminals and remote tables + raise ``NotImplementedError`` before scanning instead of silently + scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep + their existing validation errors. """ self._fragment_ids = fragment_ids return self @@ -3838,6 +3935,7 @@ class AsyncQueryBase(object): timeout: Optional[timedelta] = None, blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: + self._ensure_fragment_constraints_supported("to_batches()") if ( blob_sources and not self._user_requested_row_id() @@ -4245,6 +4343,7 @@ class AsyncQueryBase(object): ------- plan : str """ # noqa: E501 + self._ensure_fragment_constraints_supported("explain_plan()") return await self._inner.explain_plan(verbose) async def analyze_plan( @@ -4262,6 +4361,7 @@ class AsyncQueryBase(object): ------- plan : str """ + self._ensure_fragment_constraints_supported("analyze_plan()") return await self._inner.analyze_plan(distributed_metrics) @@ -4501,11 +4601,17 @@ class AsyncQuery(AsyncStandardQuery): new_self = self._inner.nearest_to(query_vectors[0]) for v in query_vectors[1:]: new_self.add_query_vector(v) - return AsyncVectorQuery(new_self, self._table) + return self._inherit_fragment_constraints( + AsyncVectorQuery(new_self, self._table) + ) else: - return AsyncVectorQuery( - self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)), - self._table, + return self._inherit_fragment_constraints( + AsyncVectorQuery( + self._inner.nearest_to( + AsyncQuery._query_vec_to_array(query_vector) + ), + self._table, + ) ) def nearest_to_text( @@ -4545,18 +4651,22 @@ class AsyncQuery(AsyncStandardQuery): columns = [] if isinstance(query, str): - return AsyncFTSQuery( - self._inner.nearest_to_text( - { - "query": query, - "columns": columns, - "operator": fts_query.operator, - } - ), - self._table, + return self._inherit_fragment_constraints( + AsyncFTSQuery( + self._inner.nearest_to_text( + { + "query": query, + "columns": columns, + "operator": fts_query.operator, + } + ), + self._table, + ) ) # FullTextQuery object - return AsyncFTSQuery(self._inner.nearest_to_text({"query": query}), self._table) + return self._inherit_fragment_constraints( + AsyncFTSQuery(self._inner.nearest_to_text({"query": query}), self._table) + ) class AsyncFTSQuery(AsyncStandardQuery): @@ -4577,6 +4687,7 @@ class AsyncFTSQuery(AsyncStandardQuery): For example, ``await table.query().nearest_to_text("gripper closed",`` ``operator="AND").where("active = true").count_rows()``. """ + self._ensure_fragment_constraints_supported("count_rows()") try: return await self._inner.count_rows() except Exception as error: @@ -4662,11 +4773,17 @@ class AsyncFTSQuery(AsyncStandardQuery): new_self = self._inner.nearest_to(query_vectors[0]) for v in query_vectors[1:]: new_self.add_query_vector(v) - return AsyncHybridQuery(new_self, self._table) + return self._inherit_fragment_constraints( + AsyncHybridQuery(new_self, self._table) + ) else: - return AsyncHybridQuery( - self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)), - self._table, + return self._inherit_fragment_constraints( + AsyncHybridQuery( + self._inner.nearest_to( + AsyncQuery._query_vec_to_array(query_vector) + ), + self._table, + ) ) async def _execute_batches( @@ -5002,15 +5119,21 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): columns = [] if isinstance(query, str): - return AsyncHybridQuery( - self._inner.nearest_to_text( - {"query": query, "columns": columns, "operator": fts_query.operator} - ), - self._table, + return self._inherit_fragment_constraints( + AsyncHybridQuery( + self._inner.nearest_to_text( + { + "query": query, + "columns": columns, + "operator": fts_query.operator, + } + ), + self._table, + ) ) # FullTextQuery object - return AsyncHybridQuery( - self._inner.nearest_to_text({"query": query}), self._table + return self._inherit_fragment_constraints( + AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table) ) async def _execute_batches( @@ -5098,6 +5221,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): the hybrid query itself. The key the legs are fused on, if any, is left on `self._pk_fusion`. """ + self._ensure_fragment_constraints_supported("this hybrid query") fts_query = AsyncFTSQuery(self._inner.to_fts_query(), self._table) vec_query = AsyncVectorQuery(self._inner.to_vector_query(), self._table) @@ -5394,15 +5518,26 @@ class BaseQueryBuilder(object): return self def with_fragments(self, fragments: Any) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragments. + """Restrict execution to the given Lance fragments. + + Fragment selection is supported only by embedded plain-scan blob + queries through ``to_pandas()``. Other terminals and remote tables + raise ``NotImplementedError`` before scanning instead of silently + scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep + their existing validation errors. """ self._inner.with_fragments(fragments) return self def fragment_ids(self, fragment_ids: List[int]) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragment ids. + """Restrict execution to the given Lance fragment ids. + + Fragment selection is supported only by embedded plain-scan blob + queries through ``to_pandas()``. On that path, an empty list selects no + rows and missing ids raise ``ValueError``. Other terminals and remote + tables raise ``NotImplementedError`` before scanning instead of + silently scanning the full table. Blob-specific ``to_pandas()`` + fallbacks keep their existing validation errors. """ self._inner.fragment_ids(fragment_ids) return self diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index 443fdebc4..ec6060db3 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -81,6 +81,31 @@ async def test_async_hybrid_query_with_row_ids(table: AsyncTable): assert result["_rowid"].to_pylist() == [0, 3] +def test_hybrid_fragment_constraints_fail_loud(sync_table: Table): + query = ( + sync_table.search("dog", query_type="hybrid") + .vector([0.5, -0.5]) + .fragment_ids([0]) + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + query.to_arrow() + with pytest.raises(NotImplementedError, match="fragment selection"): + query.explain_plan() + + +@pytest.mark.asyncio +async def test_async_hybrid_fragment_constraints_fail_loud(table: AsyncTable): + query = ( + table.query().nearest_to([0.5, -0.5]).nearest_to_text("dog").fragment_ids([0]) + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.to_arrow() + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.analyze_plan() + + @pytest.mark.asyncio async def test_async_hybrid_query_filters(table: AsyncTable): # test that query params are passed down from the regular builder to diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index aee67d32a..88bed9c1f 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -69,6 +69,36 @@ def _blob_query_data(): ) +def _fragment_query_data(): + return pa.table( + { + "id": pa.array([1, 2, 3, 4], pa.int64()), + "text": pa.array(["one", "two", "three", "four"], pa.utf8()), + "vector": pa.array( + [[1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0]], + type=pa.list_(pa.float32(), list_size=2), + ), + } + ) + + +def _fragment_query_table(db, name): + data = _fragment_query_data() + table = db.create_table(name, data.slice(0, 2)) + table.add(data.slice(2, 2)) + return table + + +def _apply_fragment_restriction(query, restriction, fragment): + if restriction == "ids": + return query.fragment_ids([fragment.fragment_id]) + if restriction == "empty": + return query.fragment_ids([]) + if restriction == "fragments": + return query.with_fragments([fragment]) + raise AssertionError(f"unknown restriction: {restriction}") + + def _create_blob_v2_query_table(db, name): schema = pa.schema( [ @@ -435,6 +465,207 @@ def test_plain_scan_query_to_pandas_scanner_state(tmp_db): ) assert df_by_fragment["id"].tolist() == [1, 2] + empty = ( + table.search() + .select(["id", "blob"]) + .fragment_ids([]) + .to_pandas(blob_mode="descriptions") + ) + assert empty.empty + with pytest.raises(ValueError, match="fragment_ids not found in dataset: 999"): + ( + table.search() + .select(["id", "blob"]) + .fragment_ids([999]) + .to_pandas(blob_mode="descriptions") + ) + + +@pytest.mark.parametrize( + "terminal", + [ + "to_arrow", + "to_batches", + "to_pandas", + "to_polars", + "to_list", + "explain_plan", + "analyze_plan", + ], +) +def test_fragment_constraints_fail_loud_on_unsupported_paths(tmp_db, terminal): + pytest.importorskip("lance") + table = _fragment_query_table(tmp_db, f"fragment_guard_{terminal}") + fragment_id = table.to_lance().get_fragments()[0].fragment_id + query = table.search().fragment_ids([fragment_id]) + + with pytest.raises(NotImplementedError, match="fragment selection"): + getattr(query, terminal)() + + +def test_with_fragments_fails_loud_on_plain_and_vector_queries(tmp_db): + pytest.importorskip("lance") + table = _fragment_query_table(tmp_db, "fragment_guard_with_fragments") + fragment = table.to_lance().get_fragments()[0] + + for query in ( + table.search().with_fragments([fragment]), + table.search([0.0, 0.0]).with_fragments([fragment]), + ): + with pytest.raises(NotImplementedError, match="fragment selection"): + query.to_arrow() + + +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"]) +def test_fts_count_rows_rejects_fragment_constraints(tmp_db, restriction): + pytest.importorskip("lance") + table = _fragment_query_table(tmp_db, f"fts_count_rows_{restriction}") + table.create_index("text", config=FTS(with_position=False)) + fragment = table.to_lance().get_fragments()[1] + query = _apply_fragment_restriction( + table.search("one", query_type="fts"), restriction, fragment + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + query.count_rows() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "terminal", + [ + "to_arrow", + "to_batches", + "to_pandas", + "to_polars", + "to_list", + "explain_plan", + "analyze_plan", + ], +) +async def test_async_fragment_constraints_fail_loud_on_unsupported_paths( + tmp_db_async, terminal +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + f"async_fragment_guard_{terminal}", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + fragments = (await table.to_lance()).get_fragments() + query = table.query().fragment_ids([fragments[0].fragment_id]) + + with pytest.raises(NotImplementedError, match="fragment selection"): + await getattr(query, terminal)() + + +@pytest.mark.asyncio +async def test_async_with_fragments_fails_loud_on_plain_and_vector_queries( + tmp_db_async, +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + "async_fragment_guard_with_fragments", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + fragments = (await table.to_lance()).get_fragments() + + for query in ( + table.query().with_fragments([fragments[0]]), + table.query().nearest_to([0.0, 0.0]).with_fragments([fragments[0]]), + ): + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.to_arrow() + + +@pytest.mark.asyncio +async def test_async_plain_scan_fragment_constraints_preserved(tmp_db_async): + pytest.importorskip("lance") + data = _blob_query_data() + table = await tmp_db_async.create_table( + "async_fragment_supported", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + await table.add(data.slice(2, 2)) + fragments = (await table.to_lance()).get_fragments() + + df = await ( + table.query() + .select(["id", "blob"]) + .fragment_ids([fragments[1].fragment_id]) + .to_pandas(blob_mode="descriptions") + ) + + assert df["id"].tolist() == [3, 4] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"]) +async def test_async_fts_count_rows_rejects_fragment_constraints( + tmp_db_async, restriction +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + f"async_fts_count_rows_{restriction}", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + await table.create_index("text", config=FTS(with_position=False)) + fragment = (await table.to_lance()).get_fragments()[1] + query = _apply_fragment_restriction( + table.query().nearest_to_text("one"), restriction, fragment + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.count_rows() + + transitioned = _apply_fragment_restriction( + table.query(), restriction, fragment + ).nearest_to_text("one") + with pytest.raises(NotImplementedError, match="fragment selection"): + await transitioned.count_rows() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"]) +@pytest.mark.parametrize( + "transition", + ["query_to_vector", "query_to_fts", "fts_to_hybrid", "vector_to_hybrid"], +) +async def test_async_fragment_constraints_survive_query_transitions( + tmp_db_async, transition, restriction +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + f"async_transition_{transition}_{restriction}", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + await table.create_index("text", config=FTS(with_position=False)) + fragment = (await table.to_lance()).get_fragments()[1] + + if transition == "query_to_vector": + query = _apply_fragment_restriction( + table.query(), restriction, fragment + ).nearest_to([0.0, 0.0]) + elif transition == "query_to_fts": + query = _apply_fragment_restriction( + table.query(), restriction, fragment + ).nearest_to_text("one") + elif transition == "fts_to_hybrid": + query = _apply_fragment_restriction( + table.query().nearest_to_text("one"), restriction, fragment + ).nearest_to([0.0, 0.0]) + else: + query = _apply_fragment_restriction( + table.query().nearest_to([0.0, 0.0]), restriction, fragment + ).nearest_to_text("one") + + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.to_arrow() + @pytest.mark.asyncio async def test_async_plain_scan_query_to_pandas_blob_projection(tmp_db_async): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index a2a26b595..ad46b5d3b 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -4163,6 +4163,36 @@ def query_test_table( yield table +def test_remote_fragment_constraints_fail_before_query(): + query_calls = 0 + + def query_handler(body): + nonlocal query_calls + query_calls += 1 + return pa.table({"text": ["unexpected"]}) + + with query_test_table(query_handler) as table: + with pytest.raises(NotImplementedError, match="fragment selection"): + table.search().fragment_ids([0]).to_arrow() + + assert query_calls == 0 + + +def test_remote_fts_count_rows_rejects_fragment_constraints(): + query_calls = 0 + + def query_handler(body): + nonlocal query_calls + query_calls += 1 + return pa.table({"text": ["unexpected"]}) + + with query_test_table(query_handler) as table: + with pytest.raises(NotImplementedError, match="fragment selection"): + table.search("hello", query_type="fts").fragment_ids([0]).count_rows() + + assert query_calls == 0 + + @pytest.mark.parametrize( "query,search_kwargs,expected_column", [ From 164aec17538b47b54d3e78643b3a32d76144d51a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:24:15 +0800 Subject: [PATCH 08/18] fix(python): start background event loop lazily (#5111) ## Summary Importing `lancedb` currently starts a daemon thread running a private asyncio loop, even when the process never performs a synchronous database operation. Start that loop on the first actual coroutine submission instead. Concurrent first callers share one initialization, and a forked child resets the singleton to the unstarted state without touching the inherited thread or lock, then starts fresh work lazily on first use. The Rust-side runtime and the existing fork/reopen contracts are unchanged. ## Validation - New import, first-use, concurrent first-use, and fork parent/child coverage passes. - Existing import, debugger-inspection, cancellation, and remote fork tests pass. - `ruff format --check .` and `ruff check .` pass. --- python/python/lancedb/background_loop.py | 62 +++-- python/python/tests/test_background_loop.py | 236 ++++++++++++++++++++ python/python/tests/test_remote_db.py | 6 +- 3 files changed, 285 insertions(+), 19 deletions(-) create mode 100644 python/python/tests/test_background_loop.py diff --git a/python/python/lancedb/background_loop.py b/python/python/lancedb/background_loop.py index 9e1fdfbd8..7e55e708b 100644 --- a/python/python/lancedb/background_loop.py +++ b/python/python/lancedb/background_loop.py @@ -13,22 +13,51 @@ class BackgroundEventLoop: A background event loop that can run futures. Used to bridge sync and async code, without messing with users event loops. + + The loop and its thread are created by the first call to :meth:`run`, not + by constructing this object, so importing lancedb does not leave an idle + background thread behind. """ def __init__(self): - self._start() + self.loop: asyncio.AbstractEventLoop | None = None + self.thread: threading.Thread | None = None + self._start_lock = threading.Lock() - def _start(self): - self.loop = asyncio.new_event_loop() - self.thread = threading.Thread( - target=self.loop.run_forever, - name="LanceDBBackgroundEventLoop", - daemon=True, - ) - self.thread.start() + def _start(self) -> asyncio.AbstractEventLoop: + loop = self.loop + if loop is not None: + return loop + with self._start_lock: + loop = self.loop + if loop is not None: + return loop + loop = asyncio.new_event_loop() + thread = threading.Thread( + target=loop.run_forever, + name="LanceDBBackgroundEventLoop", + daemon=True, + ) + thread.start() + # Publish the loop first and the thread last. Callers that reach + # _start while this is in progress wait on _start_lock, so they + # cannot observe a half-initialized loop/thread pair. + self.loop = loop + self.thread = thread + return loop + + def _reset_after_fork(self): + # Threads do not survive fork(). Reset to the unstarted state without + # calling into the inherited loop or thread: the thread is gone, and + # it may have held _start_lock when the fork happened. A fresh lock + # lets the child start a new loop on its first run(). + self.loop = None + self.thread = None + self._start_lock = threading.Lock() def run(self, future): - concurrent_future = asyncio.run_coroutine_threadsafe(future, self.loop) + loop = self._start() + concurrent_future = asyncio.run_coroutine_threadsafe(future, loop) try: return concurrent_future.result() except BaseException: @@ -60,12 +89,15 @@ _FORK_WARNED = False def _reset_after_fork(): - # Threads do not survive fork(), so the asyncio loop in LOOP.thread is - # dead in the child. Re-initialize the singleton in place so existing + # Threads do not survive fork(), so the loop in LOOP.thread is dead in + # the child. Reset the singleton in place so existing # `from .background_loop import LOOP` references in other modules see - # the new state. The Rust-side tokio runtime is reset analogously by a - # pthread_atfork hook installed in the _lancedb extension. - LOOP._start() + # the unstarted state and create a fresh loop on their first run(). Do + # not restart it here: the child may never use LanceDB, and the at-fork + # handler must not touch the vanished thread or acquire inherited locks. + # The Rust-side tokio runtime is reset analogously by a pthread_atfork + # hook installed in the _lancedb extension. + LOOP._reset_after_fork() # The embedding executor's worker threads are dead in the child as well. # Replace it with a fresh pool (threads are spawned lazily, so this is # cheap); we don't shut down the old one, since joining its dead workers diff --git a/python/python/tests/test_background_loop.py b/python/python/tests/test_background_loop.py new file mode 100644 index 000000000..52b8b1f73 --- /dev/null +++ b/python/python/tests/test_background_loop.py @@ -0,0 +1,236 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import multiprocessing as mp +import os +import subprocess +import sys +import textwrap +import traceback + +import pytest + + +BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop" + + +def _run_in_subprocess(code: str) -> subprocess.CompletedProcess: + env = os.environ.copy() + env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path) + return subprocess.run( + [sys.executable, "-c", textwrap.dedent(code)], + check=False, + capture_output=True, + text=True, + env=env, + timeout=30, + ) + + +def _assert_subprocess_ok(result: subprocess.CompletedProcess) -> None: + assert result.returncode == 0, result.stderr or result.stdout + + +def test_import_and_inspection_do_not_start_background_loop(): + result = _run_in_subprocess( + f""" + import threading + + import lancedb + from lancedb.background_loop import BackgroundEventLoop, LOOP + + def background_threads(): + return [ + thread + for thread in threading.enumerate() + if thread.name == {BACKGROUND_THREAD_NAME!r} + ] + + assert LOOP.thread is None + assert LOOP.loop is None + assert background_threads() == [] + + # Inspecting a fresh instance is also side-effect free. + loop = BackgroundEventLoop() + assert loop.thread is None + assert loop.loop is None + assert background_threads() == [] + """ + ) + _assert_subprocess_ok(result) + + +def test_first_sync_call_starts_one_daemon_thread(): + result = _run_in_subprocess( + f""" + import threading + + import lancedb + from lancedb.background_loop import LOOP + + def background_threads(): + return [ + thread + for thread in threading.enumerate() + if thread.name == {BACKGROUND_THREAD_NAME!r} + ] + + assert LOOP.thread is None + assert LOOP.loop is None + + db = lancedb.connect("memory://") + assert db.table_names() == [] + + worker = LOOP.thread + assert worker is not None + assert worker is background_threads()[0] + assert len(background_threads()) == 1 + assert worker.daemon + assert worker.is_alive() + assert LOOP.loop is not None + """ + ) + _assert_subprocess_ok(result) + + +def test_concurrent_first_use_initializes_one_background_thread(): + result = _run_in_subprocess( + f""" + import asyncio + import threading + + from lancedb.background_loop import LOOP + + worker_count = 8 + barrier = threading.Barrier(worker_count) + results = [] + errors = [] + results_lock = threading.Lock() + + def submit(index): + try: + barrier.wait(timeout=10) + value = LOOP.run(asyncio.sleep(0.05, result=index)) + with results_lock: + results.append(value) + except BaseException as exc: + with results_lock: + errors.append(repr(exc)) + + threads = [ + threading.Thread(target=submit, args=(index,)) + for index in range(worker_count) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=20) + + assert all(not thread.is_alive() for thread in threads) + assert errors == [] + assert sorted(results) == list(range(worker_count)) + + background_threads = [ + thread + for thread in threading.enumerate() + if thread.name == {BACKGROUND_THREAD_NAME!r} + ] + assert len(background_threads) == 1 + assert background_threads[0].daemon + """ + ) + _assert_subprocess_ok(result) + + +def _fork_child_starts_lazily(queue): + def background_threads(): + import threading + + return [ + thread + for thread in threading.enumerate() + if thread.name == BACKGROUND_THREAD_NAME + ] + + try: + from lancedb.background_loop import LOOP + + inherited_thread_is_none = LOOP.thread is None + inherited_loop_is_none = LOOP.loop is None + background_threads_before = [thread.name for thread in background_threads()] + + import lancedb + + db = lancedb.connect("memory://") + tables = db.table_names() + + worker = LOOP.thread + queue.put( + { + "error": None, + "inherited_thread_is_none": inherited_thread_is_none, + "inherited_loop_is_none": inherited_loop_is_none, + "background_threads_before": background_threads_before, + "tables": tables, + "thread_alive": False if worker is None else worker.is_alive(), + "thread_daemon": False if worker is None else worker.daemon, + "background_thread_count": len(background_threads()), + } + ) + except BaseException: + queue.put({"error": traceback.format_exc()}) + + +@pytest.mark.skipif( + sys.platform != "linux", + reason=( + "fork() is unavailable on Windows and unsafe on macOS " + "(Apple frameworks/TLS are not fork-safe)" + ), +) +def test_forked_child_starts_background_loop_lazily(): + import asyncio + + from lancedb.background_loop import LOOP + + assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before" + parent_thread = LOOP.thread + assert parent_thread is not None + + ctx = mp.get_context("fork") + queue = ctx.Queue() + + # Simulate forking while another thread held the initialization lock. The + # child must replace the inherited lock instead of trying to acquire it. + LOOP._start_lock.acquire() + try: + proc = ctx.Process(target=_fork_child_starts_lazily, args=(queue,)) + proc.start() + finally: + LOOP._start_lock.release() + + proc.join(timeout=20) + if proc.is_alive(): + proc.terminate() + proc.join(timeout=5) + if proc.is_alive(): + proc.kill() + proc.join() + pytest.fail("Forked child hung starting the background loop") + + assert proc.exitcode == 0, f"child exited with code {proc.exitcode}" + payload = queue.get(timeout=5) + queue.close() + assert payload["error"] is None, payload["error"] + assert payload["inherited_thread_is_none"] is True + assert payload["inherited_loop_is_none"] is True + assert payload["background_threads_before"] == [] + assert payload["tables"] == [] + assert payload["thread_alive"] is True + assert payload["thread_daemon"] is True + assert payload["background_thread_count"] == 1 + + # The child's reset must not disturb the parent's loop. + assert LOOP.thread is parent_thread + assert parent_thread.is_alive() + assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after" diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ad46b5d3b..e3ab986e2 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5370,12 +5370,10 @@ def test_background_loop_cancellation(exception): mock_future = MagicMock() mock_future.result.side_effect = exception() - with ( - patch.object(BackgroundEventLoop, "__init__", return_value=None), - patch("asyncio.run_coroutine_threadsafe", return_value=mock_future), - ): + with patch("asyncio.run_coroutine_threadsafe", return_value=mock_future): loop = BackgroundEventLoop() loop.loop = MagicMock() + loop.thread = MagicMock() with pytest.raises(exception): loop.run(None) mock_future.cancel.assert_called_once() From b9a2807049ee13ab3688672b2633c82831d2416f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:25:06 +0800 Subject: [PATCH 09/18] fix(python): accept column names in order_by and validate early (#5119) ## Summary - Accept column names, `(column_name, "asc"|"desc")` tuples, `ColumnOrdering`, and `{"column_name": ...}` dicts in both sync and async `order_by`, including mixed lists. - Distinguish a bare direction tuple from a list of column names by container type; `None` and `[]` clear ordering. - Validate at setter time with actionable errors for unknown dict keys and invalid directions. - Export `ColumnOrdering` from `lancedb` and document the accepted forms with examples. - Reject non-empty ordering on sync hybrid queries explicitly instead of silently ignoring it. Fixes OSS-3108. Namespace pushdown (OSS-3126) is intentionally out of scope. ## Tests - `python/tests/test_query.py` (214 passed, 1 skipped) - `python/tests/test_query.py -k order_by` (7 passed) - `python/tests/test_fts.py -k order_by` (2 passed) - `python/tests/test_remote_db.py::test_query_sync_maximal` - `pytest --doctest-modules python/lancedb/query.py` (21 passed) - `ruff format` / `ruff check` --- docs/src/python/python.md | 2 + python/python/lancedb/__init__.py | 1 + python/python/lancedb/query.py | 172 ++++++++++++++++++++++++++++-- python/python/tests/test_query.py | 107 +++++++++++++++++++ 4 files changed, 271 insertions(+), 11 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 752bf540f..122a73019 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -793,6 +793,8 @@ of raw SQL strings with [where][lancedb.query.LanceQueryBuilder.where] and ::: lancedb.query.Query +::: lancedb.query.ColumnOrdering + ::: lancedb.query.LanceQueryBuilder ::: lancedb.query.LanceVectorQueryBuilder diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 129a4b1c5..5095fddb0 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -79,6 +79,7 @@ from .materialized_view import ( from .view import ViewDescription as ViewDescription from .graph import PropertyGraph, PropertyGraphDescription from .table import AsyncTable, CompactionOptions, Table +from .query import ColumnOrdering as ColumnOrdering from .types import BaseTokenizerType from ._lancedb import Session from .namespace import ( diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 60fab3b8e..76d98e4f6 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -589,11 +589,107 @@ def ensure_vector_query( class ColumnOrdering(pydantic.BaseModel): + """A single sort key for ``order_by``. + + Attributes + ---------- + column_name: str + The column to sort by. + ascending: bool, default True + Sort ascending when true, descending otherwise. + nulls_first: bool, default False + Place null values before non-null values when true. + """ + column_name: str ascending: bool = True nulls_first: bool = False +_OrderingItem = Union[str, Tuple[str, str], ColumnOrdering, Dict[str, Any]] +_OrderingInput = Optional[Union[_OrderingItem, List[_OrderingItem]]] +_COLUMN_ORDERING_KEYS = frozenset({"column_name", "ascending", "nulls_first"}) +_ORDERING_EXAMPLE = '[{"column_name": "uris", "ascending": True}]' + + +def _normalize_ordering(ordering: _OrderingInput) -> Optional[List[ColumnOrdering]]: + """Normalize the accepted ``order_by`` inputs into ``ColumnOrdering`` models. + + ``None`` and an empty list clear the ordering. A tuple is always a single + ``(column_name, "asc"|"desc")`` pair, while a list is always a sequence of + separate orderings, so ``("a", "desc")`` and ``["a", "desc"]`` differ. + """ + if ordering is None: + return None + if isinstance(ordering, tuple): + items: List[Any] = [ordering] + elif isinstance(ordering, list): + items = ordering + else: + items = [ordering] + + normalized = [ + _normalize_ordering_item(item, index) for index, item in enumerate(items) + ] + return normalized or None + + +def _normalize_ordering_item(item: Any, index: int) -> ColumnOrdering: + prefix = f"order_by entry {index}" + if isinstance(item, ColumnOrdering): + if not item.column_name: + raise ValueError(f"{prefix} has an empty column_name") + return item + if isinstance(item, str): + if not item: + raise ValueError(f"{prefix} is an empty column name") + return ColumnOrdering(column_name=item) + if isinstance(item, tuple): + if len(item) != 2: + raise ValueError( + f"{prefix} must be a (column_name, 'asc'|'desc') tuple; got {item!r}" + ) + column_name, direction = item + if not isinstance(column_name, str) or not column_name: + raise ValueError( + f"{prefix} must start with a non-empty column name; got {item!r}" + ) + if not isinstance(direction, str) or direction.lower() not in ("asc", "desc"): + raise ValueError( + f"{prefix} has invalid direction {direction!r}; " + "expected 'asc' or 'desc'" + ) + return ColumnOrdering( + column_name=column_name, ascending=direction.lower() == "asc" + ) + if isinstance(item, dict): + unknown_keys = set(item) - _COLUMN_ORDERING_KEYS + if unknown_keys: + raise ValueError( + f"{prefix} has unsupported key(s) {sorted(map(str, unknown_keys))}; " + f"expected keys: {sorted(_COLUMN_ORDERING_KEYS)}. " + f"Example: {_ORDERING_EXAMPLE}" + ) + if "column_name" not in item: + raise ValueError( + f"{prefix} is missing 'column_name'. Example: {_ORDERING_EXAMPLE}" + ) + try: + normalized = ColumnOrdering(**item) + except pydantic.ValidationError as err: + raise ValueError( + f"{prefix} is not a valid ordering: {err}. Example: {_ORDERING_EXAMPLE}" + ) from err + if not normalized.column_name: + raise ValueError(f"{prefix} has an empty column_name") + return normalized + raise TypeError( + f"{prefix} must be a column name, a (column_name, 'asc'|'desc') tuple, " + f"a ColumnOrdering, or a dict with 'column_name'; " + f"got {type(item).__name__}" + ) + + class FullTextQueryType(str, Enum): MATCH = "match" MATCH_PHRASE = "match_phrase" @@ -1955,22 +2051,37 @@ class LanceQueryBuilder(ABC): self._ensure_fragment_constraints_supported("explain_plan()") return self._table._explain_plan(self.to_query_object(), verbose=verbose) - def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self: + def order_by(self, ordering: _OrderingInput = None) -> Self: """ Set the ordering for the results. Parameters ---------- - ordering: Optional[List[ColumnOrdering]] - The ordering to use for the results. If None, then the default ordering - will be used. + ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]] + The ordering to use for the results. Each entry can be a column + name, a ``(column_name, "asc"|"desc")`` tuple, a + [ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a + ``column_name`` key. A bare tuple is a single direction pair, while + a list contains separate orderings, so ``("a", "desc")`` sorts by + ``a`` descending and ``["a", "desc"]`` sorts by both columns. + Pass ``None`` or an empty list to clear the ordering. Returns ------- LanceQueryBuilder The LanceQueryBuilder object. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("memory://") + >>> table = db.create_table("ordering", [{"name": "b"}, {"name": "a"}]) + >>> table.search().order_by(["name"]).to_list() + [{'name': 'a'}, {'name': 'b'}] + >>> table.search().order_by([("name", "desc")]).to_list() + [{'name': 'b'}, {'name': 'a'}] """ - self._order_by = ordering + self._order_by = _normalize_ordering(ordering) return self def analyze_plan( @@ -2930,6 +3041,29 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): # the reranker's own use, so it cannot answer "did the caller ask?". self._caller_requested_row_id = False + def order_by(self, ordering: _OrderingInput = None) -> Self: + """ + Set the ordering for the results. + + Hybrid results are fused and reranked, so ordering the two search legs + does not define the final result order. Order the returned rows after + reranking instead. + + Parameters + ---------- + ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]] + Must be ``None`` or an empty list. Any non-empty ordering raises + ``NotImplementedError``. + """ + normalized = _normalize_ordering(ordering) + if normalized: + raise NotImplementedError( + "order_by is not supported for hybrid queries; " + "sort the returned results after reranking instead." + ) + self._order_by = None + return self + def _validate_query(self, query, vector=None, text=None): if query is not None and (vector is not None or text is not None): raise ValueError( @@ -4434,20 +4568,36 @@ class AsyncStandardQuery(AsyncQueryBase): self._inner.offset(offset) return self - def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self: + def order_by(self, ordering: _OrderingInput = None) -> Self: """ Set the ordering for the results. Parameters ---------- - ordering: Optional[List[ColumnOrdering]] - The ordering to use for the results. If None, then the default ordering - will be used. + ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]] + The ordering to use for the results. Each entry can be a column + name, a ``(column_name, "asc"|"desc")`` tuple, a + [ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a + ``column_name`` key. A bare tuple is a single direction pair, while + a list contains separate orderings, so ``("a", "desc")`` sorts by + ``a`` descending and ``["a", "desc"]`` sorts by both columns. + Pass ``None`` or an empty list to clear the ordering. + + Examples + -------- + >>> import lancedb + >>> db = await lancedb.connect_async("memory://") # doctest: +SKIP + >>> table = await db.create_table( # doctest: +SKIP + ... "ordering", [{"name": "b"}, {"name": "a"}] + ... ) + >>> await table.query().order_by(["name"]).to_list() # doctest: +SKIP + [{'name': 'a'}, {'name': 'b'}] """ - if ordering is None: + normalized = _normalize_ordering(ordering) + if normalized is None: self._inner.order_by(None) else: - self._inner.order_by([o.model_dump() for o in ordering]) + self._inner.order_by([o.model_dump() for o in normalized]) return self def fast_search(self) -> Self: diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 88bed9c1f..82b40f9c6 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1042,6 +1042,113 @@ async def test_order_by_async_query(mem_db_async: AsyncConnection): ] +def test_order_by_accepts_strings_tuples_and_dicts(mem_db): + table = mem_db.create_table( + "test_order_by_forms", + pa.table( + { + "group": [1, 1, 1, 2], + "score": [None, 1.0, 1.0, 0.5], + "name": ["z", "b", "a", "c"], + } + ), + ) + + rows = ( + table.search() + .order_by( + [ + "group", + ("score", "desc"), + {"column_name": "name", "ascending": True}, + ] + ) + .select(["name"]) + .to_list() + ) + assert rows == [{"name": "a"}, {"name": "b"}, {"name": "z"}, {"name": "c"}] + + # A bare tuple is one direction pair; a list holds separate orderings. + assert table.search().order_by("name").select(["name"]).to_list() == [ + {"name": "a"}, + {"name": "b"}, + {"name": "c"}, + {"name": "z"}, + ] + assert table.search().order_by(("name", "desc")).select(["name"]).to_list() == [ + {"name": "z"}, + {"name": "c"}, + {"name": "b"}, + {"name": "a"}, + ] + assert table.search().order_by(["group", "name"]).select(["name"]).to_list() == [ + {"name": "a"}, + {"name": "b"}, + {"name": "z"}, + {"name": "c"}, + ] + + +def test_order_by_clears_with_none_and_empty_list(mem_db): + table = mem_db.create_table("test_order_by_clear", [{"name": "a"}]) + + query = table.search().order_by("name") + assert query.to_query_object().order_by is not None + assert query.order_by(None).to_query_object().order_by is None + assert query.order_by([]).to_query_object().order_by is None + + +def test_order_by_rejects_invalid_input_early(mem_db): + table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}]) + + with pytest.raises(ValueError, match="unsupported key\\(s\\)"): + table.search().order_by([{"column": "name", "ascending": True}]) + with pytest.raises(ValueError, match="missing 'column_name'"): + table.search().order_by({"ascending": True}) + with pytest.raises(ValueError, match="invalid direction"): + table.search().order_by([("name", "sideways")]) + with pytest.raises(TypeError, match="must be a column name"): + table.search().order_by([42]) + + +@pytest.mark.asyncio +async def test_order_by_async_accepts_dicts_and_clears(mem_db_async: AsyncConnection): + table = await mem_db_async.create_table( + "test_order_by_async_forms", + pa.table({"name": ["z", "b", "a", "c"]}), + ) + + rows = await ( + table.query().order_by([{"column_name": "name", "ascending": False}]).to_arrow() + ) + assert rows["name"].to_pylist() == ["z", "c", "b", "a"] + + query = table.query().order_by("name") + assert query.to_query_object().order_by is not None + assert query.order_by(None).to_query_object().order_by is None + assert query.order_by([]).to_query_object().order_by is None + + with pytest.raises(ValueError, match="unsupported key\\(s\\)"): + table.query().order_by([{"column": "name"}]) + + +def test_column_ordering_is_exported_at_top_level(): + assert lancedb.ColumnOrdering is ColumnOrdering + + +def test_order_by_hybrid_sync_is_explicitly_unsupported(table): + query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("a") + + with pytest.raises(NotImplementedError, match="order_by is not supported"): + query.order_by(["id"]) + + # Clearing is still allowed, and invalid input still fails on its own terms. + query.order_by(None) + query.order_by([]) + with pytest.raises(ValueError, match="unsupported key\\(s\\)"): + query.order_by([{"column": "id"}]) + + def test_query_builder(table): rs = ( LanceVectorQueryBuilder(table, [0, 0], "vector") From 121de72cc449e7aacf88e0f66a6a6c64018a6e19 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:26:40 +0800 Subject: [PATCH 10/18] fix(python): keep Permutation builder copies shallow (#5121) ## Summary `Permutation`'s `with_*` builders use `copy.copy`, but `Permutation` had no `__copy__`. Python therefore fell back to `__getstate__`/`__setstate__`, which calls `permutation_table.to_arrow()` (unsupported for remote tables) and rebuilds the base table and reader on every builder call. Add a targeted `__copy__` that shallow-copies the instance state. The copy keeps the existing table handles and reader and can change its own attributes without affecting the original. Pickle serialization and persist semantics are unchanged. Refs OSS-2857. The persist feature remains open. --- python/python/lancedb/permutation.py | 14 ++++++++ python/python/tests/test_permutation.py | 45 ++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index c8e6f84e0..fcdbaa397 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -788,6 +788,20 @@ class Permutation: self.reader = None self._pid = None + def __copy__(self) -> "Permutation": + """Return a shallow copy without going through the pickle path. + + The ``with_*`` builders use ``copy.copy`` to derive a new permutation. + The default copy protocol would use ``__getstate__``/``__setstate__``, + which materializes the permutation table with ``to_arrow()`` (not + supported for remote tables) and rebuilds the base table and reader. + A shallow copy instead keeps the existing table handles and reader; + the caller replaces only the attribute it is changing. + """ + new = self.__class__.__new__(self.__class__) + new.__dict__ = self.__dict__.copy() + return new + def _ensure_open(self) -> None: pid = os.getpid() if self.reader is not None and getattr(self, "_pid", None) == pid: diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 165172622..a52aa420e 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -7,7 +7,13 @@ import pytest from lancedb import DBConnection, Table, connect from lancedb.background_loop import LOOP -from lancedb.permutation import Permutation, Permutations, permutation_builder +from lancedb.permutation import ( + DEFAULT_BATCH_SIZE, + Permutation, + Permutations, + Transforms, + permutation_builder, +) from utils import ( MockPermutationServer, assert_server_safe_row_id_requests, @@ -81,6 +87,43 @@ def test_pickled_permutation_reads_pinned_version(tmp_path): assert sorted(row["idx"] for row in rows) == list(range(20)) +def test_builder_copy_is_shallow_and_does_not_materialize( + some_table: Table, some_perm_table: Table, monkeypatch +): + """The with_* builders use copy.copy, which must stay a shallow copy. + + Without ``Permutation.__copy__`` the copy falls back to the pickle path, + which materializes the permutation table with ``to_arrow()`` before + rebuilding the base table and reader. That is expensive for in-memory + tables and fails for remote permutation tables. + """ + permutation = Permutation.from_tables(some_table, some_perm_table) + + def fail_materialize(*args, **kwargs): + raise AssertionError("copy.copy must not materialize the permutation table") + + def fail_getstate(_self): + raise AssertionError("copy.copy must not pickle the permutation") + + monkeypatch.setattr(permutation.permutation_table, "to_arrow", fail_materialize) + monkeypatch.setattr(Permutation, "__getstate__", fail_getstate) + + formatted = permutation.with_format("arrow") + assert formatted is not permutation + assert formatted.transform_fn is Transforms.arrow2arrow + assert permutation.transform_fn is Transforms.arrow2python + assert formatted.base_table is permutation.base_table + assert formatted.permutation_table is permutation.permutation_table + assert formatted.reader is permutation.reader + + resized = permutation.with_batch_size(7) + assert resized.batch_size == 7 + assert permutation.batch_size == DEFAULT_BATCH_SIZE + assert resized.selection is permutation.selection + resized.selection = {"id": "id"} + assert permutation.selection is not resized.selection + + def test_split_random_counts(mem_db): """Test random splitting with absolute counts.""" tbl = mem_db.create_table( From 3c9851966cab18b4290a0e0806524e809a14b1f6 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:28:47 +0800 Subject: [PATCH 11/18] chore(python): clarify package summary and search keywords (#5124) Replace the placeholder `lancedb` PyPI summary with factual wording covering vector, full-text, and hybrid search on Lance tables. Narrow the keywords to `lance`, `vector-search`, `full-text-search`, `dataset`, and `versioning`. Metadata-only change; runtime behavior is unchanged. Refs OSS-2883 --- python/pyproject.toml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/python/pyproject.toml b/python/pyproject.toml index ff64d9772..69130e16c 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -12,17 +12,17 @@ dependencies = [ "tqdm>=4.27.0", "lance-namespace>=0.13.0" ] -description = "lancedb" +description = "Embedded database for vector, full-text and hybrid search on Lance tables" authors = [{ name = "LanceDB Devs", email = "dev@lancedb.com" }] license = { file = "LICENSE" } readme = "README.md" requires-python = ">=3.10" keywords = [ - "data-format", - "data-science", - "machine-learning", - "arrow", - "data-analytics", + "lance", + "vector-search", + "full-text-search", + "dataset", + "versioning", ] classifiers = [ "Development Status :: 3 - Alpha", From 56638a9e71d89d043d2e680e4fbf8008c42607f5 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:34:49 +0800 Subject: [PATCH 12/18] fix(python): reject Expr inputs on unregistered Function definitions (#5125) `FunctionDefinition.__call__` ran the decorated Python callable with any value it was given, so `my_function(value=col("value"))` executed user code against an `Expr` or silently returned one, with errors such as `float() argument must be a string or a real number, not 'Expr'`. A column reference is not a local value: it binds only on a registered `FunctionVersion`. An unregistered definition now rejects `Expr` positional and keyword arguments with `TypeError` before the callable runs, and names the supported path: `create_function`/`create_function_async`, then `col(...)` on the returned version. Plain Python and Arrow arguments, and the class `__init__`/`__call__` lifecycle, are unchanged. The Function authoring guide's batch example did not register either: a `pyarrow.Array` annotation carries no element types, so `score_batch` raised `TypeError` for missing `input_schema` and `output_schema`, and the page claimed one `pa.RecordBatch` parameter could read several columns. The example now passes both schemas, shows one `pa.Array` parameter per input column for multi-column functions, and states that `input_schema` matches parameters one to one, so a `RecordBatch` parameter binds one input column. The GPU class example on the same page had the same missing-schema defect and is fixed too. Compatibility: code that passed `col(...)` to an unregistered definition now gets `TypeError` instead of running user code against an `Expr`. That call was never a supported binding and produced no usable result; no supported call changes. --- docs/src/python/python.md | 4 +- docs/web/curation/create-function.mdx | 35 +++++++++++++-- python/python/lancedb/functions.py | 28 +++++++++++- .../python/tests/test_function_packaging.py | 43 +++++++++++++++++++ 4 files changed, 103 insertions(+), 7 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 122a73019..dfd2752b8 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -449,7 +449,9 @@ and then call the returned instance; call `close()` if the class defines it. Thi path uses the current Python environment and does not create a registered `FunctionVersion`, build the declared remote runtime, resolve Secrets, or execute the remote Arrow adapter. A registered `FunctionVersion` call instead binds -`col(...)` inputs and returns a remote `FunctionApplication`. +`col(...)` inputs and returns a remote `FunctionApplication`. Passing an `Expr` +such as `col("value")` to a definition raises `TypeError` before the callable +runs; bind it on the registered `FunctionVersion` instead. ```python from lancedb import function diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 0342849b4..109846bea 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -98,10 +98,12 @@ is not a substitute for `lancedb.blob`. ## 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: +A function is called once per batch instead of once per row when all of its +parameters are annotated `pyarrow.Array`. Those annotations say that a whole +column arrives in one call, but not which Arrow type the column holds, so a +batch function also passes `input_schema` and `output_schema`; every field of +`input_schema` matches a parameter by name and by order. The same doubling +logic, vectorized over a whole batch at once: ```python Python icon="python" @@ -111,6 +113,8 @@ from lancedb import function @function( pip=["numpy==2.2.0"], + input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]), + output_schema=pa.float64(), batch_size=32, max_concurrency=4, row_timeout_seconds=90, @@ -120,6 +124,27 @@ def score_batch(value: pa.Array) -> pa.Array: ``` +Read several columns in one call by taking one `pa.Array` parameter per +column, with one schema field for each: + +```python +@function( + input_schema=pa.schema([ + pa.field("value", pa.float64(), nullable=False), + pa.field("weight", pa.float64(), nullable=False), + ]), + output_schema=pa.float64(), +) +def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array: + return pc.multiply(value, weight) +``` + +A single `pyarrow.RecordBatch` parameter is also a batch function, but it does +not read several columns at once: `input_schema` declares one field per +parameter, so a `RecordBatch` parameter binds one input column and receives +that column as a batch. A schema with more fields than the callable has +parameters is rejected at decoration. + 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. @@ -185,6 +210,8 @@ gpu_class = next( gpu=True, gpu_class=gpu_class, pip=["torch==2.12.0", "sentence-transformers==5.7.0"], + input_schema=pa.schema([pa.field("text", pa.string(), nullable=True)]), + output_schema=pa.list_(pa.float32(), 384), ) class embed_text: def __init__(self, model_name: str = "all-MiniLM-L6-v2"): diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 2d369e3ec..43226fdf3 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -3182,6 +3182,12 @@ class FunctionDefinition: remote application or build the declared remote runtime, and it does not need the private implementation attribute. + Arguments to this call are Python and Arrow values. An + [Expr][lancedb.expr.Expr] argument, such as ``col("value")``, is a column + binding that only a registered + [FunctionVersion][lancedb.functions.FunctionVersion] can carry, so this + call rejects it with ``TypeError`` instead of running the callable. + Remote execution adapts the callable to the internal Arrow batch ABI described by the registration artifact. By default it invokes the callable once per row. A callable whose parameters are all annotated as @@ -3451,6 +3457,16 @@ class FunctionDefinition: return self._request._copy(update={"secret_bindings": resolved}) def __call__(self, *args, **kwargs): + from lancedb.expr import Expr + + if any(isinstance(value, Expr) for value in (*args, *kwargs.values())): + raise TypeError( + "a FunctionDefinition runs locally on Python and Arrow values; " + "an Expr input binds only on a registered FunctionVersion. " + "Register the definition with create_function or " + "create_function_async, then bind col(...) on the returned " + "version." + ) return self._function(*args, **kwargs) @@ -3541,7 +3557,12 @@ def function( it takes one ``pyarrow.RecordBatch``. These batch annotations require both ``input_schema`` and ``output_schema`` explicitly: the annotations do not specify Arrow element types or fields. This also applies to a class's - ``__call__`` method. A decorated class is the same callable with state: + ``__call__`` method. Each ``input_schema`` field names one parameter, so + several input columns take one ``pyarrow.Array`` parameter each, while a + single ``pyarrow.RecordBatch`` parameter binds one input column and + receives it as a batch. The + [Function authoring guide](https://lancedb.com/docs/curation/create-function#batch) + has the worked examples. A decorated class is the same callable with state: each remote instance calls ``__init__`` once, calls ``__call__`` for every row or batch of every input it processes, and calls ``close()``, if defined, once when it retires. Load models, open clients, @@ -3803,7 +3824,10 @@ def function( remote environment, resolve Secrets, or run the remote Arrow adapter or sandbox. A registered ``FunctionVersion`` call is different: it binds ``col(...)`` inputs and returns a remote - [FunctionApplication][lancedb.functions.FunctionApplication]. + [FunctionApplication][lancedb.functions.FunctionApplication]. Passing an + [Expr][lancedb.expr.Expr] to a definition raises ``TypeError`` before the + callable runs, because a column reference binds only on a registered + version. ```python scaled = scale(factor=2.0) diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 874dd809f..8d2d282a9 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -20,6 +20,7 @@ from typing import Annotated, Optional, get_type_hints import numpy as np import pyarrow as pa +import pyarrow.compute as pc import pytest from lancedb import col @@ -582,6 +583,48 @@ def test_array_batch_annotations_accept_explicit_schemas(): assert identity(values).equals(values) +def test_batch_functions_take_one_array_parameter_per_input_column(): + @function( + input_schema=pa.schema( + [ + pa.field("value", pa.float64(), nullable=False), + pa.field("weight", pa.float64(), nullable=False), + ] + ), + output_schema=pa.float64(), + ) + def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array: + return pc.multiply(value, weight) + + signature = weighted_score.registration_request.signature + assert [parameter.name for parameter in signature.inputs] == ["value", "weight"] + result = weighted_score(pa.array([1.0, 2.0]), pa.array([3.0, 4.0])) + assert result.to_pylist() == [3.0, 8.0] + + +@pytest.mark.parametrize( + "invoke", + [ + lambda definition: definition(col("value")), + lambda definition: definition(value=col("value")), + lambda definition: definition(value=col("value") * 2), + ], + ids=["positional", "keyword", "derived"], +) +def test_definition_calls_reject_expr_inputs_before_user_code(invoke): + @function + def double(value: float) -> float: + raise AssertionError("user code ran") + + with pytest.raises(TypeError, match="registered FunctionVersion"): + invoke(double) + + +def test_class_definition_binds_initialization_only_on_a_version(): + with pytest.raises(TypeError, match="registered FunctionVersion"): + scale(factor=col("factor"), label="x") + + @pytest.mark.parametrize("class_function", [False, True]) @pytest.mark.parametrize("postponed", [False, True]) @pytest.mark.parametrize( From f460c34bdd62e03145b8bddd1670c734829648ef Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:36:29 +0800 Subject: [PATCH 13/18] fix: pin native permutation builds to one snapshot (#5126) ## Problem `PermutationBuilder` pinned backends that returned a snapshot handle, but `NativeTable` returned `None`. A namespace-backed latest handle could count and record the local table version while its row-id scan was pushed to a server that returned newer rows. A native handle with read refresh enabled could also advance between the version read, count, and scan. The result was a permutation whose recorded version, row count, and row ids did not describe one snapshot. ## Fix - Return an independent pinned native handle from `NativeTable::snapshot_at_current_version()`, so one build's version, count, and scan share a dataset. - Report `scan_order_is_deterministic()` false when a main/latest native handle may push queries to a namespace server, whose `QueryTable` request carries no order. Local scans remain deterministic at a fixed version. Refs OSS-3109 The query `scan_in_order` API and Python dispatch remain a separate slice. --- .../src/dataloader/permutation/builder.rs | 187 +++++++++++++++++- .../src/dataloader/permutation/split.rs | 4 +- rust/lancedb/src/table.rs | 22 ++- 3 files changed, 204 insertions(+), 9 deletions(-) diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 15f8c3cd3..770a956eb 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -249,10 +249,10 @@ impl PermutationBuilder { /// Builds the permutation table and stores it in the given database. pub async fn build(mut self) -> Result { - // Remote tables resolve latest independently for each request. Use a - // separate pinned handle so count, projection, and scan all refer to one - // snapshot without changing the caller's table checkout state. Native - // tables return `None` here and retain their existing behavior. + // Remote tables resolve latest independently for each request, and a + // native handle can refresh or answer a query from a namespace server. + // Use a separate pinned handle so count, projection, and scan all refer + // to one snapshot without changing the caller's table checkout state. if let Some(snapshot) = self .base_table .base_table() @@ -396,6 +396,51 @@ mod tests { use super::*; + /// Stands in for a namespace server whose table has advanced past the local + /// dataset. A pushed-down query reads this newer row instead of the local + /// snapshot. + #[derive(Debug, Default)] + struct ServerLatestNamespace { + query_table_calls: std::sync::atomic::AtomicUsize, + latest_row_id: u64, + } + + #[async_trait::async_trait] + impl lance_namespace::LanceNamespace for ServerLatestNamespace { + fn namespace_id(&self) -> String { + "server-latest".to_string() + } + + async fn query_table( + &self, + _request: lance_namespace::models::QueryTableRequest, + ) -> lance::Result { + self.query_table_calls + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + use arrow_array::UInt64Array; + use arrow_schema::{DataType, Field, Schema}; + + let schema = Arc::new(Schema::new(vec![Field::new( + ROW_ID, + DataType::UInt64, + false, + )])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(UInt64Array::from(vec![self.latest_row_id]))], + ) + .unwrap(); + let mut body = Vec::new(); + { + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + Ok(bytes::Bytes::from(body)) + } + } + #[tokio::test] async fn test_permutation_table_only_stores_row_id_and_split_id() { let temp_dir = tempfile::tempdir().unwrap(); @@ -451,6 +496,140 @@ mod tests { // Native tables skip the canonicalizing sort; remote does not. assert!(table.base_table().scan_order_is_deterministic()); + + // A main/latest handle may answer from a namespace server, and its + // QueryTable request carries no order. The local native scan guarantee + // does not extend to that path. + let mut pushed_down = table.as_native().unwrap().clone(); + pushed_down.namespace_client = Some(Arc::new(ServerLatestNamespace::default())); + pushed_down + .pushdown_operations + .insert(crate::connection::NamespaceClientPushdownOperation::QueryTable); + let pushed_down: Arc = Arc::new(pushed_down); + let pushed_down = Table::from(pushed_down); + assert!(!pushed_down.base_table().scan_order_is_deterministic()); + } + + /// The builder must pin one native snapshot before it counts or scans. A + /// namespace-backed latest handle can otherwise count local rows, scan + /// server-latest rows, and record the local version as if they agreed. + #[tokio::test] + async fn test_native_permutation_builder_pins_namespace_pushdown() { + use std::sync::atomic::Ordering; + + use arrow_array::{cast::AsArray, types::UInt64Type}; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(10), BatchCount::from(1)); + let table = db.create_table("base_tbl", data).execute().await.unwrap(); + + let namespace = Arc::new(ServerLatestNamespace { + latest_row_id: 10, + ..Default::default() + }); + let mut native = table.as_native().unwrap().clone(); + native.namespace_client = Some(namespace.clone()); + native + .pushdown_operations + .insert(crate::connection::NamespaceClientPushdownOperation::QueryTable); + let native: Arc = Arc::new(native); + let table = Table::from(native); + + let permutation = PermutationBuilder::new(table.clone()) + .build() + .await + .unwrap(); + + assert_eq!( + namespace.query_table_calls.load(Ordering::SeqCst), + 0, + "the builder must read its pinned local snapshot, not server-latest rows" + ); + assert_eq!(permutation.count_rows(None).await.unwrap(), 10); + + let batches: Vec = permutation + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch[SRC_ROW_ID_COL] + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(ids, (0..10).collect::>()); + + let recorded = permutation + .schema() + .await + .unwrap() + .metadata + .get(BASE_VERSION_CONFIG_KEY) + .expect("permutation should record its base version") + .parse::() + .unwrap(); + assert_eq!(recorded, table.version().await.unwrap()); + } + + /// `snapshot_at_current_version` is the builder's one-snapshot hook. With + /// read refresh enabled, the caller can advance while the pin stays put. + #[tokio::test] + async fn test_native_snapshot_pins_count_scan_and_version() { + use std::time::Duration; + + use crate::connection::ConnectBuilder; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = ConnectBuilder::new(temp_dir.path().to_str().unwrap()) + .read_consistency_interval(Duration::ZERO) + .execute() + .await + .unwrap(); + let data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(10), BatchCount::from(1)); + let table = db.create_table("base_tbl", data).execute().await.unwrap(); + + let snapshot = table + .base_table() + .snapshot_at_current_version() + .await + .unwrap() + .expect("native tables should provide an independent pinned handle"); + let version = snapshot.version().await.unwrap(); + assert_eq!(snapshot.count_rows(None).await.unwrap(), 10); + + let more_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(5), BatchCount::from(1)); + table.add(more_data).execute().await.unwrap(); + assert!(table.version().await.unwrap() > version); + + assert_eq!(snapshot.version().await.unwrap(), version); + assert_eq!(snapshot.count_rows(None).await.unwrap(), 10); + let batches: Vec = Table::from(snapshot) + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 10); + assert_eq!(table.count_rows(None).await.unwrap(), 15); } #[cfg(feature = "remote")] diff --git a/rust/lancedb/src/dataloader/permutation/split.rs b/rust/lancedb/src/dataloader/permutation/split.rs index b4e5deac1..0fb7f669b 100644 --- a/rust/lancedb/src/dataloader/permutation/split.rs +++ b/rust/lancedb/src/dataloader/permutation/split.rs @@ -406,8 +406,8 @@ impl Splitter { .collect::>(); let row_ids = arrow::compute::concat(&row_id_arrays)?; // Sample against however many rows this scan actually returned, not the - // separately computed `num_rows` count checked by `validate` -- that count and - // this scan are two different queries, not pinned to one snapshot, so a + // separately computed `num_rows` count checked by `validate`. `apply` does + // not require its caller to pass a count and scan from one snapshot, so a // concurrent append or delete between them could otherwise push // `random_range` out of `row_ids`'s real bounds. let num_eligible_rows = row_ids.len() as u64; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 4d663649e..045517968 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -4172,10 +4172,18 @@ impl BaseTable for NativeTable { self } - /// Lance scans fragments in order (`Scanner::ordered` defaults to true, and we - /// never clear it), so repeated identical scans agree. + /// Lance scans fragments in order at one dataset version (`Scanner::ordered` + /// defaults to true, and we never clear it), so repeated scans of a local + /// handle agree. A main/latest handle that may push its query to a namespace + /// server does not: the QueryTable request carries no order. fn scan_order_is_deterministic(&self) -> bool { - true + let may_push_down_namespace_query = self.namespace_client.is_some() + && self + .pushdown_operations + .contains(&NamespaceClientPushdownOperation::QueryTable) + && self.dataset.current_branch().is_none() + && self.dataset.time_travel_version().is_none(); + !may_push_down_namespace_query } fn name(&self) -> &str { @@ -4217,6 +4225,14 @@ impl BaseTable for NativeTable { })) } + async fn snapshot_at_current_version(&self) -> Result>> { + // A native handle can advance between requests when read consistency + // refreshes, and a namespace-backed handle can answer a query from a + // different snapshot than the local count/version. Hand the caller an + // independent time-travel handle so one build sees one dataset. + Ok(Some(self.checkout_current().await?)) + } + async fn checkout(&self, version: u64) -> Result<()> { self.dataset.as_time_travel(version).await } From ea4f1a38cf720ba7dd9d7c7d1350f8dfca99d293 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:45:03 +0800 Subject: [PATCH 14/18] fix: keep nonempty order_by out of namespace query pushdown (#5122) ## Problem With namespace `QueryTable` pushdown enabled, a query with a nonempty `order_by` was sent to the namespace server even though the request schema has no `order_by` field. With `limit(1)` this returned the wrong top row instead of the requested ordering. ## Fix Treat a nonempty `order_by` as requiring local execution in both the Python and Rust namespace pushdown gates. `None` or an empty ordering still uses pushdown. Local execution preserves branch, version and RTE semantics; if local storage cannot be read, the query fails explicitly rather than silently dropping the ordering. ## Validation - Public Python sync `search().order_by(...).limit(1).to_arrow()` and async `query().order_by(...).limit(1).to_arrow()` against a namespace mock: returned id 1 with zero pushdown calls. - `python/tests/test_namespace.py`: 83 passed. - Rust namespace pushdown tests: 5 passed; `table::query::tests`: 21 passed. - `cargo fmt`, `cargo clippy`, and Ruff clean. Fixes [OSS-3126](https://linear.app/lancedb/issue/OSS-3126/bug-namespace-querytable-pushdown-silently-drops-order-by). --- python/python/lancedb/namespace.py | 16 ++++-- python/python/lancedb/table.py | 3 ++ python/python/tests/test_namespace.py | 37 +++++++++++++- rust/lancedb/src/connection.rs | 7 +++ rust/lancedb/src/table/query.rs | 70 +++++++++++++++++++++++++-- 5 files changed, 124 insertions(+), 9 deletions(-) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 1de49d935..735eab51e 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -509,7 +509,9 @@ class LanceNamespaceDBConnection(DBConnection): Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a + nonempty ``order_by`` execute locally and require the client to + access the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1208,7 +1210,9 @@ class AsyncLanceNamespaceDBConnection: Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a + nonempty ``order_by`` execute locally and require the client to + access the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1811,7 +1815,9 @@ def connect_namespace( Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a nonempty + ``order_by`` execute locally and require the client to access the + table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1902,7 +1908,9 @@ def connect_namespace_async( Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a nonempty + ``order_by`` execute locally and require the client to access the + table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ea9dee024..492526344 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -146,6 +146,9 @@ def _requires_local_namespace_execution(query: Query) -> bool: or query.take_row_ids is not None or query.search_effort is not None or query.approx_mode is not None + # The namespace QueryTable request has no order_by field. Pushing a + # nonempty ordering down would drop it and return the wrong top-K rows. + or bool(query.order_by) or ( query.full_text_query is not None and query.fast_search is True diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index c965618cd..937572cc0 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -29,7 +29,7 @@ from lancedb.namespace import ( LanceNamespaceDBConnection, _query_to_namespace_request, ) -from lancedb.query import FullTextSearchQuery, Query +from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query from lancedb.table import AsyncTable, LanceTable @@ -1772,6 +1772,23 @@ class TestPushdownOperations: assert request.maximum_nprobes == 0 assert request.to_dict()["maximum_nprobes"] == 0 + def test_lance_table_order_by_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = lancedb.connect(str(tmp_path / "db")) + table = db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = table._execute_query( + Query(limit=1, order_by=[ColumnOrdering(column_name="id")]) + ).read_all() + + # Pushing this query down would drop order_by and return id 3. + assert result.column("id").to_pylist() == [1] + assert namespace_client.requests == [] + @pytest.mark.asyncio class TestAsyncPushdownOperations: @@ -1834,6 +1851,24 @@ class TestAsyncPushdownOperations: assert [request.k for request in namespace_client.requests] == [_MAX_QUERY_K] assert all(r.k <= 2**31 - 1 for r in namespace_client.requests) + async def test_async_table_order_by_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = await lancedb.connect_async(str(tmp_path / "db")) + table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = await table._execute_query( + Query(limit=1, order_by=[ColumnOrdering(column_name="id")]) + ) + + # Pushing this query down would drop order_by and return id 3. + batches = await result.read_all() + assert pa.Table.from_batches(batches).column("id").to_pylist() == [1] + assert namespace_client.requests == [] + @pytest.mark.parametrize( "query_kwargs", [ diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index db6aa2ba8..d413b2b78 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -2138,6 +2138,9 @@ use std::collections::HashSet; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum NamespaceClientPushdownOperation { /// Execute queries on the namespace server via `query_table()` instead of locally. + /// + /// Queries with a nonempty `order_by` execute locally and require client access + /// to the table storage. QueryTable, /// Execute table creation on the namespace server via `create_table()` /// instead of using `declare_table` + local write. @@ -2253,6 +2256,10 @@ impl ConnectNamespaceBuilder { /// - [`NamespaceClientPushdownOperation::QueryTable`]: Execute queries via `namespace.query_table()` /// - [`NamespaceClientPushdownOperation::CreateTable`]: Execute table creation via `namespace.create_table()` /// + /// Some query options cannot be represented in the namespace request. A query + /// with a nonempty `order_by` executes locally and requires client access to + /// the table storage. + /// /// By default, no operations are pushed down (all executed locally). pub fn pushdown_operation(mut self, operation: NamespaceClientPushdownOperation) -> Self { self.pushdown_operations.insert(operation); diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 7d98dc001..6789714e1 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -120,10 +120,18 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R } fn requires_local_namespace_execution(query: &AnyQuery) -> bool { - // The namespace QueryTable request cannot represent approx_mode, search_effort or use_rte. - // For use_rte that is worse than a tuning miss: RTE read routing lives only - // in `create_plan`, so a pushed-down query would return stale base-only data. - if query.base().use_rte.is_some() || query.base().has_take() { + // The namespace QueryTable request cannot represent approx_mode, search_effort, + // use_rte or order_by. For use_rte that is worse than a tuning miss: RTE read + // routing lives only in `create_plan`, so a pushed-down query would return + // stale base-only data. A dropped order_by would return the wrong top-K rows. + if query.base().use_rte.is_some() + || query.base().has_take() + || query + .base() + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { return true; } if matches!(query, AnyQuery::Query(query) if query.fast_search && query.full_text_search.is_some()) @@ -1858,6 +1866,60 @@ mod tests { assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); } + #[tokio::test] + async fn test_execute_query_order_by_with_namespace_pushdown_runs_locally() { + use crate::connect; + use crate::query::ColumnOrdering; + use crate::table::query::execute_query; + use arrow_array::{Int32Array, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + // Insertion order differs from ascending id, so a pushed-down query that + // drops order_by would return 3 instead of the correct top-1 row 1. + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![3, 1, 2]))]).unwrap(); + + let table = conn + .create_table("test_order_by_namespace_fallback", vec![batch]) + .execute() + .await + .unwrap(); + let namespace_client = Arc::new(CountingNamespaceClient::default()); + let mut native_table = table.as_native().unwrap().clone(); + native_table.namespace_client = Some(namespace_client.clone()); + native_table + .pushdown_operations + .insert(NamespaceClientPushdownOperation::QueryTable); + + let query = AnyQuery::Query(QueryRequest { + limit: Some(1), + order_by: Some(vec![ColumnOrdering::asc_nulls_first("id".to_string())]), + ..Default::default() + }); + + let stream = execute_query(&native_table, &query, QueryExecutionOptions::default()) + .await + .unwrap(); + let batches = stream.try_collect::>().await.unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect(); + + assert_eq!(ids, vec![1]); + assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); + } + #[tokio::test] async fn test_query_snapshot_disables_namespace_pushdown() { use crate::connect; From df8bf9ea5a3eb57a884da7710247afb4d97085ae Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:47:50 +0800 Subject: [PATCH 15/18] fix: reject unsupported layout options in remote add (#5118) ## Summary `RemoteTable::add` only transmits the write mode to the remote insert endpoint, so non-default layout options in `lance_write_params` were silently ignored. This rejects them before schema lookup and before either single-request or multipart transmission. Guarded fields: - `max_rows_per_file` - `max_rows_per_group` - `max_bytes_per_file` Default `WriteParams` and `mode = Overwrite` keep their existing behavior. Other write parameters remain untouched. ## Tests - Focused remote-table regressions cover each guarded field on both single-request and multipart paths, and verify default, `Create`, `Append`, and `Overwrite` behavior. - `cargo fmt --all -- --check` - `cargo clippy --quiet --features remote -p lancedb --tests` - Targeted `cargo test --features remote -p lancedb --lib remote::table::tests::...` Refs OSS-2882. This is the P0 hotfix; the table-level persistent layout design remains tracked separately in OSS-2882 and is not closed by this PR. --- rust/lancedb/src/remote/table.rs | 131 ++++++++++++++++++++++++++++++- rust/lancedb/src/table.rs | 4 + 2 files changed, 134 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 54b7ea7b2..4c7f3a105 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -79,7 +79,7 @@ use http::{HeaderName, StatusCode}; use lance::arrow::json::{JsonDataType, JsonSchema}; use lance::dataset::refs::TagContents; use lance::dataset::scanner::DatasetRecordBatchStream; -use lance::dataset::{ColumnAlteration, NewColumnTransform, Version}; +use lance::dataset::{ColumnAlteration, NewColumnTransform, Version, WriteParams}; use lance_core::datatypes::Schema as LanceSchema; use lance_datafusion::exec::{OneShotExec, execute_plan}; use reqwest::{RequestBuilder, Response}; @@ -2647,6 +2647,44 @@ impl RemoteTable { } } +/// Reject per-write layout options that the remote insert protocol cannot carry. +/// +/// Remote inserts only transmit `mode`; file and row-group sizing is managed by +/// the server. Silently dropping these values would produce a different layout +/// than the caller requested. +fn ensure_remote_add_supports_write_params(write_params: Option<&WriteParams>) -> Result<()> { + let Some(write_params) = write_params else { + return Ok(()); + }; + let defaults = WriteParams::default(); + let unsupported: Vec<&str> = [ + ( + "max_rows_per_file", + write_params.max_rows_per_file != defaults.max_rows_per_file, + ), + ( + "max_rows_per_group", + write_params.max_rows_per_group != defaults.max_rows_per_group, + ), + ( + "max_bytes_per_file", + write_params.max_bytes_per_file != defaults.max_bytes_per_file, + ), + ] + .into_iter() + .filter_map(|(name, differs)| differs.then_some(name)) + .collect(); + if unsupported.is_empty() { + return Ok(()); + } + Err(Error::NotSupported { + message: format!( + "write_options.lance_write_params layout options are not supported when adding data to a LanceDB Enterprise table: {}; only mode=overwrite is supported", + unsupported.join(", ") + ), + }) +} + #[async_trait] impl BaseTable for RemoteTable { fn as_any(&self) -> &dyn std::any::Any { @@ -3301,6 +3339,7 @@ impl BaseTable for RemoteTable { } async fn add(&self, mut add: AddDataBuilder) -> Result { self.check_mutable().await?; + ensure_remote_add_supports_write_params(add.write_options.lance_write_params.as_ref())?; if add.allow_external_blob_outside_bases { return Err(Error::NotSupported { @@ -5460,6 +5499,96 @@ mod tests { assert!(err.to_string().contains("LanceDB Embedded")); } + #[rstest] + #[case("max_rows_per_file")] + #[case("max_rows_per_group")] + #[case("max_bytes_per_file")] + #[tokio::test] + async fn add_rejects_layout_write_params_before_any_request(#[case] field: &str) { + for write_parallelism in [None, Some(2)] { + let table = Table::new_with_handler::("my_table", |request| { + panic!("Unexpected request: {}", request.url().path()) + }); + let data = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let mut params = WriteParams::default(); + match field { + "max_rows_per_file" => params.max_rows_per_file = 50_000, + "max_rows_per_group" => params.max_rows_per_group = 100, + "max_bytes_per_file" => params.max_bytes_per_file = 64 * 1024 * 1024, + other => panic!("unexpected field: {other}"), + } + + let mut add = table.add(data).write_options(crate::table::WriteOptions { + lance_write_params: Some(params), + }); + if let Some(write_parallelism) = write_parallelism { + add = add.write_parallelism(write_parallelism); + } + + let err = add.execute().await.unwrap_err(); + assert!( + matches!(err, Error::NotSupported { .. }), + "{field}: {err:?}" + ); + let message = err.to_string(); + assert!(message.contains(field), "{field}: {message}"); + assert!( + message.contains("only mode=overwrite is supported"), + "{field}: {message}" + ); + } + } + + #[rstest] + #[case(None, false)] + #[case(Some(lance::dataset::WriteMode::Create), false)] + #[case(Some(lance::dataset::WriteMode::Append), false)] + #[case(Some(lance::dataset::WriteMode::Overwrite), true)] + #[tokio::test] + async fn add_preserves_supported_write_params( + #[case] mode: Option, + #[case] expect_overwrite: bool, + ) { + let data = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let describe_body = describe_response(&data.schema()); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_body.clone()) + .unwrap(), + "/v1/table/my_table/insert/" => { + let mode = request + .url() + .query_pairs() + .find(|(k, _)| k == "mode") + .map(|(_, v)| v.into_owned()); + assert_eq!( + mode.as_deref(), + expect_overwrite.then_some("overwrite"), + "unexpected insert mode for {mode:?}" + ); + http::Response::builder() + .status(200) + .body(r#"{"version": 9}"#.to_string()) + .unwrap() + } + path => panic!("Unexpected request path: {}", path), + }); + + let mut add = table.add(data); + if let Some(mode) = mode { + add = add.write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + mode, + ..Default::default() + }), + }); + } + + assert_eq!(add.execute().await.unwrap().version, 9); + } + #[tokio::test] async fn add_string_blob_becomes_uri_struct_without_the_local_flag() { let table_schema = Schema::new(vec![ diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 045517968..fd7358e9a 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -283,6 +283,10 @@ pub struct WriteOptions { /// /// Overlapping `OpenTableBuilder` options (e.g. [AddDataBuilder::mode]) will take /// precedence over their counterparts in `WriteOptions` (e.g. [WriteParams::mode]). + /// + /// In LanceDB Enterprise, `add` returns [`Error::NotSupported`] when + /// `max_rows_per_file`, `max_rows_per_group`, or `max_bytes_per_file` is + /// non-default, because the remote insert protocol only transmits the write mode. pub lance_write_params: Option, } From 122e5e91d738c2c8a51ec799c57808548498d6b6 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:48:37 +0800 Subject: [PATCH 16/18] fix(python): isolate tokio runtime shutdown across fork generations (#5113) ## Problem A Python process that forks while LanceDB work is in flight inherits the parent's tokio runtime and its outstanding-call count, but the worker threads that would release that count do not survive the fork. A child that exits without using LanceDB can wait for parent work and try to shut down the inherited runtime; a child that creates its own runtime can have stale guards decrement its fresh counter. ## Behavior In-flight calls are now counted per fork generation. An inherited guard only updates the counter it was created with, and `shutdown` waits only for the current generation. A runtime tagged with an older generation is removed and leaked in the child instead of being shut down or joined. The at-fork child handler still only increments the generation counter. The fork hook is installed at the start of the first top-level call, before generation accounting, closing the window where a fork between accounting and runtime initialization could leave the child sharing the parent counter. ## Validation - New fork regressions cover parent work held across fork, child exit without and with its own runtime, and an inherited guard. Each passes when run alone in a fresh process. - `cargo test --quiet --features remote -p lancedb-python --lib runtime::tests` passes 8 tests in both default parallel and serial modes. - `cargo clippy --quiet --features remote -p lancedb-python --tests --examples` and `cargo fmt --all -- --check` pass. - Rebuilt the PyO3 extension; `test_remote_connection_after_fork` and `test_inherited_remote_table_reopens_after_fork` pass. --- python/src/runtime.rs | 537 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 475 insertions(+), 62 deletions(-) diff --git a/python/src/runtime.rs b/python/src/runtime.rs index 8891e2bf2..85d536939 100644 --- a/python/src/runtime.rs +++ b/python/src/runtime.rs @@ -21,37 +21,47 @@ //! rests on three separate mechanisms, each solving one problem the others //! cannot: //! -//! **`OUTSTANDING`, not `Arc::strong_count`, decides when the runtime is -//! idle.** Early versions tried to infer "is anything still using this -//! runtime" from how many `Arc` clones existed. That signal is -//! wrong in both directions: a clone taken only for the instant a task is -//! *submitted* says nothing about whether that task has actually finished -//! running (`Runtime::shutdown_timeout` gives spawned, non-blocking tasks -//! no grace period at all -- a task "keeps running until it yields, then is -//! dropped" -- so a reclaim landing right after submission would silently -//! abandon it before it ever got to run); and a clone held for a task's -//! *whole* lifetime can end up making that task the final owner of the -//! `Runtime`, so completing it drops the `Runtime` from inside one of its -//! own worker threads, which tokio itself forbids ("cannot drop a runtime -//! in a context where blocking is not allowed") and panics. `OUTSTANDING` -//! is an explicit courtesy counter instead: every top-level `spawn`, -//! `spawn_blocking`, or `block_on` call increments it before it starts and -//! decrements it (via [`OutstandingGuard`]) when it is truly done, entirely -//! decoupled from how many `Arc` clones exist at any instant. `shutdown` -//! waits for it to reach zero before ever touching the runtime, which also -//! closes a narrower race: because the counter is incremented *before* -//! `get_runtime()` is even called, an install already in progress when -//! `shutdown` runs is never invisible to it the way an empty slot would be. -//! If the counter never reaches zero within the bound, `shutdown` stops -//! waiting and forces the retirement attempt anyway -- silently returning -//! with the runtime and its workers still fully alive would just recreate -//! the exact race this function exists to close, for any call slower than -//! the grace period. +//! **A per-generation counter, not `Arc::strong_count`, decides when the +//! runtime is idle.** Early versions tried to infer "is anything still +//! using this runtime" from how many `Arc` clones existed. That +//! signal is wrong in both directions: a clone taken only for the instant a +//! task is *submitted* says nothing about whether that task has actually +//! finished running (`Runtime::shutdown_timeout` gives spawned, non-blocking +//! tasks no grace period at all -- a task "keeps running until it yields, +//! then is dropped" -- so a reclaim landing right after submission would +//! silently abandon it before it ever got to run); and a clone held for a +//! task's *whole* lifetime can end up making that task the final owner of +//! the `Runtime`, so completing it drops the `Runtime` from inside one of +//! its own worker threads, which tokio itself forbids ("cannot drop a +//! runtime in a context where blocking is not allowed") and panics. +//! [`GenerationCalls`] is an explicit courtesy counter instead: every +//! top-level `spawn`, `spawn_blocking`, or `block_on` call increments it +//! before it starts and decrements it (via [`OutstandingGuard`]) when it is +//! truly done, entirely decoupled from how many `Arc` clones exist at any +//! instant. `shutdown` waits for the current generation's counter to reach +//! zero before ever touching the runtime, which also closes a narrower +//! race: because the counter is incremented *before* `get_runtime()` is +//! even called, an install already in progress when `shutdown` runs is +//! never invisible to it the way an empty slot would be. If the counter +//! never reaches zero within the bound, `shutdown` stops waiting and forces +//! the retirement attempt anyway -- silently returning with the runtime and +//! its workers still fully alive would just recreate the exact race this +//! function exists to close, for any call slower than the grace period. //! -//! **Tasks never hold an `Arc`.** Because `OUTSTANDING` (not -//! reference counting) is what `shutdown` waits on, a top-level task only -//! needs to carry an `OutstandingGuard` -- a token whose `Drop` is a plain -//! atomic decrement -- not a clone of the runtime itself. That is what +//! **The counter is scoped to a fork generation, not the process.** A +//! single process-wide count cannot survive `fork()`: the child inherits the +//! parent's in-flight value, but the tasks that would decrement it do not +//! run there, and a guard copied onto the forking thread would later +//! decrement the child's count even though it belongs to the parent. Every +//! [`OutstandingGuard`] therefore holds an `Arc` for the +//! generation it was created in. A stale guard can only decrement its own +//! counter, while the child's first call lazily creates a fresh counter, and +//! `shutdown` only waits on the counter matching the live generation. +//! +//! **Tasks never hold an `Arc`.** Because the generation counter +//! (not reference counting) is what `shutdown` waits on, a top-level task +//! only needs to carry an `OutstandingGuard` -- a token whose `Drop` is a +//! plain atomic decrement -- not a clone of the runtime itself. That is what //! makes it impossible for a task's completion to become the final, //! worker-thread-side drop of the `Runtime`: nothing a task holds ever //! *is* the `Runtime`. @@ -74,11 +84,18 @@ //! installed runtime was built in against the live counter on every call, //! from ordinary (non-signal) context, and treats a mismatch as "stale, //! rebuild" -- exactly the check `atfork_child` used to perform directly. +//! [`shutdown`] makes the same comparison, because a child that exits +//! without ever installing its own runtime still finds the parent's stale +//! [`Tagged`] in the slot. It removes that slot and deliberately leaks the +//! instance instead of calling `shutdown_timeout` on it: its worker threads +//! do not exist in this process, so waiting for its counter or trying to +//! join them would hang, and a leaked reference prevents any inherited +//! `Arc` clone from becoming the final owner that drops it. use std::future::Future; use std::pin::Pin; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use arc_swap::ArcSwapOption; @@ -110,12 +127,21 @@ static RUNTIME: ArcSwapOption = ArcSwapOption::const_empty(); /// access -- just one atomic add, which is all a `pthread_atfork` child /// handler is ever safe to do. static GENERATION: AtomicU64 = AtomicU64::new(0); -/// Count of top-level `spawn`/`spawn_blocking`/`block_on` calls that have -/// started but not yet finished. See the module docs for why this, and not -/// `Arc::strong_count`, is what `shutdown` waits on. -static OUTSTANDING: AtomicU64 = AtomicU64::new(0); +/// In-flight top-level calls for one fork generation. Guards hold an `Arc` +/// to this object for their whole lifetime, so one inherited across `fork()` +/// can only decrement the counter it was created against, never the child's +/// fresh one. +struct GenerationCalls { + generation: u64, + outstanding: AtomicUsize, +} +static CALLS: ArcSwapOption = ArcSwapOption::const_empty(); static ATFORK_INSTALLED: AtomicBool = AtomicBool::new(false); +#[cfg(test)] +static TEST_WORKER_THREADS: AtomicUsize = AtomicUsize::new(0); + +#[cfg(not(test))] fn create_runtime() -> runtime::Runtime { runtime::Builder::new_multi_thread() .enable_all() @@ -124,9 +150,68 @@ fn create_runtime() -> runtime::Runtime { .expect("Failed to build tokio runtime") } +#[cfg(test)] +fn create_runtime() -> runtime::Runtime { + let mut builder = runtime::Builder::new_multi_thread(); + builder.enable_all().thread_name("lancedb-tokio-worker"); + // Fork tests hold two runtimes open at once. Keeping their worker count + // small avoids turning an unrelated parallel build on the same host into + // an apparent hang when the process thread limit is close to full. + let worker_threads = TEST_WORKER_THREADS.load(Ordering::Relaxed); + if worker_threads != 0 { + builder.worker_threads(worker_threads); + } + builder.build().expect("Failed to build tokio runtime") +} + +/// Register the fork-child handler once, before any generation-scoped state +/// is created. +/// +/// The first top-level call deliberately installs the hook before it starts +/// counting itself. Otherwise a fork between taking that first counter and +/// `get_runtime()` installing the hook would leave the child sharing the +/// parent's counter with no generation change to separate them. +fn ensure_atfork_installed() { + if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) { + install_atfork(); + } +} + +/// Get the in-flight counter for the current fork generation, creating it on +/// the first top-level call after a fork. +fn current_calls() -> Arc { + ensure_atfork_installed(); + let current_gen = GENERATION.load(Ordering::SeqCst); + loop { + let existing = CALLS.load_full(); + if let Some(existing) = &existing + && existing.generation == current_gen + { + return Arc::clone(existing); + } + let candidate = Arc::new(GenerationCalls { + generation: current_gen, + outstanding: AtomicUsize::new(0), + }); + let previous = CALLS.compare_and_swap(&existing, Some(Arc::clone(&candidate))); + let won = match (&*previous, &existing) { + (None, None) => true, + (Some(prev), Some(exist)) => Arc::ptr_eq(prev, exist), + _ => false, + }; + if won { + // A stale counter is only an integer: unlike a runtime it has no + // worker threads to join, so letting the slot's old reference go + // here is safe even in a forked child. + return candidate; + } + } +} + /// Get a live, owned handle to the shared runtime, rebuilding it if the /// installed one predates the most recent `fork()`. fn get_runtime() -> Arc { + ensure_atfork_installed(); let current_gen = GENERATION.load(Ordering::SeqCst); loop { let existing = RUNTIME.load_full(); @@ -135,9 +220,6 @@ fn get_runtime() -> Arc { { return Arc::clone(existing); } - if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) { - install_atfork(); - } // Built optimistically, outside any lock: on the rare race where two // threads both find the slot empty (or stale), one candidate wins // the compare-and-swap below and the other is simply dropped here, @@ -167,23 +249,26 @@ fn get_runtime() -> Arc { } } -/// RAII token tracked by [`OUTSTANDING`]. Held for the duration of a -/// top-level `block_on` call, or moved into a top-level `spawn`/ -/// `spawn_blocking` task so it decrements only once that task's *entire* -/// body -- including anything it nested-spawns and awaits -- has run to -/// completion or been dropped without completing. -struct OutstandingGuard; +/// RAII token tracked by the current [`GenerationCalls`] counter. Held for +/// the duration of a top-level `block_on` call, or moved into a top-level +/// `spawn`/`spawn_blocking` task so it decrements only once that task's +/// *entire* body -- including anything it nested-spawns and awaits -- has run +/// to completion or been dropped without completing. +struct OutstandingGuard { + calls: Arc, +} impl OutstandingGuard { fn new() -> Self { - OUTSTANDING.fetch_add(1, Ordering::SeqCst); - Self + let calls = current_calls(); + calls.outstanding.fetch_add(1, Ordering::SeqCst); + Self { calls } } } impl Drop for OutstandingGuard { fn drop(&mut self) { - OUTSTANDING.fetch_sub(1, Ordering::SeqCst); + self.calls.outstanding.fetch_sub(1, Ordering::SeqCst); } } @@ -219,13 +304,15 @@ where /// Gracefully quiesce the shared runtime, meant to run at normal process exit. /// -/// Waits (bounded by `timeout`) for [`OUTSTANDING`] to reach zero -- i.e. -/// for every top-level call already under way to actually finish, not just -/// for `Arc::strong_count` to look low -- before ever touching the runtime. -/// If the bound elapses first, it stops waiting and attempts retirement -/// anyway: leaving the runtime and its worker threads untouched would just -/// recreate the exact race this function exists to close, for any call -/// slower than the grace period. +/// Waits (bounded by `timeout`) for the current generation's +/// [`GenerationCalls`] counter to reach zero -- i.e. for every top-level call +/// already under way in *this* process to actually finish, not just for +/// `Arc::strong_count` to look low -- before ever touching the runtime. Work +/// inherited from a parent process at `fork()` belongs to an older +/// generation and is never waited on. If the bound elapses first, it stops +/// waiting and attempts retirement anyway: leaving the runtime and its worker +/// threads untouched would just recreate the exact race this function exists +/// to close, for any call slower than the grace period. /// /// Retirement itself removes the runtime from the slot and calls /// `shutdown_timeout` rather than a bare `drop`: dropping a tokio `Runtime` @@ -238,14 +325,22 @@ where /// the slot and finishing its own call, this abandons the runtime instead /// of forcing the issue -- the same trade `atfork_child` already makes. /// +/// A runtime tagged with a generation older than the live counter was +/// inherited through `fork()` and is never retired here; see the module docs. +/// /// Neither of the two ways this can fail to cleanly retire the runtime -- /// the wait timing out, or `try_unwrap` losing that race -- has any other /// signal to report through (`shutdown_timeout` itself returns nothing), /// so both log a warning instead of failing silently. pub fn shutdown(timeout: Duration) { let deadline = Instant::now() + timeout; + let generation = GENERATION.load(Ordering::SeqCst); + let calls = CALLS.load_full(); + let calls = calls + .as_ref() + .filter(|calls| calls.generation == generation); loop { - let outstanding = OUTSTANDING.load(Ordering::SeqCst); + let outstanding = calls.map_or(0, |calls| calls.outstanding.load(Ordering::SeqCst)); if outstanding == 0 { break; } @@ -260,6 +355,18 @@ pub fn shutdown(timeout: Duration) { let Some(current) = RUNTIME.load_full() else { return; }; + if current.generation != generation { + // The child inherited the parent's installed runtime. Its worker + // threads do not exist here, so waiting on its counter or calling + // `shutdown_timeout` would wait for work that can never finish and + // join threads that can never exit. Remove the slot in ordinary + // context and deliberately leak the instance: inherited `Arc` clones + // may still be dropped in this process, and the leaked reference + // keeps a dropped clone from becoming the final owner. + RUNTIME.compare_and_swap(&Some(Arc::clone(¤t)), None); + std::mem::forget(current); + return; + } RUNTIME.compare_and_swap(&Some(Arc::clone(¤t)), None); match Arc::try_unwrap(current) { Ok(tagged) => { @@ -320,7 +427,7 @@ impl Runtime for LanceRuntime { /// awaits its `JoinHandle`. `Handle::try_current` pins that nested call /// to whatever runtime is already executing it, so only the first, /// outermost call of a chain -- one running on a thread outside any - /// runtime -- ever consults [`get_runtime`] or [`OUTSTANDING`]. + /// runtime -- ever consults [`get_runtime`] or [`OutstandingGuard`]. fn spawn(fut: F) -> Self::JoinHandle where F: Future + Send + 'static, @@ -391,14 +498,14 @@ where mod tests { use super::*; - // RUNTIME, GENERATION, OUTSTANDING, and ATFORK_INSTALLED are process-wide + // RUNTIME, CALLS, GENERATION, and ATFORK_INSTALLED are process-wide // statics, and Rust's test harness runs tests in parallel by default, // so separate test functions below would otherwise race each other // through this shared state (this reproduced in CI: one test's // in-flight task got reclaimed by a *different* test's concurrent - // `shutdown()` call, and another observed `OUTSTANDING` left non-zero - // by a still-running sibling). Every test takes this lock first so - // only one of them touches the shared runtime state at a time; a + // `shutdown()` call, and another observed the in-flight counter left + // non-zero by a still-running sibling). Every test takes this lock first + // so only one of them touches the shared runtime state at a time; a // poisoned lock (a previous test's genuine failure) is still honored // rather than cascading into every later test as an unrelated panic. static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -570,7 +677,7 @@ mod tests { use std::sync::mpsc; let _lock = lock_runtime_state_for_test(); - // Clean slate: no runtime installed, OUTSTANDING at zero. + // Clean slate: no runtime installed, no in-flight calls. shutdown(Duration::from_secs(5)); let (installer_ready_tx, installer_ready_rx) = mpsc::channel::<()>(); @@ -596,6 +703,312 @@ mod tests { // shutdown must have waited for the install to finish and then // retired it, not returned early and left it stranded. assert!(RUNTIME.load_full().is_none()); - assert_eq!(OUTSTANDING.load(Ordering::SeqCst), 0); + let calls = CALLS + .load_full() + .expect("install race left no generation counter"); + assert_eq!(calls.outstanding.load(Ordering::SeqCst), 0); + } + + /// Keep fork-test runtimes small; see [`TEST_WORKER_THREADS`]. + #[cfg(target_os = "linux")] + struct TestWorkerThreads(usize); + + #[cfg(target_os = "linux")] + impl TestWorkerThreads { + fn new(worker_threads: usize) -> Self { + Self(TEST_WORKER_THREADS.swap(worker_threads, Ordering::SeqCst)) + } + } + + #[cfg(target_os = "linux")] + impl Drop for TestWorkerThreads { + fn drop(&mut self) { + TEST_WORKER_THREADS.store(self.0, Ordering::SeqCst); + } + } + + /// Run `f` in a forked child and return the `i32` it reports, or `None` + /// if the child did not report within the bound. The child leaves with + /// `_exit` so it never runs destructors inherited from the test process. + #[cfg(target_os = "linux")] + fn run_in_forked_child(f: F) -> Option + where + F: FnOnce() -> i32, + { + let mut pipe = [0; 2]; + assert_eq!(unsafe { libc::pipe(pipe.as_mut_ptr()) }, 0, "pipe failed"); + let (read_fd, write_fd) = (pipe[0], pipe[1]); + + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + unsafe { libc::close(read_fd) }; + let result = f(); + let bytes = result.to_ne_bytes(); + let written = unsafe { libc::write(write_fd, bytes.as_ptr().cast(), bytes.len()) }; + unsafe { libc::close(write_fd) }; + unsafe { + libc::_exit(if written == bytes.len() as isize { + 0 + } else { + 1 + }) + }; + } + + unsafe { libc::close(write_fd) }; + let mut poll_fd = libc::pollfd { + fd: read_fd, + events: libc::POLLIN, + revents: 0, + }; + let ready = loop { + let ready = unsafe { libc::poll(&mut poll_fd, 1, 10_000) }; + if ready >= 0 { + break ready; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "poll failed: {error}" + ); + }; + if ready == 0 { + unsafe { libc::kill(pid, libc::SIGKILL) }; + } + + let mut result = None; + if ready == 1 { + let mut bytes = [0u8; std::mem::size_of::()]; + let read = loop { + let read = unsafe { libc::read(read_fd, bytes.as_mut_ptr().cast(), bytes.len()) }; + if read >= 0 { + break read; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "read failed: {error}" + ); + }; + if read == bytes.len() as isize { + result = Some(i32::from_ne_bytes(bytes)); + } + } + unsafe { libc::close(read_fd) }; + + let mut status = 0; + loop { + let waited = unsafe { libc::waitpid(pid, &mut status, 0) }; + if waited == pid { + break; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "waitpid failed: {error}" + ); + } + if ready == 0 { + return None; + } + assert_eq!(status, 0, "forked child did not exit successfully"); + result + } + + // The child inherits the parent's installed runtime and its outstanding + // count, but not the worker thread that would ever release that count. + // Its exit-time shutdown must therefore ignore both: waiting for parent + // work would burn the whole grace period, and retiring the inherited + // runtime would try to join worker threads that do not exist here. + #[cfg(target_os = "linux")] + #[test] + fn test_forked_child_shutdown_does_not_wait_for_parent_work() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (done_tx, done_rx) = mpsc::channel::<()>(); + drop(LanceRuntime::spawn(async move { + started_tx.send(()).unwrap(); + let _ = release_rx.await; + let _ = done_tx.send(()); + })); + started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task did not start"); + + let child_result = run_in_forked_child(|| { + // Much longer than the watchdog: if this waits for inherited + // parent work at all, the child fails to report in time instead + // of the test comparing two elapsed durations. + shutdown(Duration::from_secs(30)); + i32::from(RUNTIME.load_full().is_some()) + }); + assert_eq!( + child_result, + Some(0), + "child shutdown waited for parent work or retired the inherited runtime" + ); + + release_tx.send(()).unwrap(); + done_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task was disturbed by the forked child"); + shutdown(Duration::from_secs(5)); + } + + // A child that builds its own runtime must drain that runtime's own + // work, and only that work: the parent's held task is still outstanding + // in the inherited copy of the counter but can never finish here. + #[cfg(target_os = "linux")] + #[test] + fn test_forked_child_drains_its_own_runtime_without_waiting_for_parent_work() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (done_tx, done_rx) = mpsc::channel::<()>(); + drop(LanceRuntime::spawn(async move { + started_tx.send(()).unwrap(); + let _ = release_rx.await; + let _ = done_tx.send(()); + })); + started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task did not start"); + + let child_result = run_in_forked_child(|| { + let child_done = Arc::new(AtomicBool::new(false)); + let child_done_flag = Arc::clone(&child_done); + let (task_started_tx, task_started_rx) = mpsc::channel(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); + let (child_tx, child_rx) = mpsc::channel(); + drop(LanceRuntime::spawn(async move { + task_started_tx.send(()).unwrap(); + let _ = release_rx.await; + child_done_flag.store(true, Ordering::SeqCst); + let _ = child_tx.send(()); + })); + task_started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("child task did not start"); + + // Keep the child's own task outstanding while shutdown starts, + // then release it once the shutdown thread is about to enter. + let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel(); + let shutdown_thread = std::thread::spawn(move || { + shutdown_ready_tx.send(()).unwrap(); + shutdown(Duration::from_secs(30)); + }); + shutdown_ready_rx.recv().unwrap(); + release_tx.send(()).unwrap(); + shutdown_thread.join().unwrap(); + + let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok() + && child_done.load(Ordering::SeqCst); + let retired = RUNTIME.load_full().is_none(); + let rebuilt = block_on(async { 40 + 2 }) == 42; + shutdown(Duration::from_secs(30)); + i32::from(!(drained && retired && rebuilt)) + }); + assert_eq!( + child_result, + Some(0), + "child did not drain its own runtime or waited for parent work" + ); + + release_tx.send(()).unwrap(); + done_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task was disturbed by the forked child"); + shutdown(Duration::from_secs(5)); + } + + // A guard created before `fork()` belongs to the parent generation. If + // the child drops that inherited guard, it must decrement the counter it + // was created against, not the child's fresh counter (a naive reset in + // the child would underflow here and make shutdown wait forever). The + // second parent guard stays held across the fork without being dropped + // in the child, so this also proves the child does not wait for work + // that can only finish in the parent. + #[cfg(target_os = "linux")] + #[test] + fn test_inherited_guard_does_not_corrupt_child_generation_counter() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + // This test forks before any runtime exists, so make the hook + // initialization explicit through the same path the first top-level + // call uses; otherwise this test only works after a preceding test + // has installed the process-wide hook. + ensure_atfork_installed(); + // Stands in for a top-level call that was in progress when the + // parent forked and is dropped by the child after it starts work. + let inherited_guard = OutstandingGuard::new(); + // Stays outstanding in the parent for the whole fork, as parent work + // that no child task can ever complete. + let parent_guard = OutstandingGuard::new(); + + let child_result = run_in_forked_child(move || { + let child_done = Arc::new(AtomicBool::new(false)); + let child_done_flag = Arc::clone(&child_done); + let (task_started_tx, task_started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (child_tx, child_rx) = mpsc::channel(); + drop(LanceRuntime::spawn(async move { + task_started_tx.send(()).unwrap(); + let _ = release_rx.await; + child_done_flag.store(true, Ordering::SeqCst); + let _ = child_tx.send(()); + })); + task_started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("child task did not start"); + + // Drop the inherited guard while the child has its own task + // outstanding, so a shared or reset counter would visibly + // perturb the child's accounting. + drop(inherited_guard); + + let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel(); + let shutdown_thread = std::thread::spawn(move || { + shutdown_ready_tx.send(()).unwrap(); + shutdown(Duration::from_secs(30)); + }); + shutdown_ready_rx.recv().unwrap(); + release_tx.send(()).unwrap(); + shutdown_thread.join().unwrap(); + + let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok() + && child_done.load(Ordering::SeqCst); + let retired = RUNTIME.load_full().is_none(); + i32::from(!(drained && retired)) + }); + assert_eq!( + child_result, + Some(0), + "inherited guard corrupted the child generation counter" + ); + + drop(parent_guard); + shutdown(Duration::from_secs(5)); } } From dcded7fb70e09206cdacb63366f6acb1c7cab77b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 21:01:25 +0800 Subject: [PATCH 17/18] feat(python): default StreamingDataLoader workers to forkserver (#5112) ## Problem `StreamingDataLoader` left PyTorch's platform default in place for worker processes, which is `fork` on Linux. Forked workers inherit the parent process's native runtime and connections, which is the failure mode behind the fork-isolation work. ## Behavior When `num_workers > 0` and `multiprocessing_context` is omitted or `None`, workers now use `forkserver` when the platform provides it, otherwise `spawn`. Explicit start-method names and context objects are unchanged. With `num_workers == 0`, no context is selected, preserving PyTorch's single-process handling. Callbacks and worker state must be picklable under the selected start method, following PyTorch's DataLoader rules. Existing `StreamingDataset` serialization is sufficient for the default worker path. This does not change the explicit fork opt-in or the native client reopen path in #3851. --- docs/web/training/checkpointing.mdx | 2 + python/python/lancedb/streaming.py | 21 +++- .../python/tests/test_elastic_dataloader.py | 100 ++++++++++++++++++ 3 files changed, 122 insertions(+), 1 deletion(-) diff --git a/docs/web/training/checkpointing.mdx b/docs/web/training/checkpointing.mdx index 119601d98..99124549a 100644 --- a/docs/web/training/checkpointing.mdx +++ b/docs/web/training/checkpointing.mdx @@ -54,6 +54,8 @@ Python's built-in `torch.utils.data.DataLoader` produces a safe checkpoint when alongside every internal batch and commits it to the parent `StreamingDataset` only when that batch is returned to the trainer. The trainer receives the same collated batch it would receive from a standard `DataLoader`. +With `num_workers > 0` and `multiprocessing_context` omitted or `None`, `StreamingDataLoader` uses `forkserver` where the platform provides it and falls back to `spawn`. Callback functions and worker state must be picklable under that start method. Multi-worker scripts should keep their entry point behind the standard `if __name__ == "__main__":` guard so spawned workers can import the module safely. + ```py Python icon=Python from lancedb.streaming import StreamingDataset, StreamingDataLoader diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 810911e28..23a81c135 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -30,7 +30,7 @@ import warnings from collections import deque from concurrent.futures import ThreadPoolExecutor from copy import deepcopy -from multiprocessing import RawArray, get_context +from multiprocessing import RawArray, get_all_start_methods, get_context from typing import Any, Callable, cast, Iterator, Literal, NamedTuple, Optional, Union import pyarrow as pa @@ -60,6 +60,13 @@ DEFAULT_PREFETCH_BATCHES = 4 _UNSET = object() +def _default_worker_start_method() -> str: + """Return the worker start method used when the caller omits a context.""" + if "forkserver" in get_all_start_methods(): + return "forkserver" + return "spawn" + + class _WorkerSample(NamedTuple): data: Any dataset: "StreamingDataset" @@ -1999,6 +2006,14 @@ class StreamingDataLoader(DataLoader): because the custom iterator cannot provide the exact per-yield checkpoint snapshots required by this loader. + When ``num_workers > 0`` and ``multiprocessing_context`` is omitted or + ``None``, workers default to the ``forkserver`` start method when the + platform provides it, and to ``spawn`` otherwise. Explicit start-method + names and context objects are used unchanged. With ``num_workers == 0``, + no context is selected, leaving PyTorch's single-process behavior intact. + Callbacks and worker state must be picklable under the selected start + method, following PyTorch's DataLoader rules. + Examples -------- >>> # dataset = StreamingDataset(table, num_splits=2) @@ -2028,6 +2043,10 @@ class StreamingDataLoader(DataLoader): ) self._streaming_dataset = dataset super().__init__(_StreamingDatasetAdapter(dataset), *args, **kwargs) + # Fill the default only after DataLoader has handled an explicit context; + # num_workers=0 keeps whatever PyTorch decided. + if self.num_workers > 0 and self.multiprocessing_context is None: + self.multiprocessing_context = _default_worker_start_method() if self.drop_last: raise ValueError( "StreamingDataLoader does not support drop_last=True because " diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index e9fb56c8a..6e6ab45d1 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -32,6 +32,7 @@ Parameters used throughout: import dataclasses import logging +import multiprocessing as mp import threading from unittest.mock import patch @@ -1028,6 +1029,105 @@ def test_multi_worker_elastic_det_across_worker_counts(lance_table): ) +# ── Worker start method defaults ───────────────────────────────────────────── + + +def _loader_start_method(loader: StreamingDataLoader) -> str: + context = loader.multiprocessing_context + if isinstance(context, str): + return context + assert context is not None + return context.get_start_method() + + +def _platform_worker_start_method() -> str: + return "forkserver" if "forkserver" in mp.get_all_start_methods() else "spawn" + + +def test_default_worker_start_method_prefers_forkserver(): + with patch.object( + streaming, + "get_all_start_methods", + return_value=["fork", "spawn", "forkserver"], + ): + assert streaming._default_worker_start_method() == "forkserver" + + +def test_streaming_dataloader_falls_back_to_spawn_without_forkserver(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + with patch.object(streaming, "get_all_start_methods", return_value=["spawn"]): + loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1) + + assert _loader_start_method(loader) == "spawn" + + +def test_streaming_dataloader_omitted_context_uses_platform_method(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1) + + assert _loader_start_method(loader) == _platform_worker_start_method() + + +def test_streaming_dataloader_treats_none_context_as_omitted(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=1, + multiprocessing_context=None, + ) + + assert _loader_start_method(loader) == _platform_worker_start_method() + + +def test_streaming_dataloader_preserves_explicit_start_method(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=1, + multiprocessing_context="spawn", + ) + + assert _loader_start_method(loader) == "spawn" + + +def test_streaming_dataloader_preserves_explicit_context_object(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + context = mp.get_context("spawn") + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=1, + multiprocessing_context=context, + ) + + assert loader.multiprocessing_context is context + + +def test_streaming_dataloader_zero_workers_leave_context_unset(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=12, num_workers=0) + + assert loader.multiprocessing_context is None + ids = [row_id for batch in loader for row_id in batch["id"].tolist()] + assert sorted(ids) == list(range(NUM_ROWS)) + + +def test_streaming_dataloader_default_context_runs_real_worker(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=12, num_workers=1) + assert _loader_start_method(loader) == _platform_worker_start_method() + + iterator = iter(loader) + try: + ids = [row_id for batch in iterator for row_id in batch["id"].tolist()] + finally: + iterator._shutdown_workers() + + assert sorted(ids) == list(range(NUM_ROWS)) + + # ── Resumability with num_workers ───────────────────────────────────────────── From 97996869864ff3c9b59a87532881f498a31f329b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 21:30:40 +0800 Subject: [PATCH 18/18] perf(python): add native eager collection for to_arrow (#5127) ## Summary `to_arrow()` currently collects results one Python future per batch: both sync and async paths call `to_batches()`, which crosses the Python/Rust bridge for every default 1024-row batch. Vector queries also materialize the whole native stream even when no reranker is configured. This adds a shared Rust eager collector. `execute_to_reader` collects the batches in Rust, asks the core to skip the default 1024-row output slicing, and exposes the result through the Arrow C Stream interface, so Python builds the Table without a Python future per batch. Sync and async `to_arrow`, including FTS, vector and hybrid eager paths, use it. `AsyncVectorQuery.to_batches` no longer materializes results when there is no reranker and now honors `max_batch_length`. Schema, empty results, timeout, cancellation, and error behavior are preserved. The existing fragment guard is enforced on the new fast path, and namespace-pushdown routing keeps its existing Python/Rust split. ## Benchmark Development-profile editable build, full scans on one revision, 1 warmup + 5 measured runs. Absolute values are not release-profile numbers; compare before/after on the same build. | Workload | Before | After | |---|---|---| | 5M rows x 3 columns, async | 3.054 s | 0.087 s (35.1x) | | 5M rows x 3 columns, sync | 3.462 s | 0.090 s (38.3x) | | 200k rows x 129 columns, async | 0.354 s | 0.082 s (4.3x) | | 200k rows x 129 columns, sync | 0.387 s | 0.085 s (4.5x) | The narrow scan returned 4,883 batches capped at 1,024 rows before and 611 batches up to 8,192 rows after. --- python/python/lancedb/_lancedb.pyi | 12 +++ python/python/lancedb/query.py | 107 ++++++++++++++++++-- python/python/lancedb/remote/table.py | 8 ++ python/python/lancedb/table.py | 47 +++++++++ python/python/tests/test_eager_collector.py | 57 +++++++++++ python/python/tests/test_fts.py | 6 +- python/python/tests/test_query.py | 3 +- python/src/arrow.rs | 45 +++++++- python/src/query.rs | 64 ++++++++++++ 9 files changed, 333 insertions(+), 16 deletions(-) create mode 100644 python/python/tests/test_eager_collector.py diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5a89f100b..962000c99 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -962,6 +962,9 @@ class Query: async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -974,6 +977,9 @@ class TakeQuery: def use_rte(self, enable: bool): ... async def output_schema(self) -> pa.Schema: ... async def execute(self) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1000,6 +1006,9 @@ class FTSQuery: async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1009,6 +1018,9 @@ class FTSQuery: class VectorQuery: async def output_schema(self) -> pa.Schema: ... async def execute(self) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... def where(self, filter: str): ... def where_expr(self, expr: PyExpr): ... def select(self, columns: List[Tuple[str, str]]): ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 76d98e4f6..ce75dd68c 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -2567,10 +2567,24 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): columns and raises for blobs inside lists. """ blob_sources = self._validated_blob_sources(blob_mode) + if blob_mode != "lazy": + return self._finalize_blob_query_table( + self.to_batches(timeout=timeout).read_all(), + blob_mode=blob_mode, + blob_sources=blob_sources, + ) + + self._ensure_fragment_constraints_supported("to_arrow()") + results = self._table._execute_arrow( + self._query_for_scan(blob_sources), timeout=timeout + ) + if self._reranker is not None: + source = results + results = self._reranker.rerank_vector(self._str_query, results) + check_reranker_result(results) + results = _merge_query_snapshot(results, source) return self._finalize_blob_query_table( - self.to_batches(timeout=timeout).read_all(), - blob_mode=blob_mode, - blob_sources=blob_sources, + results, blob_mode=blob_mode, blob_sources=blob_sources ) def to_query_object(self) -> Query: @@ -2895,8 +2909,12 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): blob_sources = self._validated_blob_sources(blob_mode) self._table._ensure_no_legacy_fts_index() + self._ensure_fragment_constraints_supported("to_arrow()") query = self._query_for_scan(blob_sources) - results = self._table._execute_query(query, timeout=timeout).read_all() + if blob_mode == "lazy": + results = self._table._execute_arrow(query, timeout=timeout) + else: + results = self._table._execute_query(query, timeout=timeout).read_all() if self._reranker is not None: source = results results = self._reranker.rerank_fts(self._query, results) @@ -2945,8 +2963,18 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): blob_sources = self._validated_blob_sources(blob_mode) if blob_mode == "bytes" and blob_sources: return self.to_batches(timeout=timeout, blob_mode=blob_mode).read_all() + if blob_mode != "lazy": + return self._finalize_blob_query_table( + self.to_batches(timeout=timeout).read_all(), + blob_mode=blob_mode, + blob_sources=blob_sources, + ) + + self._ensure_fragment_constraints_supported("to_arrow()") return self._finalize_blob_query_table( - self.to_batches(timeout=timeout).read_all(), + self._table._execute_arrow( + self._query_for_scan(blob_sources), timeout=timeout + ), blob_mode=blob_mode, blob_sources=blob_sources, ) @@ -4062,6 +4090,17 @@ class AsyncQueryBase(object): return AsyncRecordBatchReader._from_batches(schema, batches()) + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + """Execute with the native eager collector used by ``to_arrow``.""" + self._ensure_fragment_constraints_supported("to_arrow()") + await self._maybe_add_blob_row_id() + reader = await self._inner.execute_to_reader(None, timeout) + return pa.Table.from_batches(reader, schema=reader.schema) + async def _execute_batches( self, *, @@ -4187,10 +4226,17 @@ class AsyncQueryBase(object): if blob_mode == "bytes" and blob_sources: reader = await self.to_batches(timeout=timeout, blob_mode=blob_mode) return pa.Table.from_batches(await reader.read_all(), schema=reader.schema) - batch_iter = await self.to_batches(timeout=timeout) - tbl = self._finalize_blob_query_table( - pa.Table.from_batches(await batch_iter.read_all(), schema=batch_iter.schema) - ) + if blob_mode != "lazy": + batch_iter = await self.to_batches(timeout=timeout) + tbl = self._finalize_blob_query_table( + pa.Table.from_batches( + await batch_iter.read_all(), schema=batch_iter.schema + ) + ) + else: + tbl = self._finalize_blob_query_table( + await self._execute_eager(timeout=timeout) + ) return await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources) async def to_list( @@ -4936,6 +4982,22 @@ class AsyncFTSQuery(AsyncStandardQuery): ) ) + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + try: + results = await super()._execute_eager(timeout=timeout) + except Exception as error: + _add_fts_position_error_note(error) + raise + if self._reranker: + source = results + results = self._reranker.rerank_fts(self.get_query(), results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, @@ -5286,6 +5348,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table) ) + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + results = await super()._execute_eager(timeout=timeout) + if self._reranker: + source = results + results = self._reranker.rerank_vector(self._query_string, results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, @@ -5294,8 +5368,12 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: reader = await super()._execute_batches( - timeout=timeout, blob_sources=blob_sources + max_batch_length=max_batch_length, + timeout=timeout, + blob_sources=blob_sources, ) + if self._reranker is None: + return reader results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: source = results @@ -5421,6 +5499,15 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): return fts_query, vec_query, limit, offset + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + self._ensure_fragment_constraints_supported("to_arrow()") + reader = await self._execute_batches(timeout=timeout) + return pa.Table.from_batches(await reader.read_all(), schema=reader.schema) + async def _execute_batches( self, *, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 51a656a52..47d0d048f 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -927,6 +927,14 @@ class RemoteTable(Table): return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync()) + def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + return LOOP.run(self._table._execute_arrow(query, timeout=timeout)) + def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: return LOOP.run(self._table._explain_plan(query, verbose)) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 492526344..863671bd5 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2926,6 +2926,15 @@ class Table(ABC): timeout: Optional[timedelta] = None, ) -> pa.RecordBatchReader: ... + def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + """Execute a query and collect the whole result eagerly.""" + return self._execute_query(query, timeout=timeout).read_all() + @abstractmethod def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: ... @@ -5968,6 +5977,26 @@ class LanceTable(Table): return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync()) + def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + # Keep the Python namespace pushdown path, including its branch rule. + if ( + _should_push_down_query_table( + self._namespace_client, self._pushdown_operations + ) + and not self._route_pushdown_to_rust + and self.current_branch() is None + and not _requires_local_namespace_execution(query) + ): + return self._execute_query(query, timeout=timeout).read_all() + + async_query = self._table._sync_query_to_async(query) + return LOOP.run(async_query._execute_eager(timeout=timeout)) + def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: return LOOP.run(self._table._explain_plan(query, verbose)) @@ -8485,6 +8514,24 @@ class AsyncTable: max_batch_length=batch_size, timeout=timeout ) + async def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + if ( + _should_push_down_query_table( + self._namespace_client, self._pushdown_operations + ) + and not self._route_pushdown_to_rust + and not _requires_local_namespace_execution(query) + ): + return (await self._execute_query(query, timeout=timeout)).read_all() + + async_query = self._sync_query_to_async(query) + return await async_query._execute_eager(timeout=timeout) + async def _explain_plan(self, query: Query, verbose: Optional[bool]) -> str: # This method is used by the sync table async_query = self._sync_query_to_async(query) diff --git a/python/python/tests/test_eager_collector.py b/python/python/tests/test_eager_collector.py new file mode 100644 index 000000000..1eaed9678 --- /dev/null +++ b/python/python/tests/test_eager_collector.py @@ -0,0 +1,57 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import timedelta + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +async def test_execute_to_reader_collects_without_default_slicing(tmp_path): + db = await lancedb.connect_async(tmp_path) + rows = 5000 + data = pa.table( + { + "id": pa.array(range(rows), type=pa.int64()), + "text": pa.array([f"row-{i}" for i in range(rows)]), + } + ) + table = await db.create_table("test", data) + + reader = await table._inner.query().execute_to_reader(None, None) + batches = list(reader) + + assert sum(batch.num_rows for batch in batches) == rows + assert max(batch.num_rows for batch in batches) > 1024 + + +@pytest.mark.asyncio +async def test_execute_to_reader_preserves_empty_schema(tmp_path): + db = await lancedb.connect_async(tmp_path) + data = pa.table( + { + "id": pa.array([1, 2], type=pa.int64()), + "text": pa.array(["a", "b"]), + } + ) + table = await db.create_table("test", data) + + query = table._inner.query() + query.where("id < 0") + reader = await query.execute_to_reader(None, None) + result = pa.Table.from_batches(reader, schema=reader.schema) + + assert result.num_rows == 0 + assert result.schema == await table.query().where("id < 0").output_schema() + + +@pytest.mark.asyncio +async def test_execute_to_reader_propagates_timeout(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", data=[{"id": 1}, {"id": 2}]) + + with pytest.raises(Exception, match="Query timeout"): + await table._inner.query().execute_to_reader(None, timedelta(0)) diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index 26ce5e528..1bf019fc2 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -1655,7 +1655,9 @@ def test_fts_phrase_query_is_preserved_in_query_object(): def test_fts_phrase_query_execution_preserves_user_text(): table = mock.Mock() table.schema = pa.schema([]) - table._execute_query.return_value = pa.table({"text": ["result"]}).to_reader() + # to_arrow() collects through the eager path; keep a real Table so the + # reranker still receives and returns the real result contract. + table._execute_arrow.return_value = pa.table({"text": ["result"]}) class CapturingReranker: score = "relevance" @@ -1677,7 +1679,7 @@ def test_fts_phrase_query_execution_preserves_user_text(): query.to_arrow() - backend_query = table._execute_query.call_args.args[0] + backend_query = table._execute_arrow.call_args.args[0] assert ( backend_query.full_text_query.query, reranker.queries, diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 82b40f9c6..3b0f3d5a2 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1739,7 +1739,7 @@ def test_query_builder_with_different_vector_column(): ds = mock.Mock() table.to_lance.return_value = ds builder.to_arrow() - table._execute_query.assert_called_once_with( + table._execute_arrow.assert_called_once_with( Query( vector=query, filter="b < 10", @@ -1748,7 +1748,6 @@ def test_query_builder_with_different_vector_column(): columns=["b"], vector_column="foo_vector", ), - batch_size=None, timeout=None, ) diff --git a/python/src/arrow.rs b/python/src/arrow.rs index f0b4bceed..0384f2b2a 100644 --- a/python/src/arrow.rs +++ b/python/src/arrow.rs @@ -2,15 +2,20 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::sync::Arc; +use std::time::Duration; use crate::error::PythonErrorExt; use crate::runtime::future_into_py; use arrow::{ datatypes::SchemaRef, pyarrow::{IntoPyArrow, ToPyArrow}, + record_batch::{RecordBatchIterator, RecordBatchReader as ArrowRecordBatchReader}, +}; +use futures::{TryStreamExt, stream::StreamExt}; +use lancedb::{ + arrow::SendableRecordBatchStream, + query::{ExecutableQuery, QueryExecutionOptions}, }; -use futures::stream::StreamExt; -use lancedb::arrow::SendableRecordBatchStream; use pyo3::{ Bound, Py, PyAny, PyRef, PyResult, Python, exceptions::PyStopAsyncIteration, pyclass, pymethods, }; @@ -63,3 +68,39 @@ impl RecordBatchStream { }) } } + +/// Execute `query` and collect every batch in Rust before returning to Python. +/// +/// `to_arrow()` needs the complete table, so the default 1024-row output +/// slicing only adds work. Returning an Arrow C Stream reader also avoids a +/// Python future per batch while python materializes the table. +/// +/// The stream is collected inside the returned future, so timeout and +/// cancellation keep the same observable behavior as reading the stream from +/// Python: errors surface from the awaited call and dropping the future drops +/// the underlying stream. +pub fn execute_to_reader( + py: Python<'_>, + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + future_into_py(py, async move { + let mut options = QueryExecutionOptions::default(); + // `None` means the caller wants one eager result, not the core's + // default batch size. An explicit value is still honored. + options.max_batch_length = max_batch_length.unwrap_or(0); + options.timeout = timeout; + let stream = query.execute_with_options(options).await.infer_error()?; + let schema = stream.schema(); + let batches = stream.try_collect::>().await.infer_error()?; + let reader: Box = Box::new(RecordBatchIterator::new( + batches.into_iter().map(Ok), + schema, + )); + Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) + }) +} diff --git a/python/src/query.rs b/python/src/query.rs index 9864d7d74..3c6d9d662 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -696,6 +696,20 @@ impl Query { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -784,6 +798,20 @@ impl TakeQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -909,6 +937,28 @@ impl FTSQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader( + self_.py(), + self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()), + max_batch_length, + timeout, + ) + } + pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult> { let mut inner = self_ .inner @@ -1148,6 +1198,20 @@ impl VectorQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move {