mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge main into gatekeeper/fix-5025-1
This commit is contained in:
+120
-45
@@ -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:
|
||||
- "*"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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: |
|
||||
|
||||
@@ -16,14 +16,14 @@ on:
|
||||
default: ""
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
actions: read
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
update:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# Pushes the branch with the checkout token. PR creation uses ROBOT_TOKEN.
|
||||
contents: write
|
||||
steps:
|
||||
- name: Show inputs
|
||||
run: |
|
||||
@@ -44,7 +44,7 @@ jobs:
|
||||
run: npm install -g @openai/codex
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
with:
|
||||
toolchain: stable
|
||||
components: clippy, rustfmt
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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: |
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -4,9 +4,7 @@ env:
|
||||
MACOSX_DEPLOYMENT_TARGET: '10.13'
|
||||
CARGO_INCREMENTAL: '0'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
permissions: {}
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -33,6 +31,8 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
build-lancedb:
|
||||
permissions:
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -167,7 +167,7 @@ jobs:
|
||||
# Cargo also checks out Lance test fixtures below its git cache path.
|
||||
run: git config --global core.longpaths true
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
||||
with:
|
||||
version: 11.1.1
|
||||
- name: Setup node
|
||||
@@ -178,7 +178,7 @@ jobs:
|
||||
cache: pnpm
|
||||
cache-dependency-path: nodejs/pnpm-lock.yaml
|
||||
- name: Install
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
if: ${{ !matrix.settings.docker }}
|
||||
with:
|
||||
toolchain: stable
|
||||
@@ -194,7 +194,7 @@ jobs:
|
||||
# re-runs regardless, since the local crate changes every time, so the
|
||||
# win is larger on the non-LTO jobs than here.
|
||||
- name: Cache cargo (native builds)
|
||||
uses: Swatinem/rust-cache@v2
|
||||
uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
if: ${{ !matrix.settings.docker }}
|
||||
with:
|
||||
# The release profile and per-target dirs differ from what the test
|
||||
@@ -216,7 +216,7 @@ jobs:
|
||||
# that built these artifacts -- safe, since cargo fingerprints the real
|
||||
# one; a base-image bump just costs one cold build.
|
||||
- name: Cache cargo (docker builds)
|
||||
uses: Swatinem/rust-cache@v2
|
||||
uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
if: ${{ matrix.settings.docker }}
|
||||
with:
|
||||
key: docker-${{ matrix.settings.target }}
|
||||
@@ -225,17 +225,17 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Install Zig
|
||||
uses: mlugg/setup-zig@v2
|
||||
uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1
|
||||
if: ${{ contains(matrix.settings.target, 'musl') }}
|
||||
with:
|
||||
version: 0.14.1
|
||||
- name: Install cargo-zigbuild
|
||||
uses: taiki-e/install-action@v2
|
||||
uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3
|
||||
if: ${{ contains(matrix.settings.target, 'musl') }}
|
||||
with:
|
||||
tool: cargo-zigbuild
|
||||
- name: Build in docker
|
||||
uses: addnab/docker-run-action@v3
|
||||
uses: addnab/docker-run-action@4f65fabd2431ebc8d299f8e5a018d79a769ae185 # v3
|
||||
if: ${{ matrix.settings.docker }}
|
||||
with:
|
||||
image: ${{ matrix.settings.docker }}
|
||||
@@ -326,6 +326,8 @@ jobs:
|
||||
nodejs/dist/*
|
||||
!nodejs/dist/*.node
|
||||
test-lancedb:
|
||||
permissions:
|
||||
contents: read
|
||||
name: "Test: ${{ matrix.settings.target }} - node@${{ matrix.node }}"
|
||||
needs:
|
||||
- build-lancedb
|
||||
@@ -352,7 +354,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
||||
with:
|
||||
version: 11.1.1
|
||||
- name: Setup Node.js 24 for install
|
||||
@@ -394,6 +396,10 @@ jobs:
|
||||
run: node_modules/.bin/jest --verbose
|
||||
publish:
|
||||
name: Publish
|
||||
permissions:
|
||||
contents: read
|
||||
# npm provenance
|
||||
id-token: write
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
@@ -404,7 +410,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
||||
with:
|
||||
version: 11.1.1
|
||||
- name: Setup node
|
||||
|
||||
@@ -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/<repo>:<ref>` 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:
|
||||
|
||||
@@ -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
|
||||
|
||||
+16
-16
@@ -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
|
||||
|
||||
+6
-23
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -793,6 +795,8 @@ of raw SQL strings with [where][lancedb.query.LanceQueryBuilder.where] and
|
||||
|
||||
::: lancedb.query.Query
|
||||
|
||||
::: lancedb.query.ColumnOrdering
|
||||
|
||||
::: lancedb.query.LanceQueryBuilder
|
||||
|
||||
::: lancedb.query.LanceVectorQueryBuilder
|
||||
|
||||
+467
-405
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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:
|
||||
|
||||
<CodeGroup>
|
||||
```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:
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
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"):
|
||||
|
||||
@@ -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.
|
||||
|
||||
<CodeGroup>
|
||||
```py Python icon=Python
|
||||
from lancedb.streaming import StreamingDataset, StreamingDataLoader
|
||||
|
||||
@@ -217,12 +217,23 @@ dataloader = torch.utils.data.DataLoader(
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
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:
|
||||
|
||||
<CodeGroup>
|
||||
```py Python icon=Python
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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]]): ...
|
||||
@@ -1280,7 +1292,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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -584,7 +586,7 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
"storage_options": self.storage_options or None,
|
||||
"read_consistency_interval_seconds": (
|
||||
self.read_consistency_interval.total_seconds()
|
||||
if self.read_consistency_interval
|
||||
if self.read_consistency_interval is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
@@ -668,6 +670,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 +709,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 +1136,7 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
self,
|
||||
name,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
location=table_uri,
|
||||
namespace_client=namespace_client,
|
||||
managed_versioning=managed_versioning,
|
||||
@@ -1205,7 +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.
|
||||
|
||||
@@ -1808,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.
|
||||
|
||||
@@ -1899,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.
|
||||
|
||||
|
||||
@@ -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"])
|
||||
@@ -779,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:
|
||||
|
||||
+429
-57
@@ -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
|
||||
@@ -571,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"
|
||||
@@ -1686,11 +1800,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 +1948,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,24 +2048,40 @@ class LanceQueryBuilder(ABC):
|
||||
-------
|
||||
plan : str
|
||||
""" # noqa: E501
|
||||
self._ensure_fragment_constraints_supported("explain_plan()")
|
||||
return self._table._explain_plan(self.to_query_object(), verbose=verbose)
|
||||
|
||||
def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self:
|
||||
def order_by(self, ordering: _OrderingInput = None) -> Self:
|
||||
"""
|
||||
Set the ordering for the results.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ordering: Optional[List[ColumnOrdering]]
|
||||
The ordering to use for the results. If None, then the default ordering
|
||||
will be used.
|
||||
ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]]
|
||||
The ordering to use for the results. Each entry can be a column
|
||||
name, a ``(column_name, "asc"|"desc")`` tuple, a
|
||||
[ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a
|
||||
``column_name`` key. A bare tuple is a single direction pair, while
|
||||
a list contains separate orderings, so ``("a", "desc")`` sorts by
|
||||
``a`` descending and ``["a", "desc"]`` sorts by both columns.
|
||||
Pass ``None`` or an empty list to clear the ordering.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceQueryBuilder
|
||||
The LanceQueryBuilder object.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import lancedb
|
||||
>>> db = lancedb.connect("memory://")
|
||||
>>> table = db.create_table("ordering", [{"name": "b"}, {"name": "a"}])
|
||||
>>> table.search().order_by(["name"]).to_list()
|
||||
[{'name': 'a'}, {'name': 'b'}]
|
||||
>>> table.search().order_by([("name", "desc")]).to_list()
|
||||
[{'name': 'b'}, {'name': 'a'}]
|
||||
"""
|
||||
self._order_by = ordering
|
||||
self._order_by = _normalize_ordering(ordering)
|
||||
return self
|
||||
|
||||
def analyze_plan(
|
||||
@@ -1961,6 +2138,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
|
||||
)
|
||||
@@ -2389,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:
|
||||
@@ -2629,6 +2821,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)
|
||||
@@ -2716,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)
|
||||
@@ -2766,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,
|
||||
)
|
||||
@@ -2862,6 +3069,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(
|
||||
@@ -3522,6 +3752,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 +3871,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 +3994,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
|
||||
@@ -3831,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,
|
||||
*,
|
||||
@@ -3838,6 +4108,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()
|
||||
@@ -3955,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(
|
||||
@@ -4245,6 +4523,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 +4541,7 @@ class AsyncQueryBase(object):
|
||||
-------
|
||||
plan : str
|
||||
"""
|
||||
self._ensure_fragment_constraints_supported("analyze_plan()")
|
||||
return await self._inner.analyze_plan(distributed_metrics)
|
||||
|
||||
|
||||
@@ -4334,20 +4614,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:
|
||||
@@ -4501,11 +4797,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 +4847,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 +4883,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,12 +4969,34 @@ class AsyncFTSQuery(AsyncStandardQuery):
|
||||
new_self = self._inner.nearest_to(query_vectors[0])
|
||||
for v in query_vectors[1:]:
|
||||
new_self.add_query_vector(v)
|
||||
return AsyncHybridQuery(new_self, self._table)
|
||||
else:
|
||||
return AsyncHybridQuery(
|
||||
self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)),
|
||||
self._table,
|
||||
return self._inherit_fragment_constraints(
|
||||
AsyncHybridQuery(new_self, self._table)
|
||||
)
|
||||
else:
|
||||
return self._inherit_fragment_constraints(
|
||||
AsyncHybridQuery(
|
||||
self._inner.nearest_to(
|
||||
AsyncQuery._query_vec_to_array(query_vector)
|
||||
),
|
||||
self._table,
|
||||
)
|
||||
)
|
||||
|
||||
async def _execute_eager(
|
||||
self,
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
try:
|
||||
results = await super()._execute_eager(timeout=timeout)
|
||||
except Exception as error:
|
||||
_add_fts_position_error_note(error)
|
||||
raise
|
||||
if self._reranker:
|
||||
source = results
|
||||
results = self._reranker.rerank_fts(self.get_query(), results)
|
||||
results = _merge_query_snapshot(results, source)
|
||||
return results
|
||||
|
||||
async def _execute_batches(
|
||||
self,
|
||||
@@ -5002,17 +5331,35 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
columns = []
|
||||
|
||||
if isinstance(query, str):
|
||||
return AsyncHybridQuery(
|
||||
self._inner.nearest_to_text(
|
||||
{"query": query, "columns": columns, "operator": fts_query.operator}
|
||||
),
|
||||
self._table,
|
||||
return self._inherit_fragment_constraints(
|
||||
AsyncHybridQuery(
|
||||
self._inner.nearest_to_text(
|
||||
{
|
||||
"query": query,
|
||||
"columns": columns,
|
||||
"operator": fts_query.operator,
|
||||
}
|
||||
),
|
||||
self._table,
|
||||
)
|
||||
)
|
||||
# FullTextQuery object
|
||||
return AsyncHybridQuery(
|
||||
self._inner.nearest_to_text({"query": query}), self._table
|
||||
return self._inherit_fragment_constraints(
|
||||
AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table)
|
||||
)
|
||||
|
||||
async def _execute_eager(
|
||||
self,
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
results = await super()._execute_eager(timeout=timeout)
|
||||
if self._reranker:
|
||||
source = results
|
||||
results = self._reranker.rerank_vector(self._query_string, results)
|
||||
results = _merge_query_snapshot(results, source)
|
||||
return results
|
||||
|
||||
async def _execute_batches(
|
||||
self,
|
||||
*,
|
||||
@@ -5021,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
|
||||
@@ -5098,6 +5449,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)
|
||||
|
||||
@@ -5147,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,
|
||||
*,
|
||||
@@ -5394,15 +5755,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
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -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 "
|
||||
|
||||
@@ -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
|
||||
@@ -299,7 +302,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,
|
||||
@@ -2923,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: ...
|
||||
|
||||
@@ -4191,7 +4203,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 +4233,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 +4619,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 +4674,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 +4684,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 +4734,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 +5825,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 +5855,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 +5872,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:
|
||||
@@ -5798,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))
|
||||
|
||||
@@ -8315,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)
|
||||
|
||||
@@ -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"
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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))
|
||||
@@ -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 ─────────────────────────────────────────────
|
||||
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
import tempfile
|
||||
import shutil
|
||||
import importlib
|
||||
import asyncio
|
||||
import pickle
|
||||
import warnings
|
||||
import http.server
|
||||
import json
|
||||
@@ -16,6 +18,7 @@ import copy
|
||||
import pyarrow as pa
|
||||
import lancedb
|
||||
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
|
||||
from lance_namespace import DescribeTableResponse
|
||||
from utils import start_server_thread
|
||||
from lancedb.listing import AsyncListing, Listing
|
||||
from lancedb.index import FTS
|
||||
@@ -26,7 +29,7 @@ from lancedb.namespace import (
|
||||
LanceNamespaceDBConnection,
|
||||
_query_to_namespace_request,
|
||||
)
|
||||
from lancedb.query import FullTextSearchQuery, Query
|
||||
from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query
|
||||
from lancedb.table import AsyncTable, LanceTable
|
||||
|
||||
|
||||
@@ -35,6 +38,37 @@ PUSHDOWN_DATA = pa.table(
|
||||
)
|
||||
|
||||
|
||||
class _RefreshNamespaceWithExpiringOptions(LanceNamespace):
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
|
||||
def namespace_id(self):
|
||||
return f"refresh-test:{self.root}"
|
||||
|
||||
def describe_table(self, request):
|
||||
from pathlib import Path
|
||||
|
||||
return DescribeTableResponse(
|
||||
location=str(Path(self.root) / "t.lance"),
|
||||
storage_options={"vended": "fresh", "expires_at_millis": "1"},
|
||||
)
|
||||
|
||||
|
||||
class _DeclaredNamespaceWithoutProperties(LanceNamespace):
|
||||
root = None
|
||||
|
||||
def __init__(self):
|
||||
from lance.namespace import DirectoryNamespace
|
||||
|
||||
self.client = DirectoryNamespace(root=self.root)
|
||||
|
||||
def namespace_id(self):
|
||||
return self.client.namespace_id()
|
||||
|
||||
def describe_table(self, request):
|
||||
return self.client.describe_table(request)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]])
|
||||
async def test_custom_namespace_table_exists_uses_namespace_api(table_id):
|
||||
@@ -56,6 +90,70 @@ async def test_custom_namespace_table_exists_uses_namespace_api(table_id):
|
||||
assert await adb.table_exists(table_id) is (table_id != ["missing"])
|
||||
|
||||
|
||||
def test_table_pickle_rejects_custom_namespace_connection(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
from lance.namespace import DirectoryNamespace
|
||||
|
||||
lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table(
|
||||
"t", [{"id": 1}]
|
||||
)
|
||||
|
||||
class UnserializableNamespace(LanceNamespace):
|
||||
def __init__(self, root):
|
||||
from threading import Lock
|
||||
|
||||
self.client = DirectoryNamespace(root=str(root))
|
||||
self.lock = Lock()
|
||||
|
||||
def namespace_id(self):
|
||||
return self.client.namespace_id()
|
||||
|
||||
def describe_table(self, request):
|
||||
return self.client.describe_table(request)
|
||||
|
||||
db = LanceNamespaceDBConnection(UnserializableNamespace(tmp_path))
|
||||
table = db.open_table("t")
|
||||
|
||||
with pytest.raises(TypeError, match="namespace"):
|
||||
pickle.dumps(table)
|
||||
|
||||
|
||||
def test_declared_namespace_pickle_keeps_caller_options_after_refresh(tmp_path):
|
||||
lancedb.connect(tmp_path).create_table("t", [{"id": 1}])
|
||||
db = lancedb.connect_namespace(
|
||||
f"{__name__}._RefreshNamespaceWithExpiringOptions", {"root": str(tmp_path)}
|
||||
)
|
||||
table = db.open_table("t", storage_options={"caller_only": "keep"})
|
||||
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
for current in (table, restored):
|
||||
options = current.latest_storage_options()
|
||||
assert options["caller_only"] == "keep"
|
||||
assert options["vended"] == "fresh"
|
||||
|
||||
|
||||
def test_table_pickle_allows_declared_namespace_without_properties(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
|
||||
lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table(
|
||||
"t", [{"id": 1}]
|
||||
)
|
||||
_DeclaredNamespaceWithoutProperties.root = str(tmp_path)
|
||||
try:
|
||||
impl = f"{__name__}._DeclaredNamespaceWithoutProperties"
|
||||
db = LanceNamespaceDBConnection(
|
||||
_DeclaredNamespaceWithoutProperties(), namespace_client_impl=impl
|
||||
)
|
||||
table = db.open_table("t")
|
||||
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
assert restored.to_arrow()["id"].to_pylist() == [1]
|
||||
finally:
|
||||
_DeclaredNamespaceWithoutProperties.root = None
|
||||
|
||||
|
||||
class TestNamespaceCreateTableOptions:
|
||||
@pytest.mark.parametrize("version", ["legacy", "stable"])
|
||||
@pytest.mark.parametrize("empty", [False, True])
|
||||
@@ -309,6 +407,328 @@ def paginated_rest_namespace():
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_rest_namespace_table_pickle_keeps_live_storage_options(tmp_path):
|
||||
from time import time
|
||||
|
||||
local = lancedb.connect(tmp_path)
|
||||
local.create_table("t", [{"id": 1}])
|
||||
location = str(tmp_path / "t.lance")
|
||||
ipc = _ipc_file(pa.table({"id": [42]}))
|
||||
seen = []
|
||||
current_options = {
|
||||
"block_size": "4096",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
seen.append(path)
|
||||
if path.endswith("/describe"):
|
||||
body = json.dumps(
|
||||
{"location": location, "storage_options": current_options}
|
||||
).encode()
|
||||
content_type = "application/json"
|
||||
elif path.endswith("/query"):
|
||||
body = ipc
|
||||
content_type = "application/vnd.apache.arrow.file"
|
||||
else:
|
||||
self.send_error(404)
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
db = lancedb.connect_namespace(
|
||||
"rest",
|
||||
{"uri": f"http://127.0.0.1:{server.server_port}"},
|
||||
namespace_client_pushdown_operations=["QueryTable"],
|
||||
)
|
||||
table = db.open_table("t")
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
seen.clear()
|
||||
assert restored.search().limit(1).to_list() == [{"id": 42}]
|
||||
assert seen == ["/v1/table/t/query"]
|
||||
|
||||
current_options = {
|
||||
"block_size": "8192",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
}
|
||||
assert table.latest_storage_options()["block_size"] == "8192"
|
||||
assert restored.latest_storage_options()["block_size"] == "8192"
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_rest_namespace_create_empty_refresh_does_not_restore_expired_seed(tmp_path):
|
||||
from time import time
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
current_options = {
|
||||
"vended_seed": "short-lived",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
if not (path.endswith("/declare") or path.endswith("/describe")):
|
||||
self.send_error(404)
|
||||
return
|
||||
body = json.dumps(
|
||||
{"location": location, "storage_options": current_options}
|
||||
).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
db = lancedb.connect_namespace(
|
||||
"rest", {"uri": f"http://127.0.0.1:{server.server_port}"}
|
||||
)
|
||||
table = db.create_table("t", [{"id": 1}])
|
||||
payload = pickle.dumps(table)
|
||||
assert b"short-lived" not in payload
|
||||
restored = pickle.loads(payload)
|
||||
|
||||
current_options = {}
|
||||
assert table.latest_storage_options() == {}
|
||||
assert restored.latest_storage_options() == {}
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("entrypoint", ["create", "open"])
|
||||
def test_rest_namespace_pickle_layers_caller_storage_options(tmp_path, entrypoint):
|
||||
from time import time
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
caller_options = {"caller_option": "kept", "conflict": "caller"}
|
||||
vended_options = {
|
||||
"vended_1": "old",
|
||||
"conflict": "vended",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
if path.endswith("/declare") or path.endswith("/describe"):
|
||||
body = json.dumps(
|
||||
{"location": location, "storage_options": vended_options}
|
||||
).encode()
|
||||
else:
|
||||
self.send_error(404)
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
db = lancedb.connect_namespace(
|
||||
"rest",
|
||||
{"uri": f"http://127.0.0.1:{server.server_port}"},
|
||||
)
|
||||
if entrypoint == "create":
|
||||
table = db.create_table(
|
||||
"t", [{"id": 1}], storage_options=caller_options
|
||||
)
|
||||
else:
|
||||
db.create_table("t", [{"id": 1}])
|
||||
table = db.open_table("t", storage_options=caller_options)
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
for current in (table, restored):
|
||||
options = current.latest_storage_options()
|
||||
assert options["caller_option"] == "kept"
|
||||
assert options["conflict"] == "vended"
|
||||
|
||||
vended_options.update(
|
||||
{
|
||||
"vended_2": "new",
|
||||
"conflict": "vended-new",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
}
|
||||
)
|
||||
|
||||
for current in (table, restored):
|
||||
options = current.latest_storage_options()
|
||||
assert options["caller_option"] == "kept"
|
||||
assert options["vended_2"] == "new"
|
||||
assert options["conflict"] == "vended-new"
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_namespace_open_uses_explicit_storage_options_provider(tmp_path):
|
||||
from time import time
|
||||
|
||||
from lancedb._lancedb import connect_namespace as connect_namespace_inner
|
||||
from lancedb.db import AsyncConnection
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
seed_options = {
|
||||
"vended_seed": "short-lived",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
if not (path.endswith("/declare") or path.endswith("/describe")):
|
||||
self.send_error(404)
|
||||
return
|
||||
result = {"location": location, "storage_options": seed_options}
|
||||
body = json.dumps(result).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
class ExplicitClient(LanceNamespace):
|
||||
calls = 0
|
||||
|
||||
def namespace_id(self):
|
||||
return "explicit-storage-options-provider"
|
||||
|
||||
def describe_table(self, request):
|
||||
self.calls += 1
|
||||
return DescribeTableResponse(
|
||||
location=location,
|
||||
storage_options={
|
||||
"explicit_provider": "fresh",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
},
|
||||
)
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
properties = {"uri": f"http://127.0.0.1:{server.server_port}"}
|
||||
db = lancedb.connect_namespace("rest", properties)
|
||||
db.create_table("t", [{"id": 1}])
|
||||
|
||||
async def check():
|
||||
connection = AsyncConnection(
|
||||
connect_namespace_inner("rest", properties)
|
||||
)
|
||||
client = ExplicitClient()
|
||||
table = await connection.open_table("t", namespace_client=client)
|
||||
options = await table.latest_storage_options()
|
||||
assert client.calls > 0
|
||||
assert options["explicit_provider"] == "fresh"
|
||||
|
||||
asyncio.run(check())
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_namespace_create_without_seed_uses_connection_provider(tmp_path):
|
||||
from time import time
|
||||
|
||||
from lancedb._lancedb import connect_namespace as connect_namespace_inner
|
||||
from lancedb.db import AsyncConnection
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
seed_options = {
|
||||
"vended_seed": "short-lived",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
result = {"location": location}
|
||||
if path.endswith("/describe"):
|
||||
result["storage_options"] = seed_options
|
||||
elif not path.endswith("/declare"):
|
||||
self.send_error(404)
|
||||
return
|
||||
body = json.dumps(result).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
class ExplicitClient(LanceNamespace):
|
||||
calls = 0
|
||||
|
||||
def namespace_id(self):
|
||||
return "explicit-storage-options-provider"
|
||||
|
||||
def describe_table(self, request):
|
||||
self.calls += 1
|
||||
return DescribeTableResponse(
|
||||
location=location,
|
||||
storage_options={
|
||||
"explicit_provider": "fresh",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
},
|
||||
)
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
properties = {"uri": f"http://127.0.0.1:{server.server_port}"}
|
||||
|
||||
async def check():
|
||||
connection = AsyncConnection(
|
||||
connect_namespace_inner("rest", properties)
|
||||
)
|
||||
client = ExplicitClient()
|
||||
table = await connection.create_table(
|
||||
"t", [{"id": 1}], namespace_client=client
|
||||
)
|
||||
options = await table.latest_storage_options()
|
||||
assert client.calls == 0
|
||||
assert options["vended_seed"] == "short-lived"
|
||||
|
||||
asyncio.run(check())
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("namespace_path", [[], ["n"]])
|
||||
async def test_rest_namespace_table_names_collects_pages(
|
||||
@@ -1352,6 +1772,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:
|
||||
@@ -1414,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",
|
||||
[
|
||||
|
||||
@@ -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(
|
||||
@@ -275,6 +318,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(
|
||||
|
||||
@@ -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):
|
||||
@@ -811,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")
|
||||
@@ -1401,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",
|
||||
@@ -1410,7 +1748,6 @@ def test_query_builder_with_different_vector_column():
|
||||
columns=["b"],
|
||||
vector_column="foo_vector",
|
||||
),
|
||||
batch_size=None,
|
||||
timeout=None,
|
||||
)
|
||||
|
||||
|
||||
@@ -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",
|
||||
[
|
||||
@@ -5340,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()
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
+43
-2
@@ -2,6 +2,7 @@
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::error::PythonErrorExt;
|
||||
use crate::runtime::future_into_py;
|
||||
@@ -9,9 +10,13 @@ use arrow::{
|
||||
array::RecordBatch,
|
||||
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::{PyRuntimeError, PyStopAsyncIteration},
|
||||
@@ -74,6 +79,42 @@ 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<Q>(
|
||||
py: Python<'_>,
|
||||
query: Q,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>>
|
||||
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::<Vec<_>>().await.infer_error()?;
|
||||
let reader: Box<dyn ArrowRecordBatchReader + Send> = Box::new(RecordBatchIterator::new(
|
||||
batches.into_iter().map(Ok),
|
||||
schema,
|
||||
));
|
||||
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -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<String>,
|
||||
split_weights: Vec<u64>,
|
||||
discard_weight: u64,
|
||||
discard_weight: Option<u64>,
|
||||
split_names: Option<Vec<String>>,
|
||||
) -> PyResult<Self> {
|
||||
let discard_weight = discard_weight.unwrap_or(0);
|
||||
slf.modify(|builder| {
|
||||
builder.with_split_strategy(
|
||||
SplitStrategy::Hash {
|
||||
|
||||
@@ -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<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
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<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
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<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
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<Bound<'_, PyAny>> {
|
||||
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<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
|
||||
+475
-62
@@ -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<Runtime>` 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<Runtime>` 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<Runtime>`.** 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<GenerationCalls>` 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<Runtime>`.** 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<Tagged> = 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<GenerationCalls> = 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<GenerationCalls> {
|
||||
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<Tagged> {
|
||||
ensure_atfork_installed();
|
||||
let current_gen = GENERATION.load(Ordering::SeqCst);
|
||||
loop {
|
||||
let existing = RUNTIME.load_full();
|
||||
@@ -135,9 +220,6 @@ fn get_runtime() -> Arc<Tagged> {
|
||||
{
|
||||
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<Tagged> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<GenerationCalls>,
|
||||
}
|
||||
|
||||
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<F>(fut: F) -> Self::JoinHandle
|
||||
where
|
||||
F: Future<Output = ()> + 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: F) -> Option<i32>
|
||||
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::<i32>()];
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<String, String>,
|
||||
inner: Arc<dyn StorageOptionsProvider>,
|
||||
}
|
||||
|
||||
impl LayeredStorageOptionsProvider {
|
||||
pub(crate) fn new(
|
||||
caller_options: HashMap<String, String>,
|
||||
inner: Arc<dyn StorageOptionsProvider>,
|
||||
) -> Self {
|
||||
Self {
|
||||
caller_options,
|
||||
inner,
|
||||
}
|
||||
}
|
||||
|
||||
fn layer(
|
||||
&self,
|
||||
mut options: Option<HashMap<String, String>>,
|
||||
) -> Option<HashMap<String, String>> {
|
||||
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<Option<HashMap<String, String>>> {
|
||||
Ok(self.layer(self.inner.fetch_storage_options().await?))
|
||||
}
|
||||
|
||||
async fn force_fetch_storage_options(
|
||||
&self,
|
||||
) -> lance_core::Result<Option<HashMap<String, String>>> {
|
||||
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<dyn Database>,
|
||||
@@ -2069,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.
|
||||
@@ -2184,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);
|
||||
|
||||
@@ -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<dyn StorageOptionsProvider> = Arc::new(
|
||||
LanceNamespaceStorageOptionsProvider::new(self.namespace.clone(), table_id.clone()),
|
||||
);
|
||||
let provider: Arc<dyn StorageOptionsProvider> = 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)]
|
||||
|
||||
@@ -249,10 +249,10 @@ impl PermutationBuilder {
|
||||
|
||||
/// Builds the permutation table and stores it in the given database.
|
||||
pub async fn build(mut self) -> Result<Table> {
|
||||
// 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<bytes::Bytes> {
|
||||
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<dyn crate::table::BaseTable> = 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::<Int32Type>())
|
||||
.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<dyn crate::table::BaseTable> = 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<RecordBatch> = permutation
|
||||
.query()
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect()
|
||||
.await
|
||||
.unwrap();
|
||||
let ids: Vec<u64> = batches
|
||||
.iter()
|
||||
.flat_map(|batch| {
|
||||
batch[SRC_ROW_ID_COL]
|
||||
.as_primitive::<UInt64Type>()
|
||||
.values()
|
||||
.to_vec()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(ids, (0..10).collect::<Vec<_>>());
|
||||
|
||||
let recorded = permutation
|
||||
.schema()
|
||||
.await
|
||||
.unwrap()
|
||||
.metadata
|
||||
.get(BASE_VERSION_CONFIG_KEY)
|
||||
.expect("permutation should record its base version")
|
||||
.parse::<u64>()
|
||||
.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::<Int32Type>())
|
||||
.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::<Int32Type>())
|
||||
.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<RecordBatch> = Table::from(snapshot)
|
||||
.query()
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 10);
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 15);
|
||||
}
|
||||
|
||||
#[cfg(feature = "remote")]
|
||||
|
||||
@@ -406,8 +406,8 @@ impl Splitter {
|
||||
.collect::<Vec<_>>();
|
||||
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;
|
||||
|
||||
@@ -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<S: HttpSend + 'static> RemoteTable<S> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
@@ -3301,6 +3339,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
}
|
||||
async fn add(&self, mut add: AddDataBuilder) -> Result<AddResult> {
|
||||
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::<String>("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<lance::dataset::WriteMode>,
|
||||
#[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![
|
||||
|
||||
+103
-19
@@ -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;
|
||||
@@ -281,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<WriteParams>,
|
||||
}
|
||||
|
||||
@@ -3679,7 +3685,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 +3696,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<dyn StorageOptionsProvider> =
|
||||
Arc::new(LanceNamespaceStorageOptionsProvider::new(
|
||||
namespace_client.clone(),
|
||||
table_id,
|
||||
));
|
||||
let provider: Arc<dyn StorageOptionsProvider> =
|
||||
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 +3947,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<dyn StorageOptionsProvider> = Arc::new(
|
||||
LanceNamespaceStorageOptionsProvider::new(namespace_client.clone(), table_id),
|
||||
);
|
||||
|
||||
// Start with provided params or defaults
|
||||
let mut params = params.unwrap_or_default();
|
||||
@@ -3914,17 +3959,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<dyn StorageOptionsProvider> = 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() {
|
||||
@@ -4108,10 +4176,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 {
|
||||
@@ -4153,6 +4229,14 @@ impl BaseTable for NativeTable {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn snapshot_at_current_version(&self) -> Result<Option<Arc<dyn BaseTable>>> {
|
||||
// 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
|
||||
}
|
||||
|
||||
@@ -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::<Vec<_>>().await.unwrap();
|
||||
let ids: Vec<i32> = batches
|
||||
.iter()
|
||||
.flat_map(|batch| {
|
||||
batch
|
||||
.column(0)
|
||||
.as_any()
|
||||
.downcast_ref::<Int32Array>()
|
||||
.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;
|
||||
|
||||
Reference in New Issue
Block a user