Merge main into gatekeeper/fix-4911-1

This commit is contained in:
Gatefixer
2026-11-14 13:05:36 +00:00
170 changed files with 14381 additions and 1858 deletions
@@ -0,0 +1,63 @@
---
name: lancedb-vector-dedup
description: Plan and run Enterprise IVF vector deduplication with dedupe and duplicate_pairs, including sampling, index coverage, recall and resource limits. Use for near-duplicate embedding or perceptual-hash records; use MinHash guidance for text shingles.
---
# Vector deduplication
Read the maintained [workflow](../../../docs/web/curation/dedupe.mdx),
[DEDUPE reference](../../../docs/web/sql/dql/dedupe.mdx) and
[DUPLICATE_PAIRS reference](../../../docs/web/sql/dql/duplicate-pairs.mdx)
before constructing SQL. In a source checkout these paths are relative to this
skill directory. When using an installed copy without the docs, read
`https://docs.lancedb.com/curation/dedupe` and the linked SQL references.
## Establish the comparison contract
- Confirm an Enterprise deployment that supports these table functions. Use
`dedupe` and `duplicate_pairs`; legacy `vector_dedup` names are rejected.
- Inspect the vector type, metric, compatible index, indexed fragments and
source version. Wait for index coverage after writes. Do not run a full
scan over unindexed fragments or silently change the index to make it run.
- Explain that candidates are compared only within physical IVF partitions
and segments. Encoded/quantized distances are not an exact raw-vector
comparison. L2 thresholds are squared distances; Hamming counts bits.
- Use `id_column` on pair queries for business IDs. Retain `dataset_version`,
segment and partition identities. Do not decode internal row IDs or assume
that representatives stay the same after later data/index changes.
## Bound the first experiment
Use a reproducible partition sample before a full scan:
```sql
SELECT id_a, id_b, distance, dataset_version, segment_id, partition_id
FROM duplicate_pairs(
'frames', 'embedding',
distance_threshold => 0.02,
id_column => 'frame_id',
selection => 'random', count => 10, seed => 42
)
```
Adapt the threshold and sample size to the metric and actual partition count.
Sampling partitions is not uniform sampling of rows. Inspect known duplicate
and distinct examples, pair density, partition skew, memory, spill space and
elapsed time. Do not infer global recall or ten-billion-row qualification
from a small or unversioned benchmark. Pair work and output can be quadratic
within a partition; an outer SQL `LIMIT` is not an upstream work budget.
## Choose the result
`dedupe` returns original representative rows and always scans all partitions.
Use its default `connected_components` for transitive groups; choose
`direct_representative` when chains should not merge transitively. It does not
accept `id_column`, `selection`, `count` or `seed`; `duplicate_pairs` does not
accept `resolution`.
Keep pair data on the server when possible; avoid collecting an unbounded
edge set in client memory. Persist a new table/view only within the user's
authorized scope, preserving source rows unless deletion was requested.
Do not register a Python Function or fetch/rewrite Blob payloads to invoke
these built-in table functions. For MinHash/text deduplication, follow the
separate `https://docs.lancedb.com/enterprise/sql-minhash` workflow.
+1 -1
View File
@@ -1,5 +1,5 @@
[tool.bumpversion]
current_version = "0.42.0-beta.12"
current_version = "0.42.0-beta.13"
parse = """(?x)
(?P<major>0|[1-9]\\d*)\\.
(?P<minor>0|[1-9]\\d*)\\.
@@ -12,6 +12,9 @@ inputs:
runs:
using: "composite"
steps:
- name: Enable long paths for Lance dependencies
shell: bash
run: git config --global core.longpaths true
- uses: ./.github/actions/setup-protoc
- name: Build wheel
uses: PyO3/maturin-action@v1
+15 -5
View File
@@ -39,9 +39,11 @@ jobs:
distribution: temurin
java-version: 8
cache: "maven"
server-id: ossrh
server-username: SONATYPE_USER
server-password: SONATYPE_TOKEN
# Betas go to Fury and stable releases to Maven Central, which limits
# how many releases an organization may publish each month.
server-id: ${{ contains(github.ref, 'beta') && 'fury' || 'ossrh' }}
server-username: ${{ contains(github.ref, 'beta') && 'FURY_TOKEN' || 'SONATYPE_USER' }}
server-password: ${{ contains(github.ref, 'beta') && 'FURY_PASSWORD' || 'SONATYPE_TOKEN' }}
gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }}
gpg-passphrase: MAVEN_GPG_PASSPHRASE
- name: Set git config
@@ -52,8 +54,16 @@ jobs:
if: github.event_name == 'pull_request'
run: |
./mvnw --batch-mode -DskipTests package -pl lancedb-core -am
- name: Publish
if: startsWith(github.ref, 'refs/tags/v')
- name: Publish to Fury
if: startsWith(github.ref, 'refs/tags/v') && contains(github.ref, 'beta')
run: |
./mvnw --batch-mode -DskipTests deploy -pl lancedb-core -am -P deploy-to-fury
env:
FURY_TOKEN: ${{ secrets.FURY_TOKEN }}
# Fury authenticates with the token as the username; the password is ignored.
FURY_PASSWORD: NOPASS
- name: Publish to Maven Central
if: startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, 'beta')
run: |
echo "use-agent" >> ~/.gnupg/gpg.conf
echo "pinentry-mode loopback" >> ~/.gnupg/gpg.conf
+4
View File
@@ -162,6 +162,10 @@ jobs:
working-directory: nodejs
steps:
- uses: actions/checkout@v6
- name: Enable long paths for Windows dependencies
if: runner.os == 'Windows'
# 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
with:
+13 -4
View File
@@ -154,6 +154,8 @@ jobs:
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: "stable"
# The explicit cache below runs after lock removal and only saves on main.
cache: false
# Remove cargo.lock to force a fresh build
- name: Remove Cargo.lock
run: rm -f Cargo.lock
@@ -295,10 +297,12 @@ jobs:
run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests
macos:
name: ${{ matrix.phase == 'tests' && format('macos ({0})', matrix.mac-runner) || format('macos-doc ({0})', matrix.mac-runner) }}
timeout-minutes: 60
strategy:
matrix:
mac-runner: ["macos-15", "macos-26"]
phase: [tests, doc]
runs-on: "${{ matrix.mac-runner }}"
defaults:
run:
@@ -320,16 +324,17 @@ jobs:
- name: Install dependencies
run: brew install protobuf
- name: Run tests
env:
CARGO_TEST_TARGETS: ${{ matrix.phase == 'doc' && '--doc' || '--lib --tests' }}
run: |
# Don't run the s3 integration tests since docker isn't available
# on this image.
ALL_FEATURES=`cargo metadata --format-version=1 --no-deps \
| jq -r '.packages[] | .features | keys | .[]' \
| grep -v s3-test | sort | uniq | paste -s -d "," -`
# Run doctests before test binaries fill the runner disk. Examples are
# already built by the Linux job, so avoid retaining them here.
cargo test --profile ci --features $ALL_FEATURES --locked --doc
cargo test --profile ci --features $ALL_FEATURES --locked --lib --tests
# Separate jobs give each phase its own time and disk budget. Examples
# are already built by the Linux job, so avoid retaining them here.
cargo test --profile ci --features $ALL_FEATURES --locked $CARGO_TEST_TARGETS
windows:
strategy:
@@ -344,6 +349,8 @@ jobs:
working-directory: rust/lancedb
steps:
- uses: actions/checkout@v6
- name: Enable long paths for Lance dependencies
run: git config --global core.longpaths true
- name: Set target
run: rustup target add ${{ matrix.target }}
- uses: Swatinem/rust-cache@v2
@@ -381,6 +388,8 @@ jobs:
working-directory: rust/lancedb
steps:
- uses: actions/checkout@v6
- name: Enable long paths for Lance dependencies
run: git config --global core.longpaths true
- name: Set target
run: rustup target add aarch64-pc-windows-msvc
- uses: Swatinem/rust-cache@v2
Generated
+106 -279
View File
@@ -63,15 +63,15 @@ dependencies = [
[[package]]
name = "alloc-no-stdlib"
version = "2.0.4"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
[[package]]
name = "alloc-stdlib"
version = "0.2.2"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
"alloc-no-stdlib",
]
@@ -221,9 +221,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
[[package]]
name = "arrayvec"
version = "0.7.6"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "arrow"
@@ -1517,9 +1517,9 @@ dependencies = [
[[package]]
name = "brotli"
version = "3.5.0"
version = "9.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d640d25bc63c50fb1f0b545ffd80207d2e10a4c965530809b40ba3386825c391"
checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -1528,9 +1528,9 @@ dependencies = [
[[package]]
name = "brotli-decompressor"
version = "2.5.1"
version = "6.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e2e4afe60d7dd600fdd3de8d0f08c2b7ec039712e3b6137ff98b7004e82de4f"
checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -2310,7 +2310,7 @@ checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11"
dependencies = [
"cpubits",
"ctutils",
"getrandom 0.4.2",
"getrandom 0.4.3",
"hybrid-array",
"num-traits",
"rand_core 0.10.1",
@@ -2334,7 +2334,7 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710"
dependencies = [
"getrandom 0.4.2",
"getrandom 0.4.3",
"hybrid-array",
"rand_core 0.10.1",
]
@@ -3553,11 +3553,10 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f"
[[package]]
name = "event-listener"
version = "5.4.1"
version = "5.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab"
checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
dependencies = [
"concurrent-queue",
"parking",
"pin-project-lite",
]
@@ -3874,8 +3873,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
[[package]]
name = "fsst"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-array",
"rand 0.9.5",
@@ -4297,17 +4296,15 @@ dependencies = [
[[package]]
name = "getrandom"
version = "0.4.2"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if 1.0.4",
"js-sys",
"libc",
"r-efi 6.0.0",
"rand_core 0.10.1",
"wasip2",
"wasip3",
"wasm-bindgen",
]
@@ -4988,12 +4985,6 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f"
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ident_case"
version = "1.0.1"
@@ -5324,13 +5315,12 @@ dependencies = [
[[package]]
name = "js-sys"
version = "0.3.98"
version = "0.3.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08"
checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
dependencies = [
"cfg-if 1.0.4",
"futures-util",
"once_cell",
"wasm-bindgen",
]
@@ -5362,8 +5352,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a"
[[package]]
name = "lance"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arc-swap",
"arrow",
@@ -5438,8 +5428,8 @@ dependencies = [
[[package]]
name = "lance-arrow"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5461,7 +5451,7 @@ dependencies = [
[[package]]
name = "lance-arrow-scalar"
version = "59.0.0"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5475,7 +5465,7 @@ dependencies = [
[[package]]
name = "lance-arrow-stats"
version = "59.0.0"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5484,8 +5474,8 @@ dependencies = [
[[package]]
name = "lance-bitpacking"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrayref",
"crunchy",
@@ -5495,8 +5485,8 @@ dependencies = [
[[package]]
name = "lance-core"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5534,8 +5524,8 @@ dependencies = [
[[package]]
name = "lance-datafusion"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow",
"arrow-array",
@@ -5566,8 +5556,8 @@ dependencies = [
[[package]]
name = "lance-datafusion-exec"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow",
"arrow-array",
@@ -5592,8 +5582,8 @@ dependencies = [
[[package]]
name = "lance-datagen"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow",
"arrow-array",
@@ -5610,8 +5600,8 @@ dependencies = [
[[package]]
name = "lance-derive"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"proc-macro2",
"quote",
@@ -5620,8 +5610,8 @@ dependencies = [
[[package]]
name = "lance-encoding"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-arith",
"arrow-array",
@@ -5654,8 +5644,8 @@ dependencies = [
[[package]]
name = "lance-file"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-arith",
"arrow-array",
@@ -5686,8 +5676,8 @@ dependencies = [
[[package]]
name = "lance-geo"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5718,8 +5708,8 @@ dependencies = [
[[package]]
name = "lance-index"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arc-swap",
"arrow",
@@ -5755,6 +5745,7 @@ dependencies = [
"lance-arrow-stats",
"lance-bitpacking",
"lance-core",
"lance-datafusion",
"lance-datafusion-exec",
"lance-encoding",
"lance-file",
@@ -5791,8 +5782,8 @@ dependencies = [
[[package]]
name = "lance-index-core"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5815,8 +5806,8 @@ dependencies = [
[[package]]
name = "lance-io"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow",
"arrow-array",
@@ -5861,8 +5852,8 @@ dependencies = [
[[package]]
name = "lance-jsonb"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"byteorder",
"ethnum",
@@ -5879,7 +5870,7 @@ dependencies = [
[[package]]
name = "lance-linalg"
version = "15.0.0-beta.18"
version = "15.0.0-beta.21"
dependencies = [
"approx",
"argminmax 0.7.1",
@@ -5901,8 +5892,8 @@ dependencies = [
[[package]]
name = "lance-namespace"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow",
"async-trait",
@@ -5916,8 +5907,8 @@ dependencies = [
[[package]]
name = "lance-namespace-impls"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arc-swap",
"arrow",
@@ -5971,8 +5962,8 @@ dependencies = [
[[package]]
name = "lance-select"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5986,8 +5977,8 @@ dependencies = [
[[package]]
name = "lance-table"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow",
"arrow-array",
@@ -6028,8 +6019,8 @@ dependencies = [
[[package]]
name = "lance-testing"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -6042,8 +6033,8 @@ dependencies = [
[[package]]
name = "lance-tokenizer"
version = "15.0.0-beta.18"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120"
version = "15.0.0-beta.21"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
dependencies = [
"frostem",
"icu_segmenter",
@@ -6056,7 +6047,7 @@ dependencies = [
[[package]]
name = "lancedb"
version = "0.42.0-beta.12"
version = "0.42.0-beta.13"
dependencies = [
"ahash",
"anyhow",
@@ -6167,7 +6158,7 @@ dependencies = [
[[package]]
name = "lancedb-cli"
version = "0.42.0-beta.12"
version = "0.42.0-beta.13"
dependencies = [
"anyhow",
"arrow-array",
@@ -6210,7 +6201,7 @@ dependencies = [
[[package]]
name = "lancedb-nodejs"
version = "0.42.0-beta.12"
version = "0.42.0-beta.13"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -6235,7 +6226,7 @@ dependencies = [
[[package]]
name = "lancedb-python"
version = "0.42.0-beta.12"
version = "0.42.0-beta.13"
dependencies = [
"arc-swap",
"arrow",
@@ -6299,12 +6290,6 @@ dependencies = [
"spin 0.9.9",
]
[[package]]
name = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "lexical-core"
version = "1.0.6"
@@ -6760,9 +6745,9 @@ dependencies = [
[[package]]
name = "mio"
version = "1.2.0"
version = "1.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
dependencies = [
"libc",
"wasi 0.11.1+wasi-snapshot-preview1",
@@ -8606,16 +8591,6 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn 2.0.117",
]
[[package]]
name = "primefield"
version = "0.14.0"
@@ -8952,7 +8927,7 @@ checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
dependencies = [
"aws-lc-rs",
"bytes",
"getrandom 0.4.2",
"getrandom 0.4.3",
"lru-slab",
"rand 0.10.1",
"rand_pcg",
@@ -9055,7 +9030,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"
dependencies = [
"chacha20",
"getrandom 0.4.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -9152,15 +9127,13 @@ dependencies = [
[[package]]
name = "random_word"
version = "0.4.3"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07eed67a16dde2cc3c7f65c072acd8d5b2e53d4aab95067c320db851c7651f29"
checksum = "5d9299243acac3cb4f35c9f78d5ad29c87e70cd916a70f293d8526e54049c340"
dependencies = [
"ahash",
"brotli",
"once_cell",
"paste",
"rand 0.8.6",
"rand 0.10.1",
"unicase",
]
@@ -10660,9 +10633,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.15.1"
version = "1.16.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
dependencies = [
"serde",
]
@@ -11146,7 +11119,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.2",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.4",
"windows-sys 0.61.2",
@@ -11245,9 +11218,9 @@ dependencies = [
[[package]]
name = "thread_local"
version = "1.1.9"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
dependencies = [
"cfg-if 1.0.4",
]
@@ -11315,18 +11288,9 @@ dependencies = [
[[package]]
name = "tinyvec"
version = "1.11.0"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tokenizers"
@@ -11882,12 +11846,6 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "unicode_categories"
version = "0.1.1"
@@ -11974,7 +11932,7 @@ version = "1.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514"
dependencies = [
"getrandom 0.4.2",
"getrandom 0.4.3",
"js-sys",
"serde_core",
"sha1_smol",
@@ -12066,16 +12024,7 @@ version = "1.0.3+wasi-0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"
dependencies = [
"wit-bindgen 0.57.1",
]
[[package]]
name = "wasip3"
version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
dependencies = [
"wit-bindgen 0.51.0",
"wit-bindgen",
]
[[package]]
@@ -12089,12 +12038,11 @@ dependencies = [
[[package]]
name = "wasm-bindgen"
version = "0.2.121"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790"
checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
dependencies = [
"cfg-if 1.0.4",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
@@ -12102,19 +12050,20 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.71"
version = "0.4.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8"
checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"
dependencies = [
"js-sys",
"tokio",
"wasm-bindgen",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.121"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578"
checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -12122,48 +12071,26 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.121"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2"
checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn 2.0.117",
"syn 3.0.3",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.121"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441"
checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
dependencies = [
"unicode-ident",
]
[[package]]
name = "wasm-encoder"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
dependencies = [
"leb128fmt",
"wasmparser",
]
[[package]]
name = "wasm-metadata"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
dependencies = [
"anyhow",
"indexmap 2.14.0",
"wasm-encoder",
"wasmparser",
]
[[package]]
name = "wasm-streams"
version = "0.4.2"
@@ -12190,23 +12117,11 @@ dependencies = [
"web-sys",
]
[[package]]
name = "wasmparser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
dependencies = [
"bitflags 2.11.1",
"hashbrown 0.15.5",
"indexmap 2.14.0",
"semver",
]
[[package]]
name = "web-sys"
version = "0.3.98"
version = "0.3.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa"
checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -12726,100 +12641,12 @@ version = "0.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
[[package]]
name = "wit-bindgen"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
dependencies = [
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "wit-bindgen-core"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
dependencies = [
"anyhow",
"heck 0.5.0",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
dependencies = [
"anyhow",
"heck 0.5.0",
"indexmap 2.14.0",
"prettyplease",
"syn 2.0.117",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
dependencies = [
"anyhow",
"prettyplease",
"proc-macro2",
"quote",
"syn 2.0.117",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
dependencies = [
"anyhow",
"bitflags 2.11.1",
"indexmap 2.14.0",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
dependencies = [
"anyhow",
"id-arena",
"indexmap 2.14.0",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-xid",
"wasmparser",
]
[[package]]
name = "wkb"
version = "0.9.2"
@@ -12922,7 +12749,7 @@ dependencies = [
"countio",
"futures",
"futures-util",
"getrandom 0.4.2",
"getrandom 0.4.3",
"heapify",
"itertools 0.14.0",
"lz4_flex 0.13.1",
@@ -13059,18 +12886,18 @@ dependencies = [
[[package]]
name = "zerocopy"
version = "0.8.48"
version = "0.8.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.48"
version = "0.8.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
dependencies = [
"proc-macro2",
"quote",
@@ -13146,7 +12973,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e408c6cc4699dd017d53dc080cd51c2cea2b5354af57a1479bd265ed42911487"
dependencies = [
"crc32fast",
"getrandom 0.4.2",
"getrandom 0.4.3",
"indexmap 2.14.0",
"libc",
"memchr",
+14 -14
View File
@@ -20,20 +20,20 @@ categories = ["database-implementations"]
rust-version = "1.95.0"
[workspace.dependencies]
lance = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-core = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-datagen = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-file = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-io = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-index = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-jsonb = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace-impls = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-table = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-testing = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-datafusion = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance-arrow = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" }
lance = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-core = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-datagen = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-file = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-io = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-index = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-jsonb = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace-impls = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-table = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-testing = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-datafusion = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lance-arrow = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
lancedb = { path = "rust/lancedb", default-features = false }
ahash = "0.8"
anyhow = "1"
+2 -1
View File
@@ -54,6 +54,7 @@ def main() -> int:
["cargo", "metadata", "--format-version=1", "--no-deps", "--all-features"],
stdout=subprocess.PIPE,
text=True,
check=False,
)
if metadata.returncode:
return metadata.returncode
@@ -68,7 +69,7 @@ def main() -> int:
"--tests",
# Bound simultaneous compiler/linker temporary outputs as well as retained files.
"--jobs",
"1",
"2",
"--message-format=json,json-diagnostic-rendered-ansi",
]
cleanup_failed = False
+5 -3
View File
@@ -88,9 +88,11 @@ class BuildNoLockTest(unittest.TestCase):
self.assertTrue((target / "fixture_cli").is_file())
# Cargo guarantees this binary for test execution, not compile-time reads.
subprocess.run([str(target / "fixture_cli")], check=True)
self.assertTrue(list((target / "deps").glob("libartifact_fixture*.rlib")))
self.assertTrue(list((target / "build").glob("*/build-script-build")))
self.assertTrue(list((target / "build").glob("*/out/generated.rs")))
# Cargo 1.100 nests compiler inputs in per-unit build directories and
# names the build-script executable build_script_build.
self.assertTrue(list(target.rglob("libartifact_fixture*.rlib")))
self.assertTrue(list((target / "build").rglob("build[-_]script[-_]build")))
self.assertTrue(list((target / "build").rglob("out/generated.rs")))
def test_link_failure_preserves_cargo_status_and_diagnostic(self):
with tempfile.TemporaryDirectory(prefix=".no-lock-", dir=SCRIPT.parent) as temp:
+1 -1
View File
@@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`:
<dependency>
<groupId>com.lancedb</groupId>
<artifactId>lancedb-core</artifactId>
<version>0.42.0-beta.12</version>
<version>0.42.0-beta.13</version>
</dependency>
```
+42
View File
@@ -650,6 +650,48 @@ tables; no partial handles are returned.
***
### fetchBlobRanges()
```ts
abstract fetchBlobRanges(
column,
requests,
options?): Promise<(null | Buffer)[]>
```
Materializes row-specific byte ranges at the table's current checkout.
Preserves request order, duplicates, and nulls. Zero length returns an empty
buffer for a non-null blob. Invalid ranges or missing rows reject the entire
call. See [Table.fetchBlobs](Table.md#fetchblobs) for row-ID validity across versions.
Remote tables use the batched endpoint when the server advertises support,
splitting at 1024 ranges and 64 MiB, including individual larger ranges.
Older servers use descriptor queries and BlobFile range reads. Both protocols
use one exact branch and version. Errors from an advertised endpoint propagate
without switching protocols. All output bytes occupy memory.
#### Parameters
* **column**: `string`
* **requests**: readonly [`BlobRangeRequest`](../type-aliases/BlobRangeRequest.md)[]
* **options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md)
#### Returns
`Promise`&lt;(`null` \| `Buffer`)[]&gt;
#### Example
```ts
const bytes = await table.fetchBlobRanges("image", [
{ rowId: 10n, offset: 0n, length: 1024n },
]);
```
***
### fetchBlobs()
```ts
+1
View File
@@ -169,6 +169,7 @@
- [BlobMode](type-aliases/BlobMode.md)
- [BlobOptions](type-aliases/BlobOptions.md)
- [BlobRange](type-aliases/BlobRange.md)
- [BlobRangeRequest](type-aliases/BlobRangeRequest.md)
- [BlobReadOptions](type-aliases/BlobReadOptions.md)
- [BlobUri](type-aliases/BlobUri.md)
- [Data](type-aliases/Data.md)
+12
View File
@@ -71,3 +71,15 @@ await table.add(data, {
},
});
```
***
### retries?
```ts
optional retries: number;
```
Override the remote retry budget for this call (0 to 255). Zero disables
retries, including multipart parts. Ambiguous commits are never replayed.
Ignored by LanceDB Embedded.
@@ -0,0 +1,39 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / BlobRangeRequest
# Type Alias: BlobRangeRequest
```ts
type BlobRangeRequest: object;
```
One row-specific range for [Table.fetchBlobRanges](../classes/Table.md#fetchblobranges).
## Type declaration
### length
```ts
length: bigint;
```
Number of bytes to read, as a uint64. Zero returns an empty non-null value.
### offset
```ts
offset: bigint;
```
Byte offset from the beginning of the logical blob, as a uint64.
### rowId
```ts
rowId: bigint | number;
```
A row ID from a query with row IDs enabled.
+92
View File
@@ -37,6 +37,18 @@ embedding_functions`. Prefer keyword arguments for optional parameters.
::: lancedb.db.DBConnection
Use `db.server_info()` (or `await db.server_info()` on an asynchronous connection)
to include the responding server's release, Git revision, build date and Function
runtime information in a bug report. It returns a JSON-compatible dictionary and
does not submit a query or job. Configured images are distinct from the version
of an already running job. During a rolling upgrade, successive requests can
reach different query-node builds. Embedded connections and older servers without
the endpoint raise `NotImplementedError`.
::: lancedb.server_info.ServerBuildInfo
::: lancedb.server_info.ServerInfo
Resource listings return iterators. Use `list(db.list_tables())` to collect all
table names. `db.list_tables().tables` is a list of the first page; `limit`
controls its page size and `page_token` resumes at a saved token. The same
@@ -447,6 +459,51 @@ assert scaler(3.0) == 6.0
scaler.close()
```
### Function packaging restrictions
The decorator snapshots the Function's source and referenced globals into a new
module. It conservatively rejects imports of `sys`, `builtins`, `importlib`,
`inspect`, `gc`, `ctypes`, and `types`, including submodules such as `ctypes.util`
and `importlib.metadata`. This applies to imports inside function or class bodies
and references to module-level aliases. Even ordinary uses such as `sys.version`
and `ctypes.util.find_library` are blocked: these modules can reach names outside
the reconstructed Function namespace. References to `globals`, `locals`, `vars`,
`eval`, `exec`, `compile`, and `__import__` are rejected as dynamic namespace access.
These restrictions also apply to the deprecated `@udf` alias.
For legitimate uses, move the code into an importable helper module and ship it
with `code=`, or install its package with `pip=` or `conda=`. Imported helpers keep
their own namespace; the packager does not scan their bodies. Helpers defined in
`__main__` are copied by source and have the same restrictions as the Function.
For example, put this helper in `native_diagnostics/__init__.py`:
```python
import ctypes.util
def find_library(name: str) -> str:
return ctypes.util.find_library(name) or ""
```
Then import the helper and include its source in the Function's artifact:
```python
import native_diagnostics
from lancedb import function
@function(code=[native_diagnostics])
def probe_library(name: str) -> str:
return native_diagnostics.find_library(name)
```
Captured literal globals support `None`, booleans, integers, strings, bytes,
finite floats, and tuples of these values. Construct other objects, including
PyArrow types and schemas, inside the Function or helper module instead. Values
used only in the decorator's `input_schema` or `output_schema` are not captured
globals and can be defined outside the Function.
Annotate a blob input with `lancedb.BlobReader` for lazy, seekable access, or
with `bytes` to materialize its contents before the Function runs. Reader
inputs infer the Blob V2 type without an explicit input schema. Readers are
@@ -570,6 +627,20 @@ remain available, as do LanceDB Enterprise operations. The same feature
requirement applies to LanceDB Embedded SQL computed-column declaration and refresh; ordinary
eager `add_columns` transforms remain available.
Pass a complete defining SQL query with `query=` to use grouping, Functions
in `FROM`, or `UNNEST`:
```python
view = db.create_materialized_view(
"events_by_kind",
query="SELECT kind, count(*) AS n FROM events GROUP BY kind",
)
```
`query` is mutually exclusive with `source`, `select`, `where`, and `limit`.
It is also accepted by asynchronous connections and `create_materialized_view_async`.
The backend SQL parser determines which query shapes are supported.
In LanceDB Enterprise, creation accepts `auto_refresh_enabled` and
`auto_refresh_interval_seconds`:
@@ -748,6 +819,15 @@ with `search().with_row_id(True).to_arrow()` and pass the result to the fetch AP
One missing or deleted row ID rejects the entire blob-read batch; the APIs do
not return partial results.
Local and remote `BlobFile` handles prefetch 512 KiB for sequential reads by
default. Pass `buffer_size=0` to `fetch_blob_files`, `open_blob_file`, or
`open_blob_files` for sparse reads, or choose another window size in bytes.
Call `file.set_buffer_size(size)` to change it without moving the cursor;
changing the size discards unused prefetched bytes. Explicit `read_range` and
`read_ranges` calls always read exactly the requested intervals and leave the
cursor unchanged. Remote prefetch consumes the HTTP response completely before
returning, so idle handles do not hold request concurrency slots or connections.
To construct inline Blob V2 arrays for ingestion in record batches, use
[blob_array][lancedb.schema.blob_array]. It accepts bytes and `None`, preserving
the distinction between an empty blob (`b""`) and a null blob:
@@ -1340,3 +1420,15 @@ name; omitting it allows matching reads of any revision. Prefixes must be concre
paths without wildcards or traversal. This integration does not make Hugging Face
a writable database location for `ATTACH DATABASE`. Dataset SQL sources select a
matching integration automatically, with no integration argument in the query.
### Function package resources
`@function(code=[my_package])` includes the package’s Python modules and data
files, including vendored subpackages. Resource paths and bytes are preserved,
so `importlib.resources` and package integrity checks work after deployment.
Changing a resource changes the Function artifact digest. This requires a server
that accepts `python_bundle.resources`.
Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or
`conda=` for platform-specific dependencies and `models=` for large model snapshots.
+68 -233
View File
@@ -87,9 +87,9 @@ checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anyhow"
version = "1.0.102"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "ar_archive_writer"
@@ -129,9 +129,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
[[package]]
name = "arrayvec"
version = "0.7.6"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "arrow"
@@ -683,9 +683,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "bytes"
version = "1.11.1"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cast"
@@ -1019,9 +1019,9 @@ dependencies = [
[[package]]
name = "crossbeam-epoch"
version = "0.9.18"
version = "0.9.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
dependencies = [
"crossbeam-utils",
]
@@ -1904,7 +1904,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -1993,7 +1993,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -2004,11 +2004,10 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f"
[[package]]
name = "event-listener"
version = "5.4.1"
version = "5.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab"
checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
dependencies = [
"concurrent-queue",
"parking",
"pin-project-lite",
]
@@ -2289,17 +2288,15 @@ dependencies = [
[[package]]
name = "getrandom"
version = "0.4.2"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 6.0.0",
"rand_core 0.10.1",
"wasip2",
"wasip3",
"wasm-bindgen",
]
@@ -2317,9 +2314,9 @@ checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "h2"
version = "0.4.12"
version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386"
checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118"
dependencies = [
"atomic-waker",
"bytes",
@@ -2475,9 +2472,9 @@ checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"
[[package]]
name = "hyper"
version = "1.8.1"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11"
checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
dependencies = [
"atomic-waker",
"bytes",
@@ -2490,7 +2487,6 @@ dependencies = [
"httpdate",
"itoa",
"pin-project-lite",
"pin-utils",
"smallvec",
"tokio",
"want",
@@ -2699,12 +2695,6 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f"
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ident_case"
version = "1.0.1"
@@ -2808,7 +2798,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
dependencies = [
"hermit-abi",
"libc",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -2876,7 +2866,7 @@ dependencies = [
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -2917,11 +2907,12 @@ dependencies = [
[[package]]
name = "js-sys"
version = "0.3.83"
version = "0.3.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8"
checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
dependencies = [
"once_cell",
"cfg-if",
"futures-util",
"wasm-bindgen",
]
@@ -3607,12 +3598,6 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "lexical-core"
version = "1.0.6"
@@ -3925,9 +3910,9 @@ dependencies = [
[[package]]
name = "mio"
version = "1.1.1"
version = "1.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc"
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
dependencies = [
"libc",
"wasi",
@@ -3936,9 +3921,9 @@ dependencies = [
[[package]]
name = "moka"
version = "0.12.11"
version = "0.12.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8261cd88c312e0004c1d51baad2980c66528dfdb2bee62003e643a4d8f86b077"
checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9"
dependencies = [
"async-lock",
"crossbeam-channel",
@@ -3949,7 +3934,6 @@ dependencies = [
"futures-util",
"parking_lot",
"portable-atomic",
"rustc_version",
"smallvec",
"tagptr",
"uuid",
@@ -4062,7 +4046,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -4919,7 +4903,7 @@ version = "0.14.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7"
dependencies = [
"heck 0.5.0",
"heck 0.4.1",
"itertools 0.14.0",
"log",
"multimap",
@@ -5020,7 +5004,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
dependencies = [
"bytes",
"getrandom 0.4.2",
"getrandom 0.4.3",
"lru-slab",
"rand 0.10.3",
"rand_pcg",
@@ -5046,7 +5030,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -5113,7 +5097,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"chacha20",
"getrandom 0.4.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -5520,14 +5504,14 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.11.0",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
name = "rustls"
version = "0.23.45"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
@@ -5861,9 +5845,9 @@ checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589"
[[package]]
name = "smallvec"
version = "1.15.1"
version = "1.16.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
[[package]]
name = "smartstring"
@@ -5900,7 +5884,7 @@ version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451"
dependencies = [
"heck 0.5.0",
"heck 0.4.1",
"proc-macro2",
"quote",
"syn 2.0.117",
@@ -5912,7 +5896,7 @@ version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f103c50866b8743da9429b8a581d81a27c2d3a9c4ac7df8f8571c1dd7896eda"
dependencies = [
"heck 0.5.0",
"heck 0.4.1",
"proc-macro2",
"quote",
"syn 2.0.117",
@@ -6247,7 +6231,7 @@ dependencies = [
"getrandom 0.3.4",
"once_cell",
"rustix 1.1.2",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -6301,9 +6285,9 @@ dependencies = [
[[package]]
name = "thread_local"
version = "1.1.9"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
dependencies = [
"cfg-if",
]
@@ -6371,18 +6355,9 @@ dependencies = [
[[package]]
name = "tinyvec"
version = "1.10.0"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tokio"
@@ -6646,12 +6621,6 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
@@ -6700,7 +6669,7 @@ version = "1.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7"
dependencies = [
"getrandom 0.4.2",
"getrandom 0.4.3",
"js-sys",
"serde_core",
"sha1_smol",
@@ -6731,9 +6700,9 @@ dependencies = [
[[package]]
name = "want"
version = "0.3.1"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"
dependencies = [
"try-lock",
]
@@ -6750,26 +6719,16 @@ version = "1.0.1+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
dependencies = [
"wit-bindgen 0.46.0",
]
[[package]]
name = "wasip3"
version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
dependencies = [
"wit-bindgen 0.51.0",
"wit-bindgen",
]
[[package]]
name = "wasm-bindgen"
version = "0.2.106"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd"
checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
@@ -6777,22 +6736,20 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.56"
version = "0.4.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "836d9622d604feee9e5de25ac10e3ea5f2d65b41eac0d9ce72eb5deae707ce7c"
checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"
dependencies = [
"cfg-if",
"js-sys",
"once_cell",
"tokio",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.106"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3"
checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -6800,48 +6757,26 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.106"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40"
checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn 2.0.117",
"syn 3.0.6",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.106"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4"
checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
dependencies = [
"unicode-ident",
]
[[package]]
name = "wasm-encoder"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
dependencies = [
"leb128fmt",
"wasmparser",
]
[[package]]
name = "wasm-metadata"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
dependencies = [
"anyhow",
"indexmap 2.14.0",
"wasm-encoder",
"wasmparser",
]
[[package]]
name = "wasm-streams"
version = "0.4.2"
@@ -6855,23 +6790,11 @@ dependencies = [
"web-sys",
]
[[package]]
name = "wasmparser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
dependencies = [
"bitflags 2.10.0",
"hashbrown 0.15.5",
"indexmap 2.14.0",
"semver",
]
[[package]]
name = "web-sys"
version = "0.3.83"
version = "0.3.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b32828d774c412041098d182a8b38b16ea816958e07cf40eec2bc080ae137ac"
checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -6909,7 +6832,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -7254,94 +7177,6 @@ version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
[[package]]
name = "wit-bindgen"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
dependencies = [
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen-core"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
dependencies = [
"anyhow",
"heck 0.5.0",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
dependencies = [
"anyhow",
"heck 0.5.0",
"indexmap 2.14.0",
"prettyplease",
"syn 2.0.117",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
dependencies = [
"anyhow",
"prettyplease",
"proc-macro2",
"quote",
"syn 2.0.117",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
dependencies = [
"anyhow",
"bitflags 2.10.0",
"indexmap 2.14.0",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
dependencies = [
"anyhow",
"id-arena",
"indexmap 2.14.0",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-xid",
"wasmparser",
]
[[package]]
name = "writeable"
version = "0.6.2"
@@ -7388,18 +7223,18 @@ dependencies = [
[[package]]
name = "zerocopy"
version = "0.8.31"
version = "0.8.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3"
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.31"
version = "0.8.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a"
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
dependencies = [
"proc-macro2",
"quote",
+4
View File
@@ -1,3 +1,7 @@
# Standalone crate pinned to a published lancedb release, not part of the root
# workspace. Without this, cargo commands here fail to resolve the workspace.
[workspace]
[package]
name = "rs"
version = "0.1.0"
+18
View File
@@ -158,6 +158,24 @@ list, create and drop databases across the whole deployment. Its
`connect_database(name)` and `create_database(name)` then return the same
kind of database connection `lancedb.connect()` does.
In Python, `connect_catalog` and `connect_catalog_async` accept the same
connection settings as their database counterparts. Use `host_override` to
share settings that include a `db://` URI; the catalog connection targets
the root of that deployment and ignores the database name. An explicitly
supplied `region` is ignored with a warning, since the HTTP(S) endpoint
selects the deployment. Embedded-only session and namespace settings are
unsupported.
```python
settings = {
"uri": "db://analytics",
"api_key": "secret",
"host_override": "https://my-server.example",
}
db = lancedb.connect(**settings)
catalog = lancedb.connect_catalog(**settings)
```
This connection is for database administration, not table or query work:
list, create and drop databases through it, then switch to a **database**
connection for everything else -- tables, queries, and SQL all run within a
+73
View File
@@ -33,6 +33,46 @@ print(job.status())
```
</CodeGroup>
## Cached properties and live calls {#snapshots}
Python job properties describe the last observation; reading them does not
contact the server. Submission need not fetch the full registry record, so
some properties can initially be `None`.
| Surface | Contract |
| --- | --- |
| `state` | Last observed lifecycle state. It does not update on its own. |
| `job_type`, `creation_ms` | Cached job kind and creation time in epoch milliseconds. |
| `spec` | Complete, job-specific submitted specification. Read this separately from the bounded `repr(job)` display. |
| `result` | Cached, job-specific reported data; it is not necessarily the typed object returned by `wait()`. |
| `failure` | Cached `JobFailureInfo`, when the server reports a terminal failure. |
| `status()` | Live lifecycle request. For registry jobs it also caches the full record. A failed state is returned without raising a job-failure exception; request errors can still raise. |
| `refresh()` | Fetch and cache the current record without waiting for completion. |
| `events(...)` | Separate live request returning a `pyarrow.Table` of recorded events; it does not refresh the properties. |
| `wait(...)` | Poll until completion and return the operation's typed result, or raise on failure/cancellation. Refresh afterward when you need the complete final registry record. |
For example, poll a registry handle and then retrieve its final details:
```python
import time
state = job.status()
while state == "running":
print(job.state)
time.sleep(2)
state = job.status()
result = job.wait()
job.refresh()
print(result)
print(job.spec)
```
The four lifecycle strings below are the usual SDK contract; newer server
states may pass through an older client. Do not infer execution progress from
`state` alone. Structured progress methods and queue fields require matching
SDK/server support; see [refresh admission](/feature-engineering/refresh-column#admission).
## Submit and wait for a job {#waiting}
1. **Submit the operation.** Keep the returned job handle. For an Enterprise
@@ -133,6 +173,39 @@ for info in db.list_jobs(page_limit=50):
```
</CodeGroup>
`list_jobs` yields `JobInfo` summaries, newest creation time first, rather than
live `Job` handles. Open an ID to inspect its full record. `page_limit` bounds
each server request, not the total yielded items, and `page_token` resumes a
listing. It is a lazy iterator: iteration performs requests and can raise
request errors. To materialize it, use `list(db.list_jobs(...))`; it does not
support list indexing, `len()`, or a `.to_list()` method.
`Listing.num_page_results()` reports cached items remaining in the current
page and `Listing.page_token()` reports the next request's token. Drain the
cached items before saving that token, or resuming can skip them. A `None`
token after the final page can coexist with unread cached items. A resumed
listing is not a transactionally frozen view of jobs submitted in the meantime.
`events.schema` describes the Arrow response. Use `events.to_pylist()` for
Python row dictionaries. Common event columns are `event_seq` (int64), `state`
(string), `updated_at_millis` (int64), `updated_by` (string), and nullable
`emitted_from`, `emitted_by` and `claim_entity` strings. Optional uint64 work
counters such as `rows_processed` and diagnostic details depend on job type
and server version. If a `payload` column is returned, its value is a nullable
JSON string, not an already decoded Python dictionary.
Empty results retain their schema. Events are newest first and belong to the
requested job; child events are separate. An event count is not a completed-row
count, and a running job can have no terminal `result` while producing events.
For a Function refresh, `wait()` returns a `RefreshColumnResult` such as
`rows_assigned`, `rows_failed`, `rows_remaining`, `source_version` and optional
`published_version`. Other job types have different results. Do not parse the
printed representation to recover a spec, result or progress measurement.
For object-shaped registry data, `job.spec` and `job.result` are decoded Python
dictionaries: access fields with keys, such as `job.result.get("summary")`
after refreshing a successful Function job. The separate typed object from
`wait()` uses attributes, such as `result.rows_assigned`.
Event responses have [row limits](/basics/limits#jobs). An explicit limit can
request more than the default, but it does not guarantee a complete event
history.
+1 -1
View File
@@ -76,4 +76,4 @@ boundaries).
- [Multimodal data and blobs](/management/table#multimodal): declare `lancedb.blob()` columns and read blobs on demand.
- [Table versioning](/management/table#versioning): read and manage table versions.
- [Computed columns](/feature-engineering/add-computed-column): add derived features to your data.
- [Architecture](/index#architecture): how LanceDB Embedded and Enterprise build on Lance.
- [Embedded vs Enterprise](/basics/embedded-vs-enterprise): how LanceDB Embedded and Enterprise build on Lance.
+1 -1
View File
@@ -53,7 +53,7 @@ without a LanceDB SDK. For SQL queries, connect through
LanceDB's Java client builds on this Lance Namespace Java core: table creation,
listing and most other catalog operations go through the generated
`LanceNamespace` interface talking to Enterprise's Namespace endpoint.
The [real time engine](/tables/realtime-engine) is the one area with its own,
The [Realtime Engine](/tables/realtime-engine) is the one area with its own,
LanceDB-specific Java client on top, since RTE's LSM write path is not part of
the Lance Namespace Client SDK Specification.
+58 -3
View File
@@ -44,6 +44,58 @@ table.add_columns({"doubled": version(value=col("value"))})
immutable version, so changing one produces a new version rather than
altering rows a previous version already filled.
## Supported Function signatures {#signature-types}
A table's [Arrow schema](/sql/data-types#supported) can contain types that a
Function cannot accept or return. The matrix below describes the Python SDK
`0.42.0-beta.12` source contract. Nested schemas and list-Blob outputs require
a matching Enterprise server; an SDK upgrade alone does not enable them.
| Arrow type | Function input/output support |
| --- | --- |
| Boolean; signed/unsigned 8, 16, 32, 64-bit integers; float16/32/64 | Supported. Ordinary `int` and `float` annotations infer int64 and float64. |
| utf8 / large_utf8; binary / large_binary | Supported. `str` and `bytes` infer utf8 and binary. Plain binary does not carry Blob semantics. |
| date32 / date64 | Supported; Python `date` infers date32. |
| timestamp, with or without timezone; time32/64; duration; interval | Unsupported by the Function signature grammar. A Python `datetime` annotation can resolve to an Arrow timestamp but registration still rejects it. |
| decimal; map; dictionary; union; fixed-size binary | Unsupported. Decode dictionary values and use supported scalar/list/struct representations. |
| struct; list / large_list; positive-length fixed-size list | Supported with supported children. Explicit schemas preserve child nullability; annotation-only `list[T]` uses non-nullable elements. Struct fields must be nonempty and uniquely named. |
| Blob v2 at top level or in a struct | Supported in inputs and outputs; use `lancedb.blob(...)` in the schema. |
| Blob v2 under list / large_list | Output only on supporting SDK/server versions. Inputs are rejected. |
| Blob v2 under fixed-size list or map | Unsupported in both directions. |
For times, pass an int64 epoch value with an explicit unit such as microseconds,
or a UTF-8 ISO 8601 string with its timezone. Convert inside the Function and
cast the result in SQL if needed. Use scaled integers with a declared scale
when exact decimal values matter; converting to float can lose precision.
Represent a map as a list of key/value structs when that fits the calculation.
A scalar output is non-nullable because physical NULL represents an unfilled
computed output. For an optional value, return a named struct with a nullable
field, for example:
```python
import pyarrow as pa
from lancedb import function
@function(
input_schema=pa.schema([pa.field("text", pa.string(), nullable=False)]),
output_schema=pa.schema([pa.field("score", pa.float64(), nullable=True)]),
)
def optional_score(text: str):
return {"score": float(len(text)) if text else None}
```
Return a dictionary by field name. A successfully computed nullable field can
be NULL; `score IS NULL` alone cannot distinguish it from pending work or a
skipped failure. Use the job result and error diagnostics. Do not assume an
explicit assignment-state flag is available on every deployment.
List-nested Blob outputs are queryable as descriptors, but row-ID blob fetch
APIs and `blob_mode="bytes"` do not fetch payloads inside lists. Prefer a
separate row per media item when you need independent reads, retries or
re-scoring. A plain struct shaped like a Blob without its extension metadata
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
@@ -170,9 +222,12 @@ in the function's source. A Secret is a database-scoped named credential:
puts it in the environment variable the function reads, without ever
returning it from any API or recording it in the function's own definition.
Combine it with the stateful form so the HTTP client -- and any rate limiter
around it -- is built once, not reopened on every row. There is no built-in
retry or per-row error-skip policy -- a function that calls a flaky service
should handle timeouts and retries itself, inside `__call__`.
around it -- is built once, not reopened on every row. Configure HTTP timeouts
inside `__call__`. Refresh-level `error_policy='skip'` can record row failures;
see [handling failures](/management/function#failures). Native retry policies
need matching SDK, server and Function-image support; on other deployments,
handle bounded retries inside the Function only when repeating the request is
safe.
See [Vend a Secret to a Function](/curation/vend-secret#specify) for the
full worked example, how the bound value actually reaches a running
+53 -5
View File
@@ -136,12 +136,60 @@ SELECT * FROM dedupe(
See [Refresh a materialized view](/feature-engineering/refresh-materialized-view)
for manual and automatic refresh options to keep it current as new records land.
## At production scale {#production}
## Index, snapshot and recall limits {#limits}
[LeRobotDataset](/integrations/lerobotdataset) runs the same `dedupe`
call over 27.6 million real embedding rows to remove near-static frames from a
robotics training set in under 30 seconds -- the mechanism does not change
with scale, only the table it runs against.
These are Enterprise SQL table functions, not standard SQL or a registered
Python Function. They require one compatible current vector index covering
the scanned snapshot. Wait for indexing to finish after ingestion and inspect
index coverage before running a full scan. Unindexed fragments are rejected;
deleted rows are excluded at the pinned dataset version.
The scan compares candidates **within each physical IVF partition and index
segment**. It does not compare across partitions or segments. Scanning every
partition therefore does not establish global all-pairs recall. Quantized
indexes compare their encoded vector representations; `IVF_FLAT` compares the
stored vectors. Thresholds must match the index's metric: L2 is squared L2,
cosine is `1 - cosine`, dot distance is `1 - dot`, and Hamming counts differing
bits. Inspect close examples and known duplicates before choosing a threshold.
`duplicate_pairs` reports `dataset_version`, `segment_id` and `partition_id`.
Retain those with the index configuration and source version when comparing
runs. Pass `id_column` for application IDs, rather than treating physical row
addresses as durable identifiers. A new append, index change or bridge between
components can change groups and representatives.
## Efficient use and scale qualification {#production}
Start with [`duplicate_pairs` partition sampling](/sql/dql/duplicate-pairs#sampling),
using a recorded seed and a bounded partition count. Inspect pair density and
threshold quality before running `dedupe`, which always scans every partition.
Sampling partitions is not uniform row sampling and can miss rare groups.
`resolution='connected_components'` merges transitive chains;
`direct_representative` uses direct representative relationships instead.
Pair work grows quadratically within dense partitions, and a loose threshold
can emit a quadratic number of edges. An outer `LIMIT` is not a resource
budget for upstream pair finding or group resolution. Avoid repeatedly
materializing all pairs in a Python list; select needed columns, aggregate on
the server, and persist a reviewed result when repeated reads justify it.
Measure peak memory, spill storage, elapsed time and pair count on
representative partitions before increasing scope.
The [LeRobotDataset integration](/integrations/lerobotdataset) illustrates a
27.6-million-row data workflow. Its timings are not a versioned qualification
of this deduplication path on arbitrary indexes or hardware. A 10-billion-row
run is not qualified by that example. Qualify source/index versions, partition
sizes, metric, threshold, worker resources, spill limits and correctness on your
deployment before extrapolating. There is no universal row-count or latency
guarantee in this guide.
For text shingles and MinHash signatures, use the distinct
[MinHash workflow](/enterprise/sql-minhash). Vector distance deduplication and
MinHash/Jaccard text deduplication have different indexes and thresholds.
Agents can follow the repository's
[vector deduplication skill](https://github.com/lancedb/lancedb/blob/main/.agents/skills/lancedb-vector-dedup/SKILL.md)
to apply these checks without inventing Function options or scale guarantees.
## Continue with the curated data {#next}
+2 -1
View File
@@ -81,7 +81,7 @@
},
{
"source": "/basics/offerings",
"destination": "/#architecture"
"destination": "/basics/embedded-vs-enterprise"
},
{
"source": "/enterprise/deployment",
@@ -496,6 +496,7 @@
"management/materialized-view",
"management/secret",
"management/function",
"management/function-failures",
"management/storage-integration"
]
},
@@ -10,7 +10,7 @@ keywords: ["kubernetes", "k8s", "aks", "deployment", "helm"]
This page describes a LanceDB Enterprise capability. The embedded form
of LanceDB has no server to provide it. See
[Architecture](/index#architecture) for what differs between the two.
[Embedded vs Enterprise](/basics/embedded-vs-enterprise) for what differs between the two.
The Kubernetes deployment procedure is published with LanceDB Enterprise. See
[LanceDB Enterprise](/enterprise#deployment) for the general shape, and
@@ -1,7 +1,7 @@
---
title: "Distributed RTE Read"
sidebarTitle: "Distributed RTE Read"
description: "How a query combines the real time engine's fresh tier with the ordinary distributed query-serving path, machine to machine."
description: "How a query combines the Realtime Engine's fresh tier with the ordinary distributed query-serving path, machine to machine."
icon: "network-wired"
availability:
embedded: unavailable
@@ -3,7 +3,7 @@ title: "Distributed RTE Write"
sidebarTitle: "Distributed RTE Write"
description: "How Enterprise scales RTE writes horizontally across a dedicated serving tier, and the throughput limits that come with it."
icon: "bolt"
keywords: ["rte", "real time engine", "shard", "sharding", "horizontal scaling", "write throughput"]
keywords: ["rte", "realtime engine", "shard", "sharding", "horizontal scaling", "write throughput"]
availability:
embedded: unavailable
enterprise: available
@@ -128,7 +128,7 @@ throughput than this provides.
<Card title="RTE Write (Upsert)" icon="bolt" href="/ingestion/realtime-write">
Enable RTE and write to a table; the same call on Embedded or Enterprise.
</Card>
<Card title="How the real time engine works" icon="database" href="/tables/realtime-engine">
<Card title="How the Realtime Engine works" icon="database" href="/tables/realtime-engine">
MemWAL, shards, memtables and SSTables -- the shared architecture.
</Card>
<Card title="Distributed RTE Read" icon="magnifying-glass" href="/enterprise/distributed-real-time-read">
@@ -1,7 +1,7 @@
---
title: "Real Time Engine compaction"
title: "Realtime Engine compaction"
sidebarTitle: "RTE Compaction"
description: "How Enterprise automatically folds a Real Time Engine shard's SSTables into the base table and catches its indexes up."
description: "How Enterprise automatically folds a Realtime Engine shard's SSTables into the base table and catches its indexes up."
icon: "compress"
availability:
embedded: unavailable
@@ -11,7 +11,7 @@ availability:
[Distributed Compaction](/enterprise/distributed-compaction) merges small
base-table fragments and reclaims deleted rows -- the same operation
[Compaction](/maintenance/compaction) describes for LanceDB Embedded. A
table with the [real time engine](/tables/realtime-engine) enabled has a
table with the [Realtime Engine](/tables/realtime-engine) enabled has a
second, unrelated compaction: folding a shard's accumulated SSTables into
the base table and catching the base table's indexes up over the rows that
just landed. This produces two job types, `memwal_compaction` and
@@ -176,9 +176,9 @@ manifest update in step 6 is the single point where a row's SSTable copy
stops being listed, and it only commits after `merge_insert` has already
written that row into the base table.
A table queried *without* the real time engine's live path only sees data
A table queried *without* the Realtime Engine's live path only sees data
once it has been folded into the base table, so its staleness bound tracks
whichever trigger fires -- wider either way than the real time engine's
whichever trigger fires -- wider either way than the Realtime Engine's
own millisecond-scale freshness. A shard under steady write pressure
compacts on the count or bytes trigger, within `WAL_COMPACTION_INTERVAL_SECS`
plus the compaction job's own runtime. A shard that never gathers enough
@@ -197,7 +197,7 @@ for what a live RTE read sees instead.
## What to read next {#next}
<CardGroup cols={2}>
<Card title="Real Time Engine" icon="bolt" href="/tables/realtime-engine">
<Card title="Realtime Engine" icon="bolt" href="/tables/realtime-engine">
The MemWAL format, shards, and WAL nodes this page assumes.
</Card>
<Card title="Distributed Compaction" icon="compress" href="/enterprise/distributed-compaction">
+1 -1
View File
@@ -10,7 +10,7 @@ keywords: ["compliance", "security", "soc2", "encryption", "audit"]
This page describes a LanceDB Enterprise capability. The embedded form
of LanceDB has no server to provide it. See
[Architecture](/index#architecture) for what differs between the two.
[Embedded vs Enterprise](/basics/embedded-vs-enterprise) for what differs between the two.
Compliance posture (certifications, data residency, encryption at rest and in
transit, audit logging) is a property of a deployment, so it is documented
@@ -13,6 +13,13 @@ import {
PySchemaAddSetup,
} from '/snippets/tables.mdx';
<Note>
Declare computed columns on ordinary tables. A materialized view derives its
schema from its query; include the calculation in the view's `SELECT` instead
of attaching a Function with `add_columns`. See
[materialized-view schema changes](/feature-engineering/materialized-views#schema-changes).
</Note>
Lance can write a new column without rewriting the columns already in the
table. That matters most on a table that also holds large images, video or
embeddings, where rewriting everything just to add one small derived field
@@ -20,19 +20,19 @@ In SQL this is [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view#create).
## Create a view {#create}
A materialized view is defined by a SQL query, so it is created with one.
From Python, run the statement on an [Enterprise connection](/basics/catalog#enterprise)
with [`execute_query`](/basics/sql#sql-from-python); the SQL is the same
either way:
From Python, pass the defining query to `create_materialized_view` on an
[Enterprise connection](/basics/catalog#enterprise):
<CodeGroup>
```python Python icon="python"
db.execute_query("""
CREATE MATERIALIZED VIEW frames_captioned AS
SELECT frame_id, video_id, ts, caption
FROM frames
WHERE selected = true
""").read_all()
view = db.open_materialized_view("frames_captioned")
view = db.create_materialized_view(
"frames_captioned",
query="""
SELECT frame_id, video_id, ts, caption
FROM frames
WHERE selected = true
""",
)
```
```sql SQL icon="database"
@@ -43,9 +43,11 @@ WHERE selected = true
```
</CodeGroup>
`execute_query` returns once the result stream is readable, not once the
statement has finished, so `.read_all()` waits out the full creation before
the next line opens it.
`create_materialized_view` waits for creation and initial population, then
returns the view handle. Use `create_materialized_view_async` to submit a job
and wait for it separately. Both methods accept `query=` on synchronous and
asynchronous connections. `query` cannot be combined with `source`, `select`,
`where`, or `limit`; put those clauses in the query itself.
The query defines the view: here, the `frames` table's `frame_id`,
`video_id`, `ts` and `caption` columns, filtered to the frames selected for
@@ -174,6 +176,30 @@ definition is read with `await view.definition()`.
Creation, refresh and drop also have async, job-returning SDK methods; see
[Materialized view](/management/materialized-view#manage).
## Add derived values to a view {#schema-changes}
A materialized view's output schema belongs to its defining `SELECT`. Do not
use `view.table.add_columns(...)` to attach another computed or Function column
to that output. In particular, adding a Function binding is rejected: the
column would not be produced by the next view refresh.
Choose where the calculation belongs:
- Include the expression or Function call in the view's `SELECT`, as in the
[caption example](#functions). To change an existing definition, create a
replacement view under a new name, check its results, indexes and grants,
and move readers to it before dropping the old view.
- Add a Function column to the ordinary source table, refresh it, then select
that stored column in a view. This lets you manage column refresh separately
from view refresh.
- Create an ordinary table from a query when you need independently editable
outputs. That table is a snapshot; it does not inherit the view's refresh
relationship to the source.
Opening the underlying table gives access to reads and indexes; it does not
make independent schema changes part of the materialized-view definition.
Changing automatic-refresh settings also does not change that definition.
## Related guides {#next}
<CardGroup cols={2}>
@@ -77,6 +77,11 @@ catch-up works when it's re-enabled after being off.
## Refreshing part of a table {#partial}
Python `where=` requires a supporting SDK, such as `0.42.0b9`, and an
Enterprise server with filtered refresh support. Stable `0.41.0` does not
accept this argument. The SQL form is available independently of that Python
argument on supporting servers.
<Badge color="red">Enterprise</Badge> A refresh can be scoped to a predicate,
with `where=` in Python or `WHERE` in SQL, which is useful for filling a slice
first and checking it before committing to the whole table:
@@ -123,6 +128,89 @@ to let LanceDB track which outputs need updating.
`function_refresh` for one filled by a registered [function](/management/function).
</Note>
### Re-score selected list elements {#list-elements}
`WHERE` selects **rows**, not elements within a list. Refreshing a row that
contains ten answers passes the whole list to the Function. A mask can control
which elements your code computes, but the Function still returns one complete
list for that row. There is no element-level refresh or partial-list write API.
This example keeps `sample_id` as the link to an existing `samples` table with
a Blob column named `media`. It creates only answer metadata and scores; it
neither reads nor copies Blob payloads. Run it on a deployment supporting
`@function`, list signatures and Python `where=`, with `samples` already
containing sample IDs `s1` and `s2`.
```python
from lancedb import col, function
media_before = db.execute_query(
"SELECT sample_id, media FROM samples "
"WHERE sample_id IN ('s1', 's2') ORDER BY sample_id"
).read_all().to_pylist()
answers = db.create_table("answer_rescore_demo", [
{"group_id": "g1", "sample_id": "s1",
"answers": ["yes", "maybe", "no"],
"selected": [False, True, False], "previous": [0.1, 0.2, 0.3]},
{"group_id": "g1", "sample_id": "s2",
"answers": ["other"], "selected": [False], "previous": [0.4]},
])
@function
def rescore_masked(
answers: list[str], selected: list[bool], previous: list[float]
) -> list[float]:
if not (len(answers) == len(selected) == len(previous)):
raise ValueError("answers, selected and previous must have equal lengths")
return [
float(len(answer)) if choose else old
for answer, choose, old in zip(answers, selected, previous)
]
version = db.create_function(rescore_masked)
answers.add_columns(
{"rescored": version(
answers=col("answers"), selected=col("selected"), previous=col("previous")
)},
auto_refresh_enabled=False,
)
job = answers.refresh_column_async("rescored", where="sample_id = 's1'")
job.wait()
rows = answers.search().select(
["group_id", "sample_id", "previous", "rescored"]
).to_list()
by_sample = {row["sample_id"]: row for row in rows}
assert by_sample["s1"]["group_id"] == "g1"
assert by_sample["s1"]["rescored"] == [0.1, 5.0, 0.3]
assert by_sample["s1"]["previous"] == [0.1, 0.2, 0.3]
assert by_sample["s2"]["rescored"] is None
assert by_sample["s2"]["previous"] == [0.4]
media_after = db.execute_query(
"SELECT sample_id, media FROM samples "
"WHERE sample_id IN ('s1', 's2') ORDER BY sample_id"
).read_all().to_pylist()
assert media_after == media_before
```
Here length is a deterministic stand-in for a scorer. Only `"maybe"` is scored;
the other scores are copied from `previous`. The final equality checks Blob
descriptors on an otherwise unchanged source table, without fetching payloads.
Keep the source table unchanged during this comparison. Use the same model,
normalization and score type as the original computation in a real re-scoring
pass. For another pass, explicitly supply the intended prior scores and mask;
refresh does not merge the previous output into your Function's inputs.
If answers need independent retries or versions, prefer one ordinary table row
per answer, with `group_id`, `sample_id`, a stable application `answer_id`,
answer text and score. Keep media in `samples` and join by `sample_id` when
needed. A row predicate can then select exact answer IDs, and Blob storage
stays in the source table. Do not use `UNNEST` to assume that nested Blob values
become supported Function inputs; see the
[nested-Blob limits](/curation/create-function#signature-types).
## Run a refresh on Enterprise {#async}
<Badge color="red">Enterprise</Badge>
@@ -212,6 +300,31 @@ The wait helpers do not submit or cancel a refresh. They retry only the typed
finalization-pending response and propagate other errors.
*/}
### Admission and waiting {#admission}
Submission does not reserve a supervisor or GPU immediately. A refresh can wait
for source preparation/compaction, an earlier refresh, executor admission or
worker capacity. A lifecycle `running` value from `status()` alone does not
prove that Python code has begun executing.
Use [`SHOW JOBS`](/sql/ddl/job#show) and the Console's job detail to inspect
available phase and row progress. On SDK/server versions with `job.progress()`,
the snapshot can also include `phase`, `queue_reason`, timestamps and row
counters. These optional fields are version-dependent; missing values are
unknown, not zero progress or an ETA. `creation_ms` is submission time, not
worker start time. `DESCRIBE JOB` provides the finished run report, rather than
a live queue-position API.
Limits are deployment settings: the Agent dispatcher concurrency, executor
capacity, per-table automatic-refresh limit and Function-call
`max_concurrency` control different things. There is no universal five-refresh
limit per database. Ask your administrator for the effective settings and use
the [Enterprise operations guide](/enterprise/function-operations#admission)
for their configuration names. Repeated cancellation and resubmission does not
bypass those limits. Cancellation requests a stop, including while queued;
observe a terminal state before submitting replacement work. Committed work
is not rolled back.
### Configure workers and resources {#resources}
SQL exposes the worker budget directly, which is the lever when a backfill is
@@ -229,6 +342,12 @@ up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the fleet. They are not
per-worker allocations or a guaranteed worker count. `num_workers` is only
accepted for SQL-expression columns; registered Function columns reject it.
In particular, `gpu_count = 2` does not request two devices inside one Python
process or enable tensor parallelism. Inspect configured GPU classes and their
per-worker limits with `db.list_gpu_classes()` or `SHOW GPU CLASSES`. Choose a
model that fits the worker shape supported by your deployment; see
[GPU placement and budgets](/enterprise/function-operations#gpu).
The SDKs accept the same nested budget. CPU and memory are required; the GPU
count inside the budget defaults to zero, so a CPU-only Function can omit it:
+43 -114
View File
@@ -6,130 +6,59 @@ icon: "/static/assets/logo/lancedb-icon-gray.svg"
keywords: ["multimodal lakehouse", "training", "feature engineering", "search", "open source", "oss"]
---
**LanceDB** is a [multimodal lakehouse](https://lancedb.com/blog/multimodal-lakehouse/) for AI teams that need
one data layer for curation, feature engineering, search and retrieval, and model training.
It is built on top of [Lance](/basics/lance), an open-source lakehouse format designed for multimodal AI data.
LanceDB Enterprise is a distributed multimodal lakehouse for AI. It gives you one data layer for search and
retrieval, curation, feature engineering, and model training. It is built on [Lance](/basics/lance), an open-source
columnar format for multimodal AI data. For the open-source retrieval library that runs inside your application,
see [LanceDB Embedded](/basics/lancedb-embedded).
Move from data exploration to model training on one unified platform without needing to manage a
fragmented stack of storage, feature, retrieval, and training systems.
LanceDB Enterprise depends only on object storage for its primary state, and NVMe/memory for caching in the serving
layer, giving it the latency profile of an in-memory database with the petabyte scalability and cost profile of S3.
It brings these workloads into one system, giving your team one system to become expert in and removing the need
for multiple database systems and synchronization pipelines between them.
## Train on the right data faster {#train-on-the-right-data-faster}
Core features include:
Search, curate, and train at petabyte scale, with all your multimodal data in one table.
- [**SQL**](/basics/sql) powered by Apache DataFusion
- [**Secondary indexes**](/indexing) for vector search, full-text search, and scalar filters
- [**Computed columns**](/feature-engineering/add-computed-column) with on-demand or scheduled refresh
- [**Materialized views**](/feature-engineering/materialized-views) with on-demand or scheduled refresh
- [**Time travel and versioning**](/management/table#versioning) to pin and revisit datasets
- **Search**: [vector](/search/vector-search), [full-text](/search/full-text-search), and
[hybrid](/search/hybrid-search), with [filters](/search/filtering) and [reranking](/reranking)
- [**Functions**](/curation/create-function) for custom transformations and model inference (early access)
- [**Row-level random access**](/basics/lance#capabilities) for retrieval and training
- [**Column additions**](/management/table#schema-add-new-columns) without rewriting existing columns
Preparing training data and running experiments slow down when raw data, metadata, embeddings, features, and governance
artifacts live in separate systems. LanceDB keeps them together in one versioned multimodal table, so AI teams spend less
time stitching infrastructure together and more time improving datasets, testing features, and keeping GPUs fed.
{/*
Draft until branching reaches early access. Add this item to the list above, after Time travel and versioning:
- [**Copy-on-write branching**](/tables/branching) that gives each experiment or agent a writable fork of a table to review before it reaches `main`
*/}
## Accelerate the data flywheel for model research {#accelerate-the-data-flywheel-for-model-research}
LanceDB Enterprise stores images, video, audio, text, embeddings, and metadata in
[schema-enforced tables](/management/table#multimodal). These features let you build
declarative ML data pipelines: ingest raw data and metadata, enrich it incrementally with computed columns and
Functions, and organize it into [curated datasets](/curation) with materialized views. Add features without
rewriting existing columns, then train from those datasets using row-level random access and sampling.
Keep your AI data in one table.{/* Draft until branching reaches early access: restore ", and give each agent-driven experiment its own isolated branch" before the period. */}
Find the failure, fix the data, and retrain.
Connect through [SDKs](/basics/sdk) for Python, TypeScript, and Rust, and use the
[PyTorch data loader](/training/data-loading) for reproducible shuffling and streaming batches.
<Steps>
<Step title="Find a curated training subset for every failure case">
Start from one failed grasp or evaluation example. [Search](/search/) multimodal data, metadata, and embeddings
together, retrieve similar examples, and [curate](/curation) them into a targeted training subset.
</Step>
{/*
Draft until branching reaches early access.
## Architecture {#architecture}
<Step title="Data sandboxes for safe agentic experimentation">
Don't let an agent silently corrupt your data and ruin a training run. Give each agent its own
[branch](/tables/branching), a writable fork of the table, to experiment on, and review the changes before
they reach `main`. See [Run experiments on branches](/agent-branch-experiments).
</Step>
*/}
<Step title="A single dataset for every modality">
Keep episodes, frames, metadata, features, and embeddings together in one schema-enforced table, without
pipelines to keep them in sync. Table [versions](/management/table#versioning) let you trace each training
run back to the exact data it used.
</Step>
<Step title="More hillclimbing, less babysitting preprocessing jobs">
Define the [computed columns](/feature-engineering/add-computed-column) and
[materialized views](/feature-engineering/materialized-views) your experiment needs, such as extracted features
or embeddings, and refresh them as your data changes. On LanceDB Enterprise, column refreshes run as background
jobs on the cluster instead of in your code.
</Step>
<Step title="Higher GPU utilization, faster convergence">
Keep GPUs fed. [`StreamingDataset`](/training/data-loading) streams multimodal training data into PyTorch with
globally shuffled, deterministic batches, combining fast random access with high-throughput scans.
</Step>
</Steps>
Queries and feature engineering run across a cluster, with background indexing and maintenance. Deploy
LanceDB Enterprise in your cloud or use a LanceDB-managed deployment.
Use the same table to curate training data, add derived features, retrieve examples, and feed training jobs that rely on expensive GPUs.
Training workloads can sample, shuffle, and scan projected columns from local storage or object storage, then assemble
GPU-ready batches from a tagged dataset version. Training pipelines need curation, derived features, reproducible
splits, fast random access, and a clean path into frameworks such as PyTorch -- LanceDB keeps all of it connected
through the same table model, whether a workflow uses one table or several related ones.
## Architecture: Embedded and Enterprise {#architecture}
LanceDB ships as two offerings on the same [Lance](/basics/lance) format and table model, which stores table data,
versions, and indexes in open, columnar files. What changes between them is how storage and compute are organized
around that format: start locally with Embedded, then move to Enterprise when your team needs distributed scale,
managed infrastructure, private deployment, or higher-throughput curation, feature engineering, search and
retrieval, and training workflows.
<CardGroup cols={2}>
<Card title="LanceDB Embedded" icon="cube" href="/basics/lancedb-embedded">
An open-source, embedded retrieval library that runs inside your application process, with no separate
database server to deploy.
</Card>
<Card title="LanceDB Enterprise" icon="server" href="/enterprise/index">
A distributed multimodal lakehouse service for production workloads that need managed infrastructure and
higher-throughput workflows.
</Card>
</CardGroup>
See [Embedded vs Enterprise](/basics/embedded-vs-enterprise) for a feature-by-feature comparison, including
architecture, latency, throughput, and day-to-day usage differences.
Your application connects to the service through an SDK or [SQL client](/basics/sql). The cluster executes queries,
refreshes derived data, and maintains tables and indexes outside your application.
## Projects using LanceDB {#projects-using-lancedb}
### Training {#training}
- [stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) -- a platform for reproducible world-model
research built on a LanceDB data layer, reporting 3-4x faster data loading on Push-T versus HDF5 / MP4 at a
fraction of the disk footprint.
- [le-wm](https://github.com/lucas-maes/le-wm) -- a joint-embedding predictive world model from pixels, trained on
the stable-worldmodel platform and its LanceDB data layer.
- [lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb) -- a drop-in LanceDB backend for HuggingFace
LeRobot datasets with faster loading across robotics datasets.
### Agentic applications {#agentic-applications}
- [OpenClaw LanceDB Plugin](https://docs.openclaw.ai/plugins/memory-lancedb) -- stores an agent's long-term memory
in LanceDB, automatically recalling relevant memories before a model turn and capturing new facts afterward.
- [Cognee](https://github.com/topoteretes/cognee) -- an open-source AI memory platform that gives agents persistent
memory across sessions, using LanceDB as one of its vector store backends.
- [CrewAI](https://github.com/crewAIInc/crewAI) -- a multi-agent framework that
[rebuilt its agent memory on LanceDB](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb).
Across these projects, LanceDB and Lance provide the multimodal data layer that keeps raw observations, annotations,
features, and training or memory access patterns in one format instead of scattering them across task-specific
stores.
## Start with your workload {#start-with-your-workload}
<CardGroup cols={2}>
<Card title="Ingest your data" icon="inbox" href="/ingestion">
Create tables, append records, and update or delete rows as your data changes.
</Card>
<Card title="Build search and retrieval" icon="search" href="/search/">
Use vector search, full-text search, hybrid search, reranking, filtering, and SQL.
</Card>
<Card title="Curate training data" icon="filter" href="/curation">
Profile, sample, chunk, join, and deduplicate records before training on them.
</Card>
<Card title="Engineer features in place" icon="layer-group" href="/feature-engineering">
Derive computed columns and materialized views without moving data elsewhere.
</Card>
<Card title="Load data into PyTorch" icon="boxes-stacked" href="/training/data-loading">
Use LanceDB tables and permutations for projected, shuffled, random-access training reads.
</Card>
<Card title="Manage catalog objects" icon="folder-tree" href="/management">
Create, list, and drop tables, namespaces, and views from Python, TypeScript, or SQL.
</Card>
</CardGroup>
Teams use LanceDB for world-model and robotics training, as in
[stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) and
[lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb), and for agent memory, as in
[CrewAI](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb),
[Cognee](https://github.com/topoteretes/cognee), and
[OpenClaw](https://docs.openclaw.ai/plugins/memory-lancedb).
Try out LanceDB using our [quickstart](/quickstart). For help planning an Enterprise deployment
that meets your scale and performance needs, [contact the LanceDB team](https://www.lancedb.com/contact).
+7
View File
@@ -210,6 +210,13 @@ table.search().where("contains(text, 'needle')").limit(10).to_pandas()
`list_indices()` reports the index type as `"NGram"`.
<Note>
Lance 15.0.0-beta.21 writes new NGram indexes using physical row addresses. On
tables with stable row IDs, rebuild legacy NGram indexes that store row IDs
before consolidating their segments. Consolidation rejects these legacy
row-ID segments. Tables without stable row IDs retain the earlier index format.
</Note>
## Index UUID Columns
LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)`), enabling efficient lookups and filtering on UUID-based primary keys.
+87 -15
View File
@@ -150,6 +150,10 @@ Python and TypeScript report elapsed time in seconds; Rust returns a `Duration`.
The expected row count may be unknown for streaming input. On the final update,
it falls back to the number of rows written.
For remote multipart writes, rows count input scanning, while bytes count
acknowledged IPC parts. Bytes start at zero and a retried part is counted once,
after acknowledgement. Scanned rows and staged bytes do not imply a commit.
Keep callbacks short and use the write operation's result to determine success.
The final `done` update means progress reporting has ended; it can also occur
after a write fails or is cancelled. Input errors before writing starts may
@@ -164,11 +168,29 @@ from a TypeScript callback are logged and do not abort the write.
Wait for the write operation's result, then check the expected records.
Progress callbacks describe activity; they do not establish that a write
succeeded. If a request fails after the server may have committed it, blindly
repeating an append can duplicate rows. The client's automatic retries can do
the same: on an Enterprise table, the Python and TypeScript 0.40.0 clients resend an
append after a retryable status such as `504`, even when the server had already
committed it, and `add()` still returns success. Reconcile using your record
IDs, or choose an upsert policy designed for replay.
repeating an append can duplicate rows. Current clients do not automatically
replay non-idempotent writes after `500`, `502`, `503`, or `504`, or after a
response is lost. A plain `503` does not prove that a write was rejected before
commit. Connection failures before sending, `409` transaction conflicts, and
explicit `429` rate-limit rejections may be retried within `RetryConfig` limits. Idempotent multipart
parts have a separate retry policy described below.
If multipart completion times out, loses its response, or receives a `5xx`, the
error reports **commit outcome unknown**. The client neither aborts the upload
nor resends completion or the input under
a new upload ID: aborting at this point could delete already committed data.
Check the table using your record IDs before retrying the operation.
Configure connection-wide limits with `client_config.retry_config` in Python
(`lancedb.remote.RetryConfig`) or `clientConfig.retryConfig` in TypeScript.
Override the budget for one `add()` with Python `table.add(data, retries=0)`
or TypeScript `table.add(data, { retries: 0 })`. The value must be an integer
between 0 and 255. Rust write builders also provide a per-call override, for
example `table.add(data).retries(0).execute().await?`,
`table.update().retries(0)`, and `table.merge_insert(&["id"]).retries(0)`.
This disables transport retries for that operation, including multipart part
retries; it does not change local transaction conflict handling. Increasing a
retry budget never makes ambiguous commits safe to replay.
## Configure large uploads {#bulk-ingests-into-a-remote-table}
@@ -176,26 +198,41 @@ IDs, or choose an upsert policy designed for replay.
This section applies only to LanceDB Enterprise tables (`db://` connections). LanceDB Embedded writes are unaffected.
When you write to a LanceDB Enterprise table, the client sends the write as one HTTP `insert` request unless it splits the data into more than one partition, which it does for a large input it can measure or when you set [`write_parallelism`](#write-parallelism). A partitioned write goes up as a multipart write: the client cuts each partition into one or more `insert` parts and uploads them under a single upload id. Each part is streamed. Its size and duration still affect resource use and
timeouts: it has to finish within the client read timeout while the server writes it to object storage, so on very large ingests an oversized part can run past that timeout and surface as:
Large measured inputs, unknown-length streams, and explicit parallel uploads use
multipart writes when the server supports them. The client slices large batches
before IPC encoding and buffers each part for replay. A disconnected request,
read timeout, or configured retryable staging status retries exactly the same
upload ID, part ID, and IPC bytes. `RetryConfig.statuses` controls status retries;
an empty list disables them. The default includes `500`, `502`, `503`, and `504`.
The server replaces that part's staged transaction, so losing
its response does not append the rows twice. Exhausting the part retry budget
aborts the uncommitted session; it does not restart the entire upload.
A complete request rejected with a transaction conflict (`409`) or rate limit
(`429`) also triggers best-effort cleanup. Cleanup uses the call's retry budget;
its failure does not replace the original error. Ambiguous completion outcomes
never trigger cleanup or replay.
```text
lancedb.remote.errors.HttpError: operation timed out
```
Part size still affects memory and HTTP timeouts. A single blob row cannot be
split across Arrow batches; a very large row may require a larger timeout and
more memory. No connection-pool or keepalive setting guarantees that a write
response will arrive.
Two environment variables control how a multipart write's parts are cut. Both are picked up automatically by the Python and TypeScript clients, for clients that support these settings:
| Variable | Default | What it controls |
|----------|---------|------------------|
| `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 8 GiB | Maximum size of a single insert part, in LZ4-compressed Arrow IPC bytes. Set to `0` to disable splitting and send one request per partition. |
| `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Maximum wall-clock time, in whole seconds, that any one insert part may stay open. Set to `0` to disable the time-based cut. |
| `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 64 MiB | Target LZ4-compressed IPC bytes per replayable part. A single indivisible row and its IPC schema may exceed the target. `0` disables byte-based cuts and can require buffering a whole partition. |
| `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Time spent filling a replayable payload, in whole seconds. `0` disables time-based cuts. HTTP deadlines are configured separately in `timeout_config`. |
A part is cut after the input batch that reaches either limit, so cuts fall between batches. Lower the byte budget, with smaller input batches, when large ingests hit the read timeout; lower the duration when uploads are slow or throttled and the byte budget isn't the limiting factor.
A part is cut after an encoding slice reaches either limit. Input batches are
sliced to approximately 8 MiB before encoding, preserving row order. Peak
additional memory scales with active writers and the part budget. Lower
`write_parallelism` or the byte budget to reduce memory use.
<CodeGroup>
```bash Bash icon="terminal"
export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=1073741824 # 1 GiB
export LANCE_CLIENT_MAX_REQUEST_DURATION=120 # 2 minutes
export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=33554432 # 32 MiB
export LANCE_CLIENT_MAX_REQUEST_DURATION=30 # payload preparation budget
```
</CodeGroup>
@@ -203,6 +240,41 @@ Splitting into more parts does not change the final table. The server stages the
the write. This upload protocol is separate from repeating an application-level
`add()` after a timeout.
Remote `create_table(name, data)` remains one atomic request, including overwrite
and `exist_ok` modes. The client encodes into an automatically removed temporary
file before sending, rejects payloads larger than 256 MiB of compressed IPC, and
never silently creates an empty table as a fallback. Encoding and input failures
therefore issue no create request. Temporary disk usage is bounded by this budget;
individual oversized rows can still need substantial encoding memory.
For larger imports, create the schema first and upload with progress reporting.
The empty table becomes visible immediately; `add()` commits its rows atomically.
The following examples use an existing connection `db`, an Arrow `schema`, and
input `data` matching that schema (an Arrow reader in Rust):
<CodeGroup>
```python Python icon="python"
table = db.create_table("items", schema=schema)
table.add(data, progress=True)
```
```typescript TypeScript icon="square-js"
const table = await db.createEmptyTable("items", schema);
await table.add(data, {
progress: (p) => console.log(`Rows written: ${p.outputRows}`),
});
```
```rust Rust icon="rust"
let table = db.create_empty_table("items", schema).execute().await?;
table
.add(data)
.progress(|p| println!("Rows written: {}", p.output_rows()))
.execute()
.await?;
```
</CodeGroup>
## Complete write workflow {#complete-example}
<Accordion title="Complete examples: create, append, update, upsert and delete">
+4 -4
View File
@@ -1,15 +1,15 @@
---
title: "RTE Write (Upsert)"
sidebarTitle: "RTE Write (Upsert)"
description: "Enable the real time engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds."
description: "Enable the Realtime Engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds."
icon: "bolt"
keywords: ["rte", "real time engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"]
keywords: ["rte", "realtime engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"]
availability:
embedded: available
enterprise: available
---
The [real time engine](/tables/realtime-engine) puts an LSM-style write tier in
The [Realtime Engine](/tables/realtime-engine) puts an LSM-style write tier in
front of a table, turning many small writes into a few large commits. This
page covers enabling it and writing to a table; for querying an RTE table, see
[RTE reads](/search/realtime-read).
@@ -239,6 +239,6 @@ for the numbers.
- [RTE reads](/search/realtime-read) — query an RTE table
- [Distributed RTE Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales this
- [How the real time engine works](/tables/realtime-engine#memwal-format)
- [How the Realtime Engine works](/tables/realtime-engine#memwal-format)
- [Merge insert](/ingestion/merge-insert)
- [`ALTER TABLE ... SET RTE`](/sql/ddl/table#properties)
+151
View File
@@ -0,0 +1,151 @@
---
title: "Handle Function failures"
sidebarTitle: "Function Failures"
description: "Keep usable outputs, inspect row errors, retry by stable identity and isolate inputs that need attention."
tag: "Early access"
availability:
embedded: unavailable
enterprise: available
---
A Function refresh can encounter a bad row, fail to initialize a model, lose
a worker, or fail while publishing results. These need different remedies.
This guide uses the existing [refresh error policy](/sql/dml/refresh-column#options)
and Python error records; it does not require a new retry or quarantine API.
## Choose a row-error policy {#policy}
The default `fail` stops the job on a row error. `skip` writes null outputs for
failed rows and records errors, subject to the refresh's failure limits:
```python
job = table.refresh_column_async(
"embedding",
error_policy="skip",
max_failed_rows=100,
max_failed_fraction=0.1,
)
result = job.wait()
print(result.rows_assigned, result.rows_failed, result.rows_remaining)
```
Choose limits for your workload; these example limits stop work when more
than 100 rows or more than 10% fail. `skip` does not make initialization,
infrastructure or publication failures successful. If `wait()` raises,
[refresh the job record](/basics/jobs#snapshots), inspect `job.failure`, and
inspect any recorded row errors. A failed/cancelled job can have committed
some output, but retention of every successful call is not guaranteed.
External effects are not rolled back and can be repeated during recovery.
## Inspect and group recorded errors {#inspect}
Scope diagnostics to the job you are investigating:
```python
from collections import Counter
errors = table.function_errors(job_id=job.id, column="embedding", limit=10000)
groups = Counter((r.error_type, r.error_message) for r in errors.records)
for cause, count in groups.most_common():
print(count, cause)
for fragment in errors.fragments:
print(fragment.fragment_id, fragment.rows_skipped, fragment.rows_recorded)
print("listing truncated:", errors.truncated)
```
Each record includes the Function name/version, table version, error type and
message, creation time, and available row identities. `attempts` and traceback
details depend on the server/image version. This client-side grouping counts
only returned detail records. `truncated=True` or fragment summaries with
more skipped than recorded rows mean it is incomplete; do not label it a full
error census. See [`SHOW ERRORS`](/sql/ddl/job#errors) for SQL and its limits.
Records are historical observations, not a deduplicated list of currently
failed rows. Reading errors without `job_id` can include older attempts that
have since succeeded. A null output can mean unfilled, skipped, or a computed
nullable field; output nullness alone is not a current-error test.
## Retry exactly identified rows {#retry}
On tables with stable row IDs, supporting server/SDK versions return
`record.row_id` from the refresh's pinned source version. Keep that table and
branch identity with the records. Compaction can move physical addresses, so
do not derive a row ID from fragment numbers or offsets.
The following deliberately refuses incomplete or unidentified error sets.
Review historical records against the current inputs before using them as a
retry selection. Keep this selection small enough for a SQL predicate.
```python
if errors.truncated or any(f.rows_skipped > f.rows_recorded for f in errors.fragments):
raise RuntimeError("Inspect a narrower job/error set before selecting retries")
if any(r.row_id is None for r in errors.records):
raise RuntimeError("This workflow requires stable row IDs in every error record")
row_ids = sorted({int(r.row_id) for r in errors.records})
if row_ids:
predicate = "_rowid IN (" + ", ".join(map(str, row_ids)) + ")"
retry_job = table.refresh_column_async("embedding", where=predicate)
retry_job.wait()
```
This recomputes every selected live row with the existing binding. It can
repeat a row already repaired since the error was recorded. Inspect the retry
job and its errors afterward; an older record need not disappear. On tables
without stable row IDs, resolve errors to application keys at the recorded
snapshot before retrying. Do not substitute `_rowaddr` after a rewrite.
Python `where=` requires a supporting SDK such as `0.42.0b9`, not stable
`0.41.0`, plus a matching server.
## Repair with a newer Function {#new-version}
Registering a new version does not change an existing column's immutable
binding. To evaluate a fix while retaining old outputs, register the corrected
callable and declare a separate output column. For example, with a corrected
`embed_fixed` callable already defined and a `text` input column:
```python
from lancedb import col
fixed = db.create_function(embed_fixed)
table.add_columns(
{"embedding_repaired": fixed(text=col("text"))},
auto_refresh_enabled=False,
)
if row_ids:
repair_job = table.refresh_column_async("embedding_repaired", where=predicate)
repair_job.wait()
```
Only the reviewed failed-row selection is populated in the new column; other
rows remain unfilled. Compare those outputs before deciding how readers
should use them. This does not promise an in-place upgrade/retry operation or
per-row producing-version lookup for a column containing mixed executions.
Error records' Function versions describe failures, not the provenance of
every successful row.
## Quarantine inputs for review {#quarantine}
Use an application-owned table of source table/branch, recorded table version,
stable row ID or business key, Function version, cause and review disposition.
Keep Blob payloads in the source table; a quarantine entry can refer to their
source identity. Choose an ordinary table name such as `function_quarantine`,
and explicitly exclude its reviewed IDs in subsequent input selections.
Quarantine is an application workflow here: there is no implied built-in
quarantine lifecycle, automatic current-error clearing or exactly-once retry.
Do not delete source rows merely to hide an error. For very large failure sets,
bounded error listings cannot select every row; use a smaller reviewed scope
or wait for a deployment with the required complete selection support.
Native retry policies, full current-error summaries, in-place version upgrades
and materialized-view row-error handling have separate server/SDK prerequisites.
Do not apply `REFRESH COLUMN` options to a materialized view and assume the
same policy; consult the [MV refresh reference](/sql/dml/refresh-materialized-view)
for your deployment's accepted options.
## Continue {#next}
- [Function lifecycle and failures](/management/function#failures)
- [Conditional and list-element refresh](/feature-engineering/refresh-column#partial)
- [Job results and events](/basics/jobs#snapshots)
+71 -7
View File
@@ -111,6 +111,19 @@ with `db.get_function(name, version=...)`. The version may be an integer or
its string form. Omit `version` to resolve and return the latest currently
visible revision.
{/* Draft for the function exist_ok release.
Use `exist_ok=True` on `create_function` or `create_function_async` to return
the existing named version without changing its code, credentials or settings.
This requires a deployment that supports the option. The default retains the
current behavior of registering a new version.
```python
version = db.create_function(embed, exist_ok=True)
```
*/}
<Note>
The SQL command submits an internal `create_function` image-build job and
waits for publication. The SDK returns the SQL query handle. Query handles
@@ -407,6 +420,9 @@ full worked example.
## Failure handling {#failures}
For the full skip, inspect, grouped-error, stable-row-ID retry and quarantine
workflow, see [Handle Function failures](/management/function-failures).
By default, a Function that raises fails the refresh job. Choose how the
refresh handles row errors with its error policy:
@@ -482,6 +498,47 @@ In practice this means a function should be self-contained: take its inputs as
arguments, import what it needs at module level, and avoid capturing state from
the surrounding scope.
### Supported global captures {#captures}
The Python SDK's source packager captures only these literal values:
| Module-level value | Packaging behavior |
| --- | --- |
| `None`, exact `bool`, `int`, `str`, `bytes`, finite `float` | Inlined as a snapshot at registration. |
| Tuples containing only those values, including nested tuples | Recursively inlined. |
| Imported modules, importable functions/classes | Reconstructed as imports; declare their packages in `pip` or `conda`, or ship local source with `code`. |
| Arrow types/schemas, lists, dictionaries, sets, NumPy arrays, non-finite floats, other objects | Not captured as literals. Construct them inside the Function or class. |
For example, a module-level `OUT_TYPE = pa.list_(pa.float32(), 3)` referenced
from the Function body is unsupported. Construct the type where it is used:
```python
import pyarrow as pa
from lancedb import function
@function(
input_schema=pa.schema([pa.field("value", pa.float32(), nullable=False)]),
output_schema=pa.list_(pa.float32(), 3),
)
def make_vector(value: pa.Array) -> pa.Array:
out_type = pa.list_(pa.float32(), 3)
return pa.array([[v, v, v] for v in value.to_pylist()], type=out_type)
```
Decorator schema arguments are serialized as the signature; this restriction
concerns values referenced by the packaged body. For an expensive constant or
model, build it in a class Function's `__init__` and keep it on `self`.
Later mutations of a client global do not update a registered version. Register
a new version to change captured literals or source. The diagnostic fix in
[SDK #4938](https://github.com/lancedb/lancedb/pull/4938) names the unsupported
global and its type; it does not add Arrow/container capture support. There is
no supported arbitrary-object serialization or documented container-size limit
to rely on for those rejected types.
See the [Function type matrix](/curation/create-function#signature-types) for
what can travel as row inputs and outputs rather than captured globals.
Pass `code=[module, ...]` to ship additional helper modules into the same
image, for logic the function imports but that does not belong inlined into
it -- a model-loading helper shared by several Functions, for example.
@@ -499,13 +556,20 @@ def caption(jpeg: bytes) -> str:
</CodeGroup>
Each module in `code` is captured and shipped the same way the function
itself is: as source, snapshotted at registration. Only `.py` source files are
included; package data such as JSON, YAML, prompt, or tokenizer files is not
copied. `@function` warns before registration when it skips such files from a
package in `code`, naming the affected paths. To use a package that includes
the required resources, install it with `pip=` or `conda=` and remove that
package from `code`; otherwise the Python-only copied package shadows the
installed distribution.
itself is: as source, snapshotted at registration. Packages also include regular
data files such as JSON, YAML, prompts, and tokenizer files, including resources
inside vendored subpackages. Resource paths and bytes are preserved for
`importlib.resources` and package integrity checks. Changing a resource changes
the Function artifact's identity. Caches, hidden paths, symlinks, and unsafe
paths are excluded.
Package resources require matching SDK and server support. Upgrade query nodes
and Function image-building workers before registering resource bundles; older
servers reject them. Older SDKs ship only Python source and warn when excluding
package data. On deployments without resource-bundle support, install the
package with `pip=` or `conda=` and omit it from `code` so the copied package does
not shadow the installed distribution. Use environment dependencies for
platform-specific packages and `models=` for large model snapshots.
## Drop it {#drop}
+136 -5
View File
@@ -270,6 +270,18 @@ Renaming is not supported on a local directory connection. In LanceDB Enterprise
whether a table can be renamed or cloned at all depends on how the deployment
stores its catalog.
{/* Draft for the table-clone exist_ok release.
Pass `exist_ok=True` to keep an existing target table, including its data and
version history, instead of reporting a duplicate. The source is used only when
the target is missing. Remote use requires a deployment that supports this option.
```python
db.clone_table("docs_snapshot", source_uri="s3://bucket/db/documents.lance", exist_ok=True)
```
*/}
A **shallow** clone (the default) references the source's data files rather
than copying them, so it is fast and cheap regardless of table size. It is the
practical way to branch an experiment off a known version, or to pin a training
@@ -375,8 +387,16 @@ file, up to 64 KiB by default, and larger values are stored outside it.
A `blob` column keeps metadata separate from the payload bytes, so queries can
filter rows without loading the blobs.
Most queries return descriptors, which contain metadata about the blob instead
of its bytes. You can
{/* Draft for Blob v2 GA. Confirm release status before removing Early access.
Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled
are outside the GA support scope.
*/}
SDK queries return descriptors by default, which contain metadata about the
blob instead of its bytes. Enterprise SQL queries return payload bytes by
default; use `blob_descriptor(column)` to select metadata instead. With an SDK,
you can
[read the bytes in the query results](#multimodal-blob-query-results) or
[fetch them by row ID](#multimodal-read-blobs).
@@ -500,14 +520,41 @@ the default `"lazy"` mode because it would open `BlobFile` handles. Query with
`blob_mode="descriptions"`, then read bytes with `fetch_blobs` or
`fetch_blob_files`.
{/* Draft for the Enterprise Python bytes release. Replace the released instructions above only after SDK and serving-node rollout.
`blob_mode="bytes"` also supports Enterprise queries. The SDK locks all blob
fetches, including streaming batches, to both the version in
`x-lancedb-query-version` and the incarnation/revision identity in
`x-lancedb-query-snapshot`, captured from the same query response. Every payload
request verifies that identity against the actual opened dataset before reading
rows. Concurrent writes therefore preserve the selected payloads. Dropping and
recreating a table, even at the same location and version, cannot substitute the
replacement's bytes: the original snapshot is served or the read fails explicitly.
Upgrade the SDK and every serving node to support snapshot identities. A server
that reports only a numeric query version, a legacy `x-lancedb-version` watermark,
or Arrow schema metadata does not enable deferred bytes. Missing or unsupported
identities raise `NotImplementedError`; use `"descriptions"` until the upgrade is
complete. Ordinary queries, descriptors, and independent `fetch_blobs` calls keep
working. Old SDKs keep their existing behavior and do not gain this protection
from a server-only upgrade. Realtime/MemWAL and historical manifests without a
native transaction identity do not support deferred bytes. Snapshot identities
do not retain old versions; deleting the selected version still fails explicitly.
In-memory tables and namespace `QueryTable` pushdown do not support bytes mode.
On an Enterprise table, sync `Table.to_pandas()` and `Table.to_arrow()` are not
supported; use `table.search()` instead. A query's `to_pandas()` also raises in
the default `"lazy"` mode because remote lazy handles are not supported.
*/}
###### Copy a subset of blob rows {#multimodal-copy-subset}
Blob query results describe the stored payload; they are not the bytes to
insert into another table. These APIs return different values:
SDK descriptors identify stored payloads; materialize the bytes before inserting
them into another table. These APIs return different values:
| Read path | Value |
| --- | --- |
| SQL or an Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. |
| Enterprise SQL | Raw payload bytes by default. |
| An SDK Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. |
| `table.fetch_blobs(column, row_ids)` | Arrow `large_binary` array; `.to_pylist()` gives `bytes` or `None` in the requested order. |
| A Function parameter annotated `lancedb.BlobReader` | Lazy, seekable reader over the input blob, available inside the Function. |
@@ -545,6 +592,50 @@ Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches
for larger subsets; `fetch_blobs` materializes all requested bytes in memory.
For incremental decoding, use `fetch_blob_files` instead.
{/* Draft for the Enterprise Python bytes release. Replace the copy example above when snapshot-bound remote bytes are released.
For Enterprise tables, prefer server-side `CREATE TABLE AS SELECT` or
`INSERT INTO ... SELECT` to copy blobs without a client round trip:
```sql
CREATE TABLE image_subset AS SELECT id, image FROM images WHERE id < 100;
-- To append to an existing destination:
INSERT INTO image_subset SELECT id, image FROM images WHERE id >= 100 AND id < 200;
```
For SDK copies, query with `blob_mode="bytes"` to bind selection and payload
reads to one snapshot. The following example copies up to 100 rows from an
existing `images` table with an integer `id` and a blob `image` column.
```python
import lancedb
import pyarrow as pa
source = db.open_table("images")
hits = (
source.search()
.where("id < 100")
.select(["id", "image"])
.limit(100)
.to_arrow(blob_mode="bytes")
)
subset = db.create_table(
"image_subset",
schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]),
)
if hits.num_rows:
subset.add(hits)
```
Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches
for larger subsets; `fetch_blobs` materializes all requested bytes in memory.
For incremental decoding, use `fetch_blob_files` instead.
Remote bytes mode requires a server that supports snapshot-bound Blob reads.
Older servers and Realtime/MemWAL tables can still return descriptors, but
bytes mode raises an explicit unsupported-operation error before fetching payloads.
*/}
`blob_mode="bytes"` materializes top-level and struct-nested blob columns. It
raises `ValueError` when the selected columns include blobs
inside a list. Select those columns with `blob_mode="descriptions"`, or leave
@@ -579,6 +670,19 @@ overwrite the table, use a separate reader checked out to a fixed version
before querying. Otherwise, an overwrite can invalidate the row IDs used to
fetch bytes and raise `ValueError`.
{/* Draft for the Enterprise Python bytes release. Replace the streaming restrictions above after release.
Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`,
including no blobs inside lists, namespace `QueryTable` pushdown, or query
shapes that cannot preserve their row results. Enterprise queries require a
valid `x-lancedb-query-version` and `x-lancedb-query-snapshot` response headers.
Legacy v1 bytes are limited to
eligible local plain scans. For local queries, if concurrent writers can
overwrite the table, use a separate reader checked out to a fixed version
before querying. Otherwise, an overwrite can invalidate the row IDs used to
fetch bytes and raise `ValueError`.
*/}
###### Optional pandas examples {#multimodal-blob-pandas}
The lazy-handle calls below require pylance. The query example expects `tbl_async`,
@@ -644,6 +748,10 @@ The other fetch methods load bytes directly:
| Whole payloads for a set of rows | `fetch_blobs` | `fetchBlobs` | `fetch_blobs` |
| Byte slices across many rows in one call | `fetch_blob_ranges` | Not available. Use `fetchBlobFiles` and `readRanges`. | `fetch_blob_ranges` |
{/* Draft for the TypeScript cross-row Blob range release. Replace the row above:
| Byte slices across many rows in one call | `fetch_blob_ranges` | `fetchBlobRanges` | `fetch_blob_ranges` |
*/}
- `fetch_blobs` returns the full bytes for each row ID in order. Null blobs
produce null entries, and empty blobs produce empty byte strings.
- `fetch_blob_files` loads bytes when you call `read`, `read_range`, or
@@ -667,6 +775,21 @@ The other fetch methods load bytes directly:
</CodeBlock>
</CodeGroup>
{/* Draft for the TypeScript cross-row Blob range release.
<Info>
Upcoming-release draft: TypeScript adds `fetchBlobRanges` for cross-row slices.
Until that SDK release is available, use `fetchBlobFiles` and `readRanges`.
Server-side batching requires a deployment with the validated range capability;
older servers continue using the descriptor and Range path selected before the
read. An error from the selected batched endpoint is returned without fallback.
A batched call keeps the native snapshot identity from its first range response
across every partition and requires each serving node to verify it. Missing identity
support or a replaced/deleted snapshot fails the whole call; upgrade all serving
nodes before selecting the batched endpoint with a new SDK.
Custom TypeScript `Table` subclasses must implement the new abstract method.
</Info>
*/}
Python and Rust read slices across rows with `fetch_blob_ranges`. On a handle,
`read_ranges` reads more than one slice of one blob. Python takes
`(offset, length)` pairs, TypeScript takes `{ start, end }` ranges with an
@@ -678,6 +801,14 @@ exclusive `end`, and Rust takes `start..end` ranges:
</CodeBlock>
<CodeBlock filename="TypeScript" language="TypeScript" icon="square-js">
{/* Draft for the TypeScript cross-row Blob range release.
{`// Upcoming-release draft: slices from more than one row.
const slices = await blobTable.fetchBlobRanges("image", [
{ rowId: rowIds[0]!, offset: 0n, length: 6n },
{ rowId: rowIds[1]!, offset: 7n, length: 5n },
]);
`}{"\n"}
*/}
{TsBlobApiRanges}
</CodeBlock>
+4 -2
View File
@@ -7,8 +7,10 @@ icon: rocket
import { PyConnect, TsConnect, RsConnect, PyConnectObjectStorage, TsConnectObjectStorage, RsConnectObjectStorage, PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders, RsConnectEnterprisePlaceholders } from '/snippets/connection.mdx';
import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartCurateSample, PyQuickstartCurateDedupeSetup, PyQuickstartCurateDedupe, PyQuickstartCurateDedupeQuery, PyQuickstartFlattenStats, PyQuickstartAddFeature, PyQuickstartAddFeatureEnterprise, PyQuickstartMultimodalBytes, PyQuickstartTraining, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, TsQuickstartMultimodalBytes, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1, RsQuickstartMultimodalBytes } from '/snippets/quickstart.mdx';
This quickstart uses LanceDB Embedded with a local database and works without an account or API key.
LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage.
This quickstart walks you through creating a table, searching your data, and preparing it for training.
By default, it uses LanceDB Embedded with a local database, so no account or API key is required.
To follow along with an existing LanceDB Enterprise deployment, use the
[Enterprise connection instructions](#connect-to-lancedb-enterprise).
## 1\. Install LanceDB {#1-install-lancedb}
+57
View File
@@ -182,6 +182,56 @@ BM25 scores depend on the indexed corpus and its term statistics. Compare
rankings on the dataset you will search; treat scores as relative relevance
values rather than probabilities.
### Match any word or every word {#term-operators}
A multi-word string such as `"happy puppy"` uses **OR**: a row can match either
term. Writing `"happy AND puppy"` does not select an AND operator; the string
is analyzed as search text. To require both terms, construct a match query:
<CodeGroup>
```python Python icon="python"
from lancedb.query import FullTextOperator, MatchQuery
query = MatchQuery("happy puppy", "text", operator=FullTextOperator.AND)
results = table.search(query, query_type="fts").limit(10).to_list()
```
```typescript TypeScript icon="square-js"
import { MatchQuery, Operator } from "@lancedb/lancedb";
const query = new MatchQuery("happy puppy", "text", { operator: Operator.And });
const results = await tbl.query().fullTextSearch(query).limit(10).toArray();
```
```rust Rust icon="rust"
use lance_index::scalar::{
FullTextSearchQuery,
inverted::query::{MatchQuery, Operator},
};
use lancedb::query::{ExecutableQuery, QueryBase};
let query = MatchQuery::new("happy puppy".to_owned())
.with_column(Some("text".to_owned()))
.with_operator(Operator::And);
let results = tbl
.query()
.full_text_search(FullTextSearchQuery::new_query(query.into()))
.limit(10)
.execute()
.await?;
```
</CodeGroup>
AND requires all analyzed terms, without requiring adjacency or order. Use
[`PhraseQuery`](#phrase-vs-terms-queries) for an ordered phrase, or combine
separate queries with [`&` and `|`](#boolean-queries). Python `and` and `or`
do not build queries.
On Enterprise, the existing [`fts()` SQL reference](/sql/dql/fts#term-operators)
shows the equivalent JSON (`"operator":"And"`), `_score`, and a
[`COUNT(*)` workaround](/sql/dql/fts#count) for counting matches without a
top-k limit. `len(results)` counts only the returned result page.
### Keeping the index up to date {#keeping-the-index-up-to-date}
In LanceDB Embedded, new rows can remain outside the FTS index until you optimize the table.
@@ -395,6 +445,13 @@ table.create_index("text", config=FTS(with_position=True, remove_stop_words=Fals
</CodeGroup>
Storing token positions increases the index size and adds indexing work.
On Enterprise, wait for the replacement index to finish before issuing the
phrase query, using `table.wait_for_index(["text_idx"])` with your actual
index name. An existing index without positions must be rebuilt; changing the
query does not add positions. A phrase query against such an index is rejected
with an error asking you to recreate it with positions, rather than returning
an empty match set. See [FTS index options](/indexing/fts-index#fts-parameters)
and the [SQL phrase reference](/sql/dql/fts#phrase).
### Fuzzy Search {#fuzzy-search}
+4 -4
View File
@@ -1,15 +1,15 @@
---
title: "RTE reads"
sidebarTitle: "RTE Read"
description: "Query a table with the real time engine enabled and get writes back within milliseconds of being written, merged transparently with the base table."
description: "Query a table with the Realtime Engine enabled and get writes back within milliseconds of being written, merged transparently with the base table."
icon: "magnifying-glass"
keywords: ["rte", "real time engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"]
keywords: ["rte", "realtime engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"]
availability:
embedded: available
enterprise: available
---
A table with the [real time engine](/tables/realtime-engine) enabled queries
A table with the [Realtime Engine](/tables/realtime-engine) enabled queries
the same way as any other table — nothing about `search`, filtering, or SQL
changes. This page covers what you get back; for enabling RTE and writing to
a table, see [RTE writes](/ingestion/realtime-write). For how Enterprise
@@ -79,6 +79,6 @@ available.
- [RTE writes](/ingestion/realtime-write) — enable RTE and write to a table
- [Distributed RTE Read](/enterprise/distributed-real-time-read) — combining results across machines in Enterprise
- [How the real time engine works](/tables/realtime-engine#memwal-format)
- [How the Realtime Engine works](/tables/realtime-engine#memwal-format)
- [Hybrid search](/search/hybrid-search)
- [Vector search](/search/vector-search)
+9
View File
@@ -16,6 +16,15 @@ availability:
## CREATE FUNCTION {#create}
{/* Draft for the function exist_ok release.
`CREATE FUNCTION IF NOT EXISTS` preserves an existing named Function version,
including its code, credentials and execution settings. In Python, pass
`exist_ok=True` to `create_function` or `create_function_async`. The default
retains the existing version-creation behavior.
*/}
<CodeGroup>
```sql SQL icon="database"
CREATE FUNCTION f(x int64) RETURNS int64
+40
View File
@@ -38,6 +38,46 @@ runs as `create_` followed by the algorithm instead. See
[Incremental Indexing](/indexing/incremental-indexing).
</Note>
{/* Draft for the index exist_ok release.
```sql
CREATE INDEX IF NOT EXISTS text_search ON documents USING fts (text)
```
Use `IF NOT EXISTS` to preserve the existing index with the same name. Without an
explicit name, the name is derived from the column (`title_idx`, or
`title_list_element_idx` for list-element FTS). Existing definitions and builds
are kept, even when the new request specifies different settings.
The Python SDK exposes the same behavior through `exist_ok=True` on
`create_index` and `create_index_async`, including scalar and FTS wrappers.
This option takes precedence over `replace`, whose default behavior is unchanged.
```python
from lancedb.index import BTree
table.create_index("title", config=BTree(), name="title_idx", exist_ok=True)
```
```rust
use lancedb::index::Index;
table.create_index(&["title"], Index::BTree(Default::default()))
.name("title_idx".to_string())
.exist_ok(true)
.execute()
.await?;
```
The SDK option is available in Python and Rust. TypeScript support is a separate
follow-up. Remote use requires a server that supports the option.
An existing background build continues running. A completed submission handle
for a skipped creation does not wait for that build; use `wait_for_index` when
its completion is required.
*/}
## DROP INDEX {#drop}
<CodeGroup>
+10
View File
@@ -27,6 +27,16 @@ CREATE MATERIALIZED VIEW <name> AS SELECT ...
```
</CodeGroup>
{/* Draft for the materialized-view exist_ok release.
`IF NOT EXISTS` preserves an existing materialized view's definition, data and
refresh settings without refreshing it. The Python equivalent is
`db.create_materialized_view("saved", "source", exist_ok=True)`. A skipped
asynchronous creation returns a completed job without submitting a refresh job.
Existing names are errors by default.
*/}
Once created, a materialized view can be queried like a table. Use the
statements below to list, refresh and drop it. For SDK methods, see
[Materialized views](/management/materialized-view#create).
+10
View File
@@ -28,6 +28,16 @@ CREATE STORAGE INTEGRATION <name>
```
</CodeGroup>
{/* Draft for the storage-integration exist_ok release.
`IF NOT EXISTS` returns an existing integration unchanged, including its provider,
storage prefix, credential references and external ID. In the Python SDK, pass
`exist_ok=True` to `create_storage_integration`. The default reports an error when
the name already exists.
Returning an existing integration requires `USAGE` on that integration.
*/}
`STORAGE_PROVIDER` and `STORAGE_PREFIX` are required for every provider.
`STORAGE_PREFIX` is the URI prefix the integration covers -- a query only
matches an integration whose prefix is a prefix of the URI it reads.
+11 -1
View File
@@ -176,7 +176,7 @@ ALTER TABLE t UNSET RTE
```
</CodeGroup>
The [real time engine](/tables/realtime-engine) puts a write-ahead log in front
The [Realtime Engine](/tables/realtime-engine) puts a write-ahead log in front
of the table, making small frequent writes cheap by batching them out of the
commit path. `sharding` and `buckets` spread the log so concurrent writers do
not contend on one place; `bucket` sharding names its `column`, which must be
@@ -205,6 +205,16 @@ Dropping, renaming, or retyping a column is an SDK operation
## CLONE {#clone}
{/* Draft for the table-clone exist_ok release.
Use `CREATE TABLE IF NOT EXISTS target CLONE source` to preserve an existing
target unchanged. The Python equivalent is
`db.clone_table("target", source_uri, exist_ok=True)`. Omitting the option reports
an error for an existing target. A skipped clone does not copy rows or change
the target's version history.
*/}
<CodeGroup>
```sql SQL icon="database"
CREATE TABLE docs_snapshot CLONE documents
+10
View File
@@ -23,6 +23,16 @@ catalog removal; physical cleanup can continue afterward.
## CREATE VIEW {#create}
{/* Draft for the view exist_ok release.
`CREATE VIEW IF NOT EXISTS` creates a missing view and returns an existing
view's stored query and schema unchanged. Without `IF NOT EXISTS`, an existing
name is an error. In Python, use `db.create_view(name, query, exist_ok=True)`;
in Rust, use `db.create_view(name, query, &namespace).exist_ok(true).await?`.
Returning an existing view requires `SELECT` on that view.
*/}
<CodeGroup>
```sql SQL icon="database"
CREATE VIEW "recent_matches" AS
+4 -4
View File
@@ -15,10 +15,10 @@ SELECT id, blob_descriptor(video) AS descriptor FROM videos
```
</CodeGroup>
A [BlobV2](/management/table#managed-blobs) column's bytes are not fetched by
a plain `SELECT`: that already returns `large_binary`, the same as any other
binary column. `blob_descriptor` instead returns a small struct describing
where the payload lives, without reading it. Pass one row's descriptor to
A plain `SELECT` of a [BlobV2](/management/table#managed-blobs) column returns
its payload as `large_binary`. `blob_descriptor` instead returns a small
struct describing where the payload lives, without reading the payload.
Pass one row's descriptor to
the SDK's blob file reader to open that payload directly:
<CodeGroup>
+9
View File
@@ -55,6 +55,15 @@ current deployments.
a subset of partitions and `id_column` are pair-query-only options, accepted
by [`duplicate_pairs`](/sql/dql/duplicate-pairs#input) but refused here.
## Index and snapshot requirements {#requirements}
Use one compatible, current vector index covering the source snapshot.
Full scans reject unindexed fragments. Comparisons stay within physical IVF
partitions and index segments; this does not enumerate cross-partition or
cross-segment duplicates. Quantized-index distances use encoded vector
representations. See [recall and scale limits](/curation/dedupe#limits) before
treating the result as globally exact deduplication.
## Output {#output}
One row per duplicate group, **in the table's own schema** -- every column of
+6
View File
@@ -60,6 +60,12 @@ only [`dedupe`](/sql/dql/dedupe#input) accepts it.
## Output {#output}
See [`dedupe` index prerequisites](/sql/dql/dedupe#requirements) and the
[recall limits](/curation/dedupe#limits). Pairs are found within each physical
partition and index segment, not across them. A full scan requires complete
index coverage; sampling is a diagnostic view of the selected indexed
partitions and does not prove coverage or recall for the rest of the table.
One row per close pair found, in a fixed schema independent of the source
table:
+60 -3
View File
@@ -30,14 +30,16 @@ INSERT INTO my_docs VALUES
(3, 'The puppy catches a ball with great enthusiasm', 'sports', 'Alice'),
(5, 'Puppy training requires patience and dedication', 'training', 'Alice');
CREATE INDEX ON my_docs USING fts (text);
CREATE INDEX ON my_docs USING fts (text) WITH (with_position = true);
```
</CodeGroup>
<Warning>
Phrase queries need position information, which costs extra index size.
Add `WITH (with_position = true)` to `CREATE INDEX`. Without it,
[phrase queries](#phrase) find nothing. See
The setup above enables it with `WITH (with_position = true)`. An existing
index without positions must be rebuilt before running a phrase query; the
server rejects the query and asks you to recreate the index with positions.
It does not silently return no matches. See
[FTS parameters](/indexing/fts-index#fts-parameters).
</Warning>
@@ -86,6 +88,44 @@ LIMIT 5
it behaves like any other column, but exists only in a relation that came
from `fts()`. See [Data types](/sql/data-types#pseudo-columns).
## Match any term or every term {#term-operators}
The default match operator is OR. `"happy puppy"` matches either analyzed
term. SQL JSON uses `"Or"` and `"And"`, with this casing; Python uses the
`FullTextOperator.OR` and `FullTextOperator.AND` enum members:
```python
from lancedb.query import FullTextOperator, MatchQuery
query = MatchQuery("happy puppy", "text", operator=FullTextOperator.AND)
json_query = query.to_json()
```
```sql
SELECT id, text, _score
FROM fts('my_docs', '{"match":{"column":"text","terms":"happy puppy","operator":"And"}}')
ORDER BY _score DESC
```
Both terms must occur, but they need not be adjacent. Do not embed `AND` or
`OR` in `terms` to select an operator.
## Count matches {#count}
Count the `fts()` relation before applying a top-k limit:
```sql
SELECT COUNT(*) AS matching_rows
FROM fts('my_docs', '{"match":{"column":"text","terms":"happy puppy","operator":"And"}}')
```
This is an Enterprise SQL workaround when the SDK's FTS query builder does
not expose a match-count operation. `table.count_rows()` without an FTS
relation counts table rows, and taking the length of a limited search counts
only that result page. For list-element indexes, multiple matching elements
can produce multiple rows; use `COUNT(DISTINCT id)` when you need unique
application records.
## Fuzzy {#fuzzy}
Tolerates typos, up to a character-edit budget:
@@ -109,6 +149,12 @@ PhraseQuery("puppy park", "text", slop=2) # up to 2 words between them
```
</CodeGroup>
```sql
SELECT id, text, _score
FROM fts('my_docs', '{"phrase":{"column":"text","terms":"happy puppy","slop":0}}')
ORDER BY _score DESC
```
## Boolean {#boolean}
Combine queries with `&` (AND) or `|` (OR):
@@ -120,6 +166,17 @@ MatchQuery("puppy", "text") | MatchQuery("kitten", "text")
```
</CodeGroup>
For SQL, serialize the composed query rather than writing occurrence enums
by hand:
```python
query = MatchQuery("puppy", "text") & MatchQuery("happy", "text")
json_query = query.to_json()
```
Use that string as the second `fts()` argument. `.to_json()` supplies the
serialized Boolean field names for the SDK version you use.
## Boost {#boost}
Weight a query up or down relative to another:
+5 -5
View File
@@ -1,21 +1,21 @@
---
title: "Real Time engine (RTE)"
sidebarTitle: "Real Time Engine (RTE)"
title: "Realtime Engine (RTE)"
sidebarTitle: "Realtime Engine (RTE)"
description: "Absorb small, frequent writes cheaply and make them queryable within milliseconds."
icon: "bolt"
keywords: ["rte", "real time engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"]
keywords: ["rte", "realtime engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"]
availability:
embedded: available
enterprise: available
---
## What is the real time engine? {#what-is-rte}
## What is the Realtime Engine? {#what-is-rte}
Every write to a LanceDB table is normally a commit to the underlying Lance
dataset. That is ideal for bulk loads, but a stream of small upserts becomes a
stream of small commits, and each write is only visible once its commit lands.
The real time engine (RTE) puts an LSM-style write tier in front of the table.
The Realtime Engine (RTE) puts an LSM-style write tier in front of the table.
It turns many small writes into a few large commits, and makes each write
**searchable within milliseconds** of being acknowledged. It is enabled per
table, and nothing about how you query that table changes.
+34
View File
@@ -1,5 +1,39 @@
# LanceDB Java Enterprise Client
## Installation
Stable releases of `com.lancedb:lancedb-core` are published to Maven Central.
Beta releases are published to `https://maven.fury.io/lancedb/` instead. They
depend on Lance beta releases, which are published to `https://maven.lance.org`.
To use a beta, add both repositories alongside Maven Central:
```xml
<repositories>
<repository>
<id>lancedb</id>
<url>https://maven.fury.io/lancedb/</url>
</repository>
<repository>
<id>lance</id>
<url>https://maven.lance.org</url>
</repository>
</repositories>
```
For Gradle:
```kotlin
repositories {
mavenCentral()
maven { url = uri("https://maven.fury.io/lancedb/") }
maven { url = uri("https://maven.lance.org") }
}
```
Use an explicit version, including the full `-beta.N` suffix. Beta versions are
Maven releases, not `SNAPSHOT` versions.
## Configuration and Initialization
### LanceDB Cloud (legacy)
+1 -1
View File
@@ -8,7 +8,7 @@
<parent>
<groupId>com.lancedb</groupId>
<artifactId>lancedb-parent</artifactId>
<version>0.42.0-beta.12</version>
<version>0.42.0-beta.13</version>
<relativePath>../pom.xml</relativePath>
</parent>
+11 -2
View File
@@ -6,7 +6,7 @@
<groupId>com.lancedb</groupId>
<artifactId>lancedb-parent</artifactId>
<version>0.42.0-beta.12</version>
<version>0.42.0-beta.13</version>
<packaging>pom</packaging>
<name>${project.artifactId}</name>
<description>LanceDB Java SDK Parent POM</description>
@@ -28,7 +28,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<arrow.version>15.0.0</arrow.version>
<lance-core.version>15.0.0-beta.18</lance-core.version>
<lance-core.version>15.0.0-beta.21</lance-core.version>
<jackson.version>2.18.12</jackson.version>
<spotless.skip>false</spotless.skip>
<spotless.version>2.30.0</spotless.version>
@@ -318,6 +318,15 @@
</plugins>
</build>
</profile>
<profile>
<id>deploy-to-fury</id>
<distributionManagement>
<repository>
<id>fury</id>
<url>https://maven.fury.io/lancedb/</url>
</repository>
</distributionManagement>
</profile>
<profile>
<id>deploy-to-ossrh</id>
<build>
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "lancedb-nodejs"
edition.workspace = true
version = "0.42.0-beta.12"
version = "0.42.0-beta.13"
publish = false
license.workspace = true
description.workspace = true
+589
View File
@@ -0,0 +1,589 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import { createHash } from "crypto";
import { getEventListeners } from "events";
import { createReadStream } from "fs";
import * as http from "http";
import { AddressInfo } from "net";
import {
Table as ArrowTable,
Binary,
Field,
LargeBinary,
Struct,
Uint8,
Uint32,
Uint64,
Utf8,
tableToIPC,
vectorFromArray,
} from "apache-arrow";
import { BlobRangeRequest, Connection, Table, connect } from "../lancedb";
jest.setTimeout(30000);
const IDENTITY = `v1:${"a".repeat(64)}`;
const MIB = 1024 * 1024;
type Range = {
// biome-ignore lint/style/useNamingConvention: Matches the server JSON contract.
row_id: number;
offset: number;
length: number;
};
type Request = {
column: string;
branch: string | null;
version: number | null;
ranges: Range[];
identity?: string;
};
function payload(row: number, offset: number, length: number, version: number) {
const bytes = Buffer.alloc(length);
for (let i = 0; i < length; i++) {
bytes[i] = (row * 17 + ((offset + i) % 251) + version) % 251;
}
return bytes;
}
async function withRangeServer(
run: (db: Connection, calls: Request[], paths: string[]) => Promise<void>,
fault?: string | number,
capability: string | null = "1",
onStall?: () => void,
) {
let takes = 0;
const calls: Request[] = [];
const paths: string[] = [];
const server = http.createServer((req, res) => {
req.setTimeout(15000);
paths.push(req.url ?? "");
if (
req.url === "/v1/table/test/describe/" ||
req.url === "/v1/table/test/branches/list/"
) {
res.writeHead(200, {
"Content-Type": "application/json",
"phalanx-version": "1.13.0-beta.0",
...(req.url.endsWith("/describe/") && capability !== null
? { "x-lancedb-blob-ranges": capability }
: {}),
});
const response = req.url.endsWith("branches/list/")
? {
branches: {
experiment: {
parentBranch: null,
parentVersion: 1,
createAt: 1,
manifestSize: 1,
},
},
}
: { version: 8, schema: { fields: [] } };
res.end(JSON.stringify(response));
return;
}
if (capability !== "1" && req.method === "GET") {
const url = new URL(req.url!, "http://localhost");
expect(url.searchParams.get("branch")).toBe("experiment");
expect(url.searchParams.get("version")).toBe("3");
const [start, end] = req.headers.range!.slice(6).split("-").map(Number);
const bytes = Buffer.from("alpha").subarray(start, end + 1);
res
.writeHead(206, {
"Content-Range": `bytes ${start}-${end}/5`,
"Content-Length": bytes.length,
"x-lancedb-version": "3",
})
.end(bytes);
return;
}
expect(req.method).toBe("POST");
expect(req.url).toBe(
capability === "1"
? "/v1/table/test/fetch_blob_ranges/"
: "/v1/table/test/query/",
);
const chunks: Buffer[] = [];
let size = 0;
req.on("data", (chunk: Buffer) => {
size += chunk.length;
expect(size).toBeLessThanOrEqual(256 * 1024);
chunks.push(chunk);
});
req.on("end", () => {
if (capability !== "1") {
const body = JSON.parse(Buffer.concat(chunks).toString()) as {
branch: string;
version: number;
filter: string;
};
expect(body.branch).toBe("experiment");
expect(body.version).toBe(3);
takes++;
const ids = (body.filter.match(/\d+/g) ?? [])
.map(Number)
.filter((id) => [10, 20, 40].includes(id))
.reverse();
const descriptor = new Struct([
new Field("kind", new Uint8(), false),
new Field("position", new Uint64(), false),
new Field("size", new Uint64(), false),
new Field("blob_id", new Uint32(), false),
new Field("blob_uri", new Utf8(), false),
]);
const arrow = new ArrowTable({
image: vectorFromArray(
ids.map((id) =>
id === 20
? null
: {
kind: 0,
position: 0n,
size: id === 40 ? 0n : 5n,
// biome-ignore lint/style/useNamingConvention: Arrow descriptor field.
blob_id: 0,
// biome-ignore lint/style/useNamingConvention: Arrow descriptor field.
blob_uri: "",
},
),
descriptor,
),
_rowid: vectorFromArray(ids.map(BigInt), new Uint64()),
});
expect(takes).toBeGreaterThan(0);
res
.writeHead(200, {
"Content-Type": "application/vnd.apache.arrow.stream",
"x-lancedb-version": "3",
})
.end(tableToIPC(arrow, "stream"));
return;
}
const body = JSON.parse(Buffer.concat(chunks).toString()) as Request;
body.identity = req.headers["x-lancedb-query-snapshot"] as
| string
| undefined;
calls.push(body);
expect(body.column).toBe("image");
expect(body.branch).toBe("experiment");
expect(body.ranges.length).toBeLessThanOrEqual(1024);
expect(
body.ranges.reduce((sum, range) => sum + range.length, 0),
).toBeLessThanOrEqual(64 * MIB);
const version = body.version ?? (calls.length === 1 ? 7 : 8);
const failure =
calls.length > 1 || String(fault).startsWith("first-")
? fault
: undefined;
if (failure === "recreated" || failure === "gone") {
res
.writeHead(failure === "recreated" ? 400 : 404)
.end("query snapshot identity mismatch: source gone or replaced");
return;
}
if (failure === "stall" && calls.length === 2) {
res.writeHead(200, {
"Content-Type": "application/vnd.apache.arrow.stream",
"x-lancedb-version": "7",
"x-lancedb-query-snapshot": IDENTITY,
});
res.flushHeaders();
onStall?.();
return;
}
if (typeof failure === "number") {
res.writeHead(failure).end("ordinary server failure");
return;
}
if (failure === "disconnect") {
req.socket.destroy();
return;
}
let values = body.ranges.map((range) =>
range.row_id === 20
? null
: payload(range.row_id, range.offset, range.length, version),
);
if (failure === "count") values = [];
if (failure === "length") values = [Buffer.alloc(0)];
const arrow = new ArrowTable({
[failure === "column" ? "wrong" : "value"]: vectorFromArray(
values,
failure === "type" ? new Binary() : new LargeBinary(),
),
});
let ipc = tableToIPC(arrow, "stream");
if (failure === "eos") ipc = ipc.subarray(0, ipc.length - 8);
if (failure === "body") ipc = ipc.subarray(0, Math.floor(ipc.length / 2));
res.writeHead(200, {
"Content-Type": "application/vnd.apache.arrow.stream",
connection: "close",
"Content-Length": ipc.length + (failure === "transport" ? 10 : 0),
...(failure === "version" ? {} : { "x-lancedb-version": version }),
...(["missing-identity", "first-missing-identity"].includes(
String(failure),
)
? {}
: {
"x-lancedb-query-snapshot":
failure === "wrong-identity"
? `v1:${"b".repeat(64)}`
: failure === "first-invalid-identity"
? "broken"
: IDENTITY,
}),
});
// Fragment the generated IPC payload across actual HTTP writes.
for (let i = 0; i < ipc.length; i += 8192)
res.write(ipc.subarray(i, i + 8192));
res.end();
});
});
server.listen(0, "127.0.0.1");
await new Promise<void>((resolve) => server.once("listening", resolve));
const port = (server.address() as AddressInfo).port;
const db = await connect("db://dev", {
apiKey: "fake",
hostOverride: `http://127.0.0.1:${port}`,
clientConfig: {
retryConfig: { retries: 2, connectRetries: 2, readRetries: 2 },
blobRequestConcurrency: 1,
timeoutConfig: { timeout: 20 },
},
});
try {
await run(db, calls, paths);
} finally {
await new Promise<void>((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
});
}
}
async function open(db: Connection, version?: number): Promise<Table> {
return db.openTable("test", [], { branch: "experiment", version });
}
describe("fetchBlobRanges", () => {
it.each([null, "0", "2"])(
"uses old routes before data requests for capability %s",
async (capability) => {
await withRangeServer(
async (db, calls, paths) => {
// Reopening exercises both the initial and cached database describe paths.
for (let i = 0; i < 2; i++) {
const table = await open(db, 3);
const requests = [
{ rowId: 10n, offset: 1n, length: 3n },
{ rowId: 20n, offset: 0n, length: 1n },
{ rowId: 40n, offset: 0n, length: 0n },
{ rowId: 10n, offset: 5n, length: 0n },
{ rowId: 10n, offset: 1n, length: 3n },
];
expect(await table.fetchBlobRanges("image", requests)).toEqual([
Buffer.from("lph"),
null,
Buffer.alloc(0),
Buffer.alloc(0),
Buffer.from("lph"),
]);
for (const row of [
{ rowId: 10n, offset: 4n, length: 2n },
{ rowId: 99n, offset: 0n, length: 1n },
])
await expect(
table.fetchBlobRanges("image", [row]),
).rejects.toThrow();
const before = paths.length;
expect(await table.fetchBlobRanges("image", [])).toEqual([]);
expect(paths).toHaveLength(before);
}
expect(calls).toHaveLength(0);
expect(paths.some((path) => path.includes("fetch_blob_ranges"))).toBe(
false,
);
},
undefined,
capability,
);
},
);
it("renegotiates advertised support when reopening a cached table", async () => {
await withRangeServer(async (db, calls) => {
for (let i = 0; i < 2; i++) {
const table = await open(db);
expect(
await table.fetchBlobRanges("image", [
{ rowId: 10n, offset: 0n, length: 1n },
]),
).toEqual([payload(10, 0, 1, i === 0 ? 7 : 8)]);
}
expect(calls).toHaveLength(2);
});
});
it("cancels while waiting for a later response body and releases the only permit", async () => {
let markStalled!: () => void;
const stalled = new Promise<void>((resolve) => {
markStalled = resolve;
});
await withRangeServer(
async (db, calls) => {
const table = await open(db);
const controller = new AbortController();
const pending = table.fetchBlobRanges(
"image",
Array.from({ length: 2049 }, () => ({
rowId: 10n,
offset: 0n,
length: 1n,
})),
{ signal: controller.signal },
);
const rejected = expect(pending).rejects.toMatchObject({
name: "AbortError",
});
await stalled;
controller.abort();
await rejected;
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
expect(calls).toHaveLength(2);
expect(
await table.fetchBlobRanges("image", [
{ rowId: 10n, offset: 0n, length: 1n },
]),
).toEqual([payload(10, 0, 1, 8)]);
expect(calls).toHaveLength(3);
},
"stall",
"1",
() => markStalled(),
);
});
it.each([undefined, 3])(
"preserves order, nulls, duplicates and snapshot (checkout %s)",
async (version) => {
await withRangeServer(async (db, calls, paths) => {
const table = await open(db, version);
const requests: BlobRangeRequest[] = Array.from(
{ length: 1025 },
(_, i) => ({
rowId: i % 9 === 0 ? 20 : 10 + (i % 7),
offset: BigInt(i),
length: BigInt(i % 4),
}),
);
requests.push(
{ rowId: 10n, offset: 0n, length: 0n },
{ rowId: 10n, offset: 2n, length: 3n },
{ rowId: 10n, offset: 2n, length: 3n },
);
const result = await table.fetchBlobRanges("image", requests);
expect(result).toEqual(
requests.map((range) =>
Number(range.rowId) === 20
? null
: payload(
Number(range.rowId),
Number(range.offset),
Number(range.length),
version ?? 7,
),
),
);
expect(calls.map((body) => body.version)).toEqual([
version ?? null,
version ?? 7,
]);
expect(
await table.fetchBlobRanges("image", [
{ rowId: 10n, offset: 0n, length: 1n },
]),
).toEqual([payload(10, 0, 1, version ?? 8)]);
expect(calls[2].version).toBe(version ?? null);
expect(
paths.filter((path) => path.endsWith("fetch_blob_ranges/")),
).toHaveLength(3);
});
},
);
it("partitions the byte budget and reassembles one range larger than 64 MiB", async () => {
await withRangeServer(async (db, calls) => {
const table = await open(db);
const requests = [
{ rowId: 10n, offset: 3n, length: BigInt(65 * MIB) },
{ rowId: 30n, offset: 7n, length: 2n },
];
const result = await table.fetchBlobRanges("image", requests);
for (const [i, range] of requests.entries()) {
expect(result[i]?.length).toBe(Number(range.length));
expect(
createHash("sha256")
.update(result[i] as Buffer)
.digest("hex"),
).toBe(
createHash("sha256")
.update(
payload(
Number(range.rowId),
Number(range.offset),
Number(range.length),
7,
),
)
.digest("hex"),
);
}
expect(calls).toHaveLength(2);
expect(calls.map((body) => body.version)).toEqual([null, 7]);
});
});
it.each([
"type",
"column",
"count",
"length",
"eos",
"body",
"transport",
"version",
"disconnect",
401,
403,
404,
429,
500,
])("rejects the whole call after a later %s failure", async (fault) => {
await withRangeServer(async (db, calls, paths) => {
const table = await open(db);
await expect(
table.fetchBlobRanges(
"image",
Array.from({ length: 1025 }, () => ({
rowId: 10n,
offset: 0n,
length: 1n,
})),
),
).rejects.toThrow();
expect(calls).toHaveLength(2);
expect(
paths.every(
(path) =>
path.endsWith("describe/") ||
path.endsWith("branches/list/") ||
path.endsWith("fetch_blob_ranges/"),
),
).toBe(true);
}, fault);
});
it.each(["missing-identity", "wrong-identity", "recreated", "gone"])(
"retains original identity through row and byte partitions (%s)",
async (fault) => {
for (const huge of [false, true]) {
await withRangeServer(async (db, calls) => {
const table = await open(db);
const requests = huge
? [{ rowId: 10n, offset: 0n, length: BigInt(64 * MIB + 1) }]
: Array.from({ length: 1025 }, () => ({
rowId: 10n,
offset: 0n,
length: 1n,
}));
await expect(
table.fetchBlobRanges("image", requests),
).rejects.toThrow();
expect(calls.map((call) => call.identity)).toEqual([
undefined,
IDENTITY,
]);
expect(calls.map((call) => call.version)).toEqual([null, 7]);
}, fault);
}
},
);
it.each(["first-missing-identity", "first-invalid-identity"])(
"requires a first authoritative bulk identity (%s)",
async (fault) => {
await withRangeServer(async (db, calls, paths) => {
const table = await open(db);
const before = paths.length;
await expect(
table.fetchBlobRanges(
"image",
Array.from({ length: 1025 }, () => ({
rowId: 10n,
offset: 0n,
length: 1n,
})),
),
).rejects.toThrow(/snapshot identity/);
expect(calls).toHaveLength(1);
expect(paths).toHaveLength(before + 1);
}, fault);
},
);
it("validates integers, overflow and cancellation and leaves empty calls at zero I/O", async () => {
await withRangeServer(async (db, calls, paths) => {
const table = await open(db);
const before = paths.length;
expect(await table.fetchBlobRanges("image", [])).toEqual([]);
for (const request of [
{ rowId: -1, offset: 0n, length: 1n },
{ rowId: 1.5, offset: 0n, length: 1n },
{ rowId: Number.MAX_SAFE_INTEGER + 1, offset: 0n, length: 1n },
{ rowId: -1n, offset: 0n, length: 1n },
{ rowId: 1n << 64n, offset: 0n, length: 1n },
{ rowId: 10n, offset: -1n, length: 1n },
{ rowId: 10n, offset: 0n, length: -1n },
{ rowId: 10n, offset: 0n, length: 1n << 64n },
{ rowId: 20n, offset: (1n << 64n) - 1n, length: 1n },
]) {
await expect(
table.fetchBlobRanges("image", [request]),
).rejects.toThrow();
}
// Runtime type validation must also reject a number passed as an offset.
await expect(
table.fetchBlobRanges("image", [
{ rowId: 10n, offset: 0 as unknown as bigint, length: 1n },
]),
).rejects.toThrow();
const controller = new AbortController();
controller.abort(new Error("cancelled by caller"));
await expect(
table.fetchBlobRanges(
"image",
[{ rowId: 10n, offset: 0n, length: 1n }],
{ signal: controller.signal },
),
).rejects.toThrow("cancelled by caller");
expect(paths).toHaveLength(before);
expect(calls).toHaveLength(0);
});
});
it("records the loaded native artifact", async () => {
const artifacts = Object.keys(require.cache).filter(
(path) => path.endsWith(".node") && path.includes("lancedb"),
);
expect(artifacts.length).toBeGreaterThan(0);
for (const path of artifacts) {
const hash = createHash("sha256");
for await (const chunk of createReadStream(path)) hash.update(chunk);
console.log(
`loaded native artifact=${path} sha256=${hash.digest("hex")}`,
);
}
});
});
+59
View File
@@ -483,6 +483,65 @@ describe("remote connection", () => {
expect(insertRequests).toBe(2);
});
it.each([
{ status: 429, retries: undefined, attempts: 2 },
{ status: 429, retries: 0, attempts: 1 },
{ status: 504, retries: undefined, attempts: 1 },
{ status: 504, retries: 0, attempts: 1 },
])("applies per-call add retries: %j", async (scenario) => {
let attempts = 0;
await withMockDatabase(
(req, res) => {
if (req.url?.endsWith("/describe/")) {
res.writeHead(200).end(
JSON.stringify({
version: 1,
schema: {
fields: [
{ name: "id", type: { type: "int64" }, nullable: true },
],
},
}),
);
return;
}
expect(req.url).toContain("/insert/");
req.resume();
req.on("end", () => {
attempts++;
res
.writeHead(attempts === 1 ? scenario.status : 200)
.end('{"version":2}');
});
},
async (db) => {
const table = await db.openTable("items");
const result = table.add([{ id: 1n }], { retries: scenario.retries });
if (scenario.attempts === 2) {
await expect(result).resolves.toMatchObject({ version: 2 });
} else {
await expect(result).rejects.toThrow();
}
for (const retries of [-1, 256, 1.5]) {
await expect(table.add([{ id: 2n }], { retries })).rejects.toThrow(
"retries must be an integer between 0 and 255",
);
}
},
{
clientConfig: {
retryConfig: {
retries: 3,
statuses: [429, 504],
backoffFactor: 0,
backoffJitter: 0,
},
},
},
);
expect(attempts).toBe(scenario.attempts);
});
it("should accept partial connection options", async () => {
await connect("db://test", {
apiKey: "fake",
+2 -2
View File
@@ -282,7 +282,7 @@ maybeDescribe("DynamoDB Lock", () => {
});
it("can be used to configure a DynamoDB table for commit log", async () => {
const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`;
const uri = `s3+ddb://${bucket.name}/concurrent-appends?ddbTableName=${commitTable.name}`;
const db = await connect(uri, {
storageOptions: CONFIG,
readConsistencyInterval: 0,
@@ -307,7 +307,7 @@ maybeDescribe("DynamoDB Lock", () => {
});
it("clears dynamodb state after dropping all tables", async () => {
const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`;
const uri = `s3+ddb://${bucket.name}/drop-all-tables?ddbTableName=${commitTable.name}`;
const db = await connect(uri, {
storageOptions: CONFIG,
readConsistencyInterval: 0,
+37
View File
@@ -3019,6 +3019,43 @@ describe("when dealing with blob columns", () => {
expect(bytes.map((b) => b?.toString())).toEqual(["new", "hi"]);
});
it("fetchBlobRanges reads local ranges with order, duplicates, nulls and validation", async () => {
const { table, rowIds } = await openBlobTable();
const [alphaId, betaId, nullId] = rowIds;
const requests = [
{ rowId: betaId, offset: 1n, length: 3n },
{ rowId: alphaId, offset: 0n, length: 2n },
{ rowId: nullId, offset: 0n, length: 1n },
{ rowId: alphaId, offset: 5n, length: 0n },
{ rowId: betaId, offset: 1n, length: 3n },
];
expect(await table.fetchBlobRanges("image", requests)).toEqual([
Buffer.from("eta"),
Buffer.from("al"),
null,
Buffer.alloc(0),
Buffer.from("eta"),
]);
expect(await table.fetchBlobRanges("image", [])).toEqual([]);
await expect(
table.fetchBlobRanges("image", [
{ rowId: alphaId, offset: 4n, length: 2n },
]),
).rejects.toThrow();
await expect(
table.fetchBlobRanges("image", [
{ rowId: (1n << 63n) - 1n, offset: 0n, length: 1n },
]),
).rejects.toThrow();
const controller = new AbortController();
expect(
await table.fetchBlobRanges("image", requests, {
signal: controller.signal,
}),
).toHaveLength(5);
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
});
it("discovers blob columns", async () => {
const { table } = await openBlobTable();
expect(await table.blobColumns()).toEqual(["image"]);
+10
View File
@@ -305,6 +305,16 @@ export async function runWithSignal<T>(
}
}
/** One row-specific range for {@link Table.fetchBlobRanges}. */
export type BlobRangeRequest = {
/** A row ID from a query with row IDs enabled. */
rowId: bigint | number;
/** Byte offset from the beginning of the logical blob, as a uint64. */
offset: bigint;
/** Number of bytes to read, as a uint64. Zero returns an empty non-null value. */
length: bigint;
};
/** A half-open byte range `[start, end)` for {@link BlobFile.readRanges}. */
export type BlobRange = {
start: bigint;
+1
View File
@@ -91,6 +91,7 @@ export type {
BlobInput,
BlobOptions,
BlobRange,
BlobRangeRequest,
BlobReadOptions,
BlobUri,
} from "./blob";
+64 -1
View File
@@ -17,7 +17,12 @@ import {
tableFromIPC,
} from "./arrow";
import { BlobFile, BlobReadOptions, runWithSignal } from "./blob";
import {
BlobFile,
BlobRangeRequest,
BlobReadOptions,
runWithSignal,
} from "./blob";
import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry";
import { IndexOptions } from "./indices";
import { Job } from "./job";
@@ -137,6 +142,13 @@ export interface AddDataOptions {
* when the blob is read later.
*/
allowExternalBlobOutsideBases?: boolean;
/**
* Override the remote retry budget for this call (0 to 255). Zero disables
* retries, including multipart parts. Ambiguous commits are never replayed.
* Ignored by LanceDB Embedded.
*/
retries?: number;
}
export interface UpdateOptions {
@@ -676,6 +688,31 @@ export abstract class Table {
options?: BlobReadOptions,
): Promise<(Buffer | null)[]>;
/**
* Materializes row-specific byte ranges at the table's current checkout.
* Preserves request order, duplicates, and nulls. Zero length returns an empty
* buffer for a non-null blob. Invalid ranges or missing rows reject the entire
* call. See {@link Table.fetchBlobs} for row-ID validity across versions.
*
* Remote tables use the batched endpoint when the server advertises support,
* splitting at 1024 ranges and 64 MiB, including individual larger ranges.
* Older servers use descriptor queries and BlobFile range reads. Both protocols
* use one exact branch and version. Errors from an advertised endpoint propagate
* without switching protocols. All output bytes occupy memory.
*
* @example
* ```ts
* const bytes = await table.fetchBlobRanges("image", [
* { rowId: 10n, offset: 0n, length: 1024n },
* ]);
* ```
*/
abstract fetchBlobRanges(
column: string,
requests: readonly BlobRangeRequest[],
options?: BlobReadOptions,
): Promise<(Buffer | null)[]>;
/**
* Opens lazy blob handles for `column` at the given row IDs using the
* table's current checkout.
@@ -1320,6 +1357,14 @@ export class LocalTable extends Table {
}
async add(data: Data, options?: Partial<AddDataOptions>): Promise<AddResult> {
if (
options?.retries !== undefined &&
(!Number.isInteger(options.retries) ||
options.retries < 0 ||
options.retries > 255)
) {
throw new Error("retries must be an integer between 0 and 255");
}
const mode = options?.mode ?? "append";
const schema = await this.schema();
@@ -1342,6 +1387,7 @@ export class LocalTable extends Table {
mode,
progress,
options?.allowExternalBlobOutsideBases,
options?.retries,
);
}
@@ -1494,6 +1540,23 @@ export class LocalTable extends Table {
return values.map((value) => value ?? null);
}
async fetchBlobRanges(
column: string,
requests: readonly BlobRangeRequest[],
options?: BlobReadOptions,
): Promise<(Buffer | null)[]> {
const rowIds = rowIdsToBigInts(requests.map((request) => request.rowId));
const ranges = requests.map((request, i) => ({
rowId: rowIds[i],
offset: request.offset,
length: request.length,
}));
const values = await runWithSignal(options?.signal, (signal) =>
this.inner.fetchBlobRanges(column, ranges, signal),
);
return values.map((value) => value ?? null);
}
async fetchBlobFiles(
column: string,
rowIds: readonly (bigint | number)[],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-darwin-arm64",
"version": "0.42.0-beta.12",
"version": "0.42.0-beta.13",
"os": ["darwin"],
"cpu": ["arm64"],
"main": "lancedb.darwin-arm64.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-arm64-gnu",
"version": "0.42.0-beta.12",
"version": "0.42.0-beta.13",
"os": ["linux"],
"cpu": ["arm64"],
"main": "lancedb.linux-arm64-gnu.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-arm64-musl",
"version": "0.42.0-beta.12",
"version": "0.42.0-beta.13",
"os": ["linux"],
"cpu": ["arm64"],
"main": "lancedb.linux-arm64-musl.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-x64-gnu",
"version": "0.42.0-beta.12",
"version": "0.42.0-beta.13",
"os": ["linux"],
"cpu": ["x64"],
"main": "lancedb.linux-x64-gnu.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-x64-musl",
"version": "0.42.0-beta.12",
"version": "0.42.0-beta.13",
"os": ["linux"],
"cpu": ["x64"],
"main": "lancedb.linux-x64-musl.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-win32-arm64-msvc",
"version": "0.42.0-beta.12",
"version": "0.42.0-beta.13",
"os": [
"win32"
],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-win32-x64-msvc",
"version": "0.42.0-beta.12",
"version": "0.42.0-beta.13",
"os": ["win32"],
"cpu": ["x64"],
"main": "lancedb.win32-x64-msvc.node",
+1 -1
View File
@@ -11,7 +11,7 @@
"ann"
],
"private": false,
"version": "0.42.0-beta.12",
"version": "0.42.0-beta.13",
"main": "dist/index.js",
"exports": {
".": "./dist/index.js",
+40 -10
View File
@@ -21,6 +21,25 @@ pub struct BlobRange {
pub end: BigInt,
}
#[napi(object)]
pub struct BlobRangeRequest {
pub row_id: BigInt,
pub offset: BigInt,
pub length: BigInt,
}
impl BlobRangeRequest {
pub(crate) fn parse(self) -> napi::Result<lancedb::blob::BlobRangeRequest> {
let row_id = parse_u64(self.row_id, "row id")?;
let offset = parse_u64(self.offset, "offset")?;
let length = parse_u64(self.length, "length")?;
offset
.checked_add(length)
.ok_or_else(|| napi::Error::from_reason("blob range offset + length overflows u64"))?;
Ok(lancedb::blob::BlobRangeRequest::new(row_id, offset, length))
}
}
#[napi]
pub struct BlobFile {
inner: Arc<LanceBlobFile>,
@@ -205,14 +224,25 @@ pub fn parse_row_ids(row_ids: Vec<BigInt>) -> napi::Result<Vec<u64>> {
.collect()
}
pub fn copy_blob_buffers(array: LargeBinaryArray) -> Vec<Option<Buffer>> {
(0..array.len())
.map(|i| {
if array.is_null(i) {
None
} else {
Some(Buffer::from(array.value(i).to_vec()))
}
})
.collect()
pub fn copy_blob_buffers(array: LargeBinaryArray) -> napi::Result<Vec<Option<Buffer>>> {
let allocation_error =
|error| napi::Error::from_reason(format!("cannot allocate blob result: {error}"));
let mut result = Vec::new();
result
.try_reserve_exact(array.len())
.map_err(allocation_error)?;
for value in array.iter() {
let buffer = value
.map(|value| {
let mut bytes = Vec::new();
bytes
.try_reserve_exact(value.len())
.map_err(allocation_error)?;
bytes.extend_from_slice(value);
Ok::<_, napi::Error>(Buffer::from(bytes))
})
.transpose()?;
result.push(buffer);
}
Ok(result)
}
+34 -3
View File
@@ -17,7 +17,7 @@ use napi::bindgen_prelude::*;
use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
use napi_derive::napi;
use crate::blob::{BlobFile, copy_blob_buffers, parse_row_ids, spawn_abortable};
use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable};
use crate::error::NapiErrorExt;
use crate::index::Index;
use crate::job::JobFailureInfo;
@@ -134,7 +134,7 @@ impl Table {
#[napi(
catch_unwind,
ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean"
ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean, retries?: number"
)]
pub async fn add(
&self,
@@ -142,6 +142,7 @@ impl Table {
mode: String,
progress_callback: Option<ProgressFn>,
allow_external_blob_outside_bases: Option<bool>,
retries: Option<u32>,
) -> napi::Result<AddResult> {
let batches = ipc_file_to_batches(buf.to_vec())
.map_err(|e| napi::Error::from_reason(format!("Failed to read IPC file: {}", e)))?;
@@ -157,6 +158,11 @@ impl Table {
})
.collect::<Result<Vec<_>>>()?;
let mut op = self.inner_ref()?.add(batches);
if let Some(retries) = retries {
let retries = u8::try_from(retries)
.map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?;
op = op.retries(retries);
}
op = if mode == "append" {
op.mode(AddDataMode::Append)
@@ -414,7 +420,32 @@ impl Table {
.fetch_blobs(column.as_str(), &row_ids)
.await
.default_error()?;
Ok(copy_blob_buffers(array))
copy_blob_buffers(array)
})
}
#[napi(catch_unwind)]
pub fn fetch_blob_ranges<'env>(
&self,
env: &'env Env,
column: String,
requests: Vec<BlobRangeRequest>,
signal: Option<AbortSignal>,
) -> napi::Result<PromiseRaw<'env, Vec<Option<Buffer>>>> {
let mut ranges = Vec::new();
ranges.try_reserve_exact(requests.len()).map_err(|error| {
napi::Error::from_reason(format!("cannot allocate blob range requests: {error}"))
})?;
for request in requests {
ranges.push(request.parse()?);
}
let table = self.inner_ref()?.clone();
spawn_abortable(env, signal, async move {
let array = table
.fetch_blob_ranges(column.as_str(), ranges)
.await
.default_error()?;
copy_blob_buffers(array)
})
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-python"
version = "0.42.0-beta.12"
version = "0.42.0-beta.13"
publish = false
edition.workspace = true
description = "Python bindings for LanceDB"
+183
View File
@@ -0,0 +1,183 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Measure fetch_blobs RSS in a fresh client process against real HTTP.
Run with the uv environment's Python. The server lives in a separate process so
payload generation and Arrow serialization are excluded from the client's RSS.
Each row contains 1 MiB; requests over the server's 64 MiB limit are split by the
SDK. Example: python benchmarks/bench_fetch_blobs_rss.py --rows 48 144
"""
import argparse
import json
import resource
import subprocess
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
def serve(batch_rows, row_mib):
import pyarrow as pa
payload = b"x" * (row_mib << 20)
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def respond(self, status, data, content_type="application/json"):
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.send_header("phalanx-version", "0.5.0")
self.send_header("x-lancedb-version", "1")
self.end_headers()
for offset in range(0, len(data), 8192):
self.wfile.write(data[offset : offset + 8192])
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
request_body = self.rfile.read(length)
if self.path.endswith("/describe/"):
self.do_GET()
return
body = json.loads(request_body)
count = len(body["row_ids"])
if count * row_mib > 64:
self.respond(
400,
b"fetch_blobs accepts at most 67108864 total blob bytes",
)
return
schema = pa.schema([pa.field("image", pa.large_binary())])
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, schema) as writer:
for start in range(0, count, batch_rows):
array = pa.array(
[payload] * min(batch_rows, count - start),
type=pa.large_binary(),
)
writer.write_batch(pa.record_batch([array], schema=schema))
self.respond(200, sink.getvalue(), "application/vnd.apache.arrow.stream")
def do_GET(self):
if "/blob/image/" in self.path:
start, end = map(int, self.headers["Range"][6:].split("-"))
body = memoryview(payload)[start : end + 1]
self.send_response(206)
self.send_header("Content-Length", str(len(body)))
self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
self.send_header("x-lancedb-version", "1")
self.end_headers()
for offset in range(0, len(body), 8192):
self.wfile.write(body[offset : offset + 8192])
return
self.respond(
200,
json.dumps(
{
"table": "test",
"version": 1,
"schema": {"fields": []},
}
).encode(),
)
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
print(server.server_port, flush=True)
server.serve_forever()
def client(port, rows, row_mib):
import lancedb
db = lancedb.connect(
"db://rss-test", api_key="test", host_override=f"http://127.0.0.1:{port}"
)
table = db.open_table("test")
# Reset the Linux high-water mark after imports and connection setup.
with open("/proc/self/clear_refs", "w") as reset:
reset.write("5")
def memory_kib(field):
with open("/proc/self/status") as status:
return next(
int(line.split()[1]) for line in status if line.startswith(field + ":")
)
before = memory_kib("VmRSS")
values = table.fetch_blobs("image", list(range(rows)))
peak = memory_kib("VmHWM")
assert len(values) == rows
assert values.buffers()[2].size == rows * (row_mib << 20)
# Inspect slices without copying the result to Python bytes.
for i in (0, rows - 1):
assert values.slice(i, 1).buffers()[2][i * (row_mib << 20)] == ord("x")
print(
json.dumps(
{
"rows": rows,
"payload_mib": rows * row_mib,
"baseline_rss_kib": before,
"peak_rss_kib": peak,
"peak_delta_kib": peak - before,
"peak_delta_per_payload": (peak - before) / (rows * row_mib * 1024),
"rusage_maxrss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
}
),
flush=True,
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--rows", nargs="+", type=int, default=[48, 144])
parser.add_argument("--batch-rows", type=int, default=48)
parser.add_argument("--row-mib", type=int, default=1)
parser.add_argument("--serve", action="store_true")
parser.add_argument("--client", type=int)
args = parser.parse_args()
if args.serve:
serve(args.batch_rows, args.row_mib)
elif args.client is not None:
client(args.client, args.rows[0], args.row_mib)
else:
server = subprocess.Popen(
[
sys.executable,
__file__,
"--serve",
"--batch-rows",
str(args.batch_rows),
"--row-mib",
str(args.row_mib),
],
stdout=subprocess.PIPE,
text=True,
)
try:
port = server.stdout.readline().strip()
for rows in args.rows:
subprocess.run(
[
sys.executable,
__file__,
"--client",
port,
"--rows",
str(rows),
"--row-mib",
str(args.row_mib),
],
check=True,
)
finally:
server.terminate()
server.wait()
if __name__ == "__main__":
main()
+1 -1
View File
@@ -64,7 +64,7 @@ tests = [
"polars>=0.19, <=1.32.3",
"pyarrow>=16",
"pyarrow-stubs>=16.0",
"pylance==15.0.0b18",
"pylance==15.0.0b21",
"requests>=2.31.0",
"datafusion>=54,<55",
"opentelemetry-sdk>=1.30.0",
+19
View File
@@ -35,6 +35,15 @@ FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray]
FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]]
def _validate_blob_buffer_size(size: Optional[int]) -> Optional[int]:
if size is None:
return None
size = operator.index(size)
if size < 0:
raise ValueError("buffer_size must be non-negative")
return size
def _normalize_blob_descriptor(value):
if isinstance(value, pa.Scalar):
value = value.as_py()
@@ -58,6 +67,16 @@ class BlobFile(io.RawIOBase):
def __init__(self, inner) -> None:
self._inner = inner
def set_buffer_size(self, size: int) -> None:
"""Set sequential read-ahead bytes (default 512 KiB); 0 disables it.
Changing the size discards unused prefetched bytes without moving the
cursor. Explicit ``read_range`` and ``read_ranges`` bypass read-ahead.
"""
if self.closed:
raise ValueError("set_buffer_size of closed file")
self._inner.set_buffer_size(_validate_blob_buffer_size(size))
async def aread(self) -> bytes:
if self.closed:
raise ValueError("read of closed file")
+44 -8
View File
@@ -185,9 +185,14 @@ class Connection(object):
limit: Optional[int],
) -> list[str]: ... # Deprecated: Use list_tables instead
async def open_job(self, job_id: str) -> Job: ...
async def server_info(self) -> str: ...
async def list_gpu_classes(self) -> list[GpuClass]: ...
async def create_function_async(
self, request_json: str, namespace_path: Optional[List[str]] = None
self,
request_json: str,
namespace_path: Optional[List[str]] = None,
*,
exist_ok: bool = False,
) -> Job: ...
async def get_function(
self,
@@ -228,7 +233,12 @@ class Connection(object):
self, name: str, namespace_path: Optional[List[str]] = None
) -> None: ...
async def create_secret(
self, name: str, value: str, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
namespace_path: Optional[List[str]] = None,
*,
exist_ok: bool = False,
) -> None: ...
async def alter_secret(
self, name: str, value: str, namespace_path: Optional[List[str]] = None
@@ -247,7 +257,12 @@ class Connection(object):
self, name: str, namespace_path: Optional[List[str]] = None
) -> Tuple[str, int, int]: ...
async def create_view(
self, name: str, query: str, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
namespace_path: Optional[List[str]] = None,
*,
exist_ok: bool = False,
) -> Tuple[str, List[str], str, str, List[str], pa.Schema]: ...
async def describe_view(
self, name: str, namespace_path: Optional[List[str]] = None
@@ -332,6 +347,8 @@ class Connection(object):
source_version: Optional[int] = None,
source_tag: Optional[str] = None,
is_shallow: bool = True,
*,
exist_ok: bool = False,
) -> Table: ...
async def rename_table(
self,
@@ -343,24 +360,30 @@ class Connection(object):
async def create_materialized_view(
self,
name: str,
source: str,
source: Optional[str] = None,
projections: Optional[List[Tuple[str, str]]] = None,
filter: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
*,
query: Optional[str] = None,
exist_ok: bool = False,
) -> Table: ...
async def create_materialized_view_async(
self,
name: str,
source: str,
source: Optional[str] = None,
projections: Optional[List[Tuple[str, str]]] = None,
filter: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
*,
query: Optional[str] = None,
exist_ok: bool = False,
) -> Job: ...
def list_materialized_views(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
@@ -392,6 +415,7 @@ class BlobFile:
def seek(self, position: int) -> None: ...
def tell(self) -> int: ...
def size(self) -> int: ...
def set_buffer_size(self, size: int) -> None: ...
def read_range(self, offset: int, length: int) -> bytes: ...
def read_ranges(self, ranges: list[tuple[int, int]]) -> list[bytes]: ...
def read_up_to(self, length: int) -> bytes: ...
@@ -413,6 +437,7 @@ class Job:
async def cancel(self) -> None: ...
async def refresh(self) -> None: ...
async def timeline(self) -> str: ...
async def stats(self) -> Optional[str]: ...
async def events(
self,
*,
@@ -538,6 +563,7 @@ class Table:
progress: Optional[Any] = None,
write_parallelism: Optional[int] = None,
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult: ...
async def update(
self, updates: Dict[str, str], where: Optional[str]
@@ -566,6 +592,7 @@ class Table:
*,
name: Optional[str],
train: Optional[bool],
exist_ok: bool = False,
): ...
async def create_index_async(
self,
@@ -590,6 +617,7 @@ class Table:
*,
name: Optional[str],
train: Optional[bool],
exist_ok: bool = False,
) -> Job: ...
async def list_versions(self) -> List[Dict[str, Any]]: ...
async def version(self) -> int: ...
@@ -742,7 +770,12 @@ class Table:
def take_row_ids(self, row_ids: list[int]) -> TakeQuery: ...
async def blob_columns(self) -> list[str]: ...
async def fetch_blobs(
self, column: str, row_ids: list[int]
self,
column: str,
row_ids: list[int],
*,
version: Optional[int] = None,
snapshot_identity: Optional[str] = None,
) -> pa.LargeBinaryArray: ...
async def fetch_blob_ranges(
self,
@@ -750,9 +783,11 @@ class Table:
requests: Sequence[Sequence[int]],
) -> pa.LargeBinaryArray: ...
async def fetch_blob_files(
self, column: str, row_ids: list[int]
self, column: str, row_ids: list[int], buffer_size: Optional[int] = None
) -> list[Optional[BlobFile]]: ...
async def open_blob_file(self, descriptor: str) -> BlobFile: ...
async def open_blob_file(
self, descriptor: str, buffer_size: Optional[int] = None
) -> BlobFile: ...
def vector_search(self) -> VectorQuery: ...
class Tags:
@@ -1227,6 +1262,7 @@ async def connect_catalog(
sql_host_override: Optional[str] = None,
read_consistency_interval: Optional[float] = None,
oauth_config: Optional[Any] = None,
storage_options: Optional[dict[str, str]] = None,
) -> Catalog: ...
class NameListing:
+144 -10
View File
@@ -3,13 +3,17 @@
"""Remote catalogs manage databases."""
from functools import cached_property
import os
import warnings
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
from functools import cached_property
from typing import Any, AsyncIterator, Iterator, Optional, Union
from . import _lancedb
from .background_loop import LOOP
from .authz import AsyncAuthorization, Authorization
from .common import URI, sanitize_uri
from .db import AsyncConnection, DBConnection
from .remote import ClientConfig, OAuthConfig
from .remote.db import RemoteDBConnection
@@ -163,12 +167,14 @@ class Catalog:
client_config=None,
sql_host_override: Optional[str] = None,
oauth_config: Optional[OAuthConfig] = None,
storage_options: Optional[dict[str, str]] = None,
):
self._inner = inner
self._api_key = api_key
self._client_config = client_config
self._sql_host_override = sql_host_override
self._oauth_config = oauth_config
self._storage_options = storage_options
@cached_property
def authz(self) -> Authorization:
@@ -198,6 +204,7 @@ class Catalog:
self._client_config,
self._oauth_config,
self._sql_host_override,
self._storage_options,
)
def list_databases(
@@ -227,28 +234,71 @@ class Catalog:
async def connect_catalog_async(
endpoint: str,
uri: Optional[URI] = None,
*,
api_key: Optional[str] = None,
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
region: Optional[str] = None,
host_override: Optional[str] = None,
sql_host_override: Optional[str] = None,
read_consistency_interval: Optional[timedelta] = None,
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
storage_options: Optional[dict[str, str]] = None,
session: Optional[_lancedb.Session] = None,
manifest_enabled: bool = False,
namespace_client_properties: Optional[dict[str, str]] = None,
oauth_config: Optional[OAuthConfig] = None,
) -> AsyncCatalog:
"""Connect to an HTTP(S) server's root catalog.
"""Connect to a server's root catalog using database connection settings.
``host_override`` selects the HTTP(S) catalog endpoint when provided; otherwise
``uri`` must be an HTTP(S) endpoint. A ``db://`` URI can be shared with
[connect_async][lancedb.connect_async] when ``host_override`` is set: the URI's
database is ignored and requests target the root catalog.
``region`` is ignored with a warning when supplied. Catalog connections use
the explicit endpoint rather than a region-derived Cloud (legacy) endpoint.
``api_key`` defaults to the ``LANCEDB_API_KEY`` environment variable.
Embedded-only ``session``, ``manifest_enabled`` and
``namespace_client_properties`` are not supported.
Root requests omit database-selection headers. API key, client configuration,
OAuth, and table read consistency settings are inherited by opened databases.
OAuth, storage options, and table read consistency settings are inherited by
opened databases.
Database names containing slashes remain single logical names.
Set ``sql_host_override`` to the SQL service endpoint to execute SQL through
returned connections when the catalog endpoint uses HTTPS.
"""
if region is not None:
warnings.warn(
"region is ignored by connect_catalog_async; the catalog endpoint "
"is selected by host_override or uri.",
UserWarning,
stacklevel=2,
)
for name, value in (
("session", session),
("manifest_enabled", manifest_enabled or None),
("namespace_client_properties", namespace_client_properties),
):
if value is not None:
raise NotImplementedError(
f"{name} is not supported for catalog connections"
)
endpoint = host_override if host_override is not None else uri
if endpoint is None:
raise ValueError("uri or host_override is required for catalog connections")
if isinstance(client_config, dict):
client_config = ClientConfig(**client_config)
if client_config is None:
client_config = ClientConfig()
if (
api_key is None
and oauth_config is None
and client_config.header_provider is None
):
api_key = os.environ.get("LANCEDB_API_KEY")
inner = await _lancedb.connect_catalog(
endpoint,
sanitize_uri(endpoint),
api_key=api_key,
client_config=client_config,
sql_host_override=sql_host_override,
@@ -258,32 +308,115 @@ async def connect_catalog_async(
else None
),
oauth_config=oauth_config,
storage_options=storage_options,
)
return AsyncCatalog(inner)
def connect_catalog(
endpoint: str,
uri: Optional[URI] = None,
*,
api_key: Optional[str] = None,
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
region: Optional[str] = None,
host_override: Optional[str] = None,
sql_host_override: Optional[str] = None,
read_consistency_interval: Optional[timedelta] = None,
request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None,
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
storage_options: Optional[dict[str, str]] = None,
session: Optional[_lancedb.Session] = None,
manifest_enabled: bool = False,
namespace_client_impl: Optional[str] = None,
namespace_client_properties: Optional[dict[str, str]] = None,
namespace_client_pushdown_operations: Optional[list[str]] = None,
oauth_config: Optional[OAuthConfig] = None,
**kwargs: Any,
) -> Catalog:
"""Connect synchronously to an HTTP(S) server's root catalog.
"""Connect synchronously to a root catalog using database connection settings.
See [connect_catalog_async][lancedb.connect_catalog_async] for options.
The inputs match [connect][lancedb.connect]; ``region`` is ignored with a
warning when supplied. Namespace client options and embedded session settings
are not supported. ``request_thread_pool`` is deprecated and unused, as in
``connect``.
Local filesystem and object-store catalogs are not supported.
Examples
--------
```python
settings = {"api_key": "secret", "host_override": "https://my-server.example"}
catalog = lancedb.connect_catalog("db://analytics", **settings)
db = lancedb.connect("db://analytics", **settings)
```
"""
unknown_kwargs = {
key: value
for key, value in kwargs.items()
if key not in ("connection_timeout", "read_timeout")
}
if unknown_kwargs:
raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}")
for name, value in (
("namespace_client_impl", namespace_client_impl),
("namespace_client_pushdown_operations", namespace_client_pushdown_operations),
):
if value is not None:
raise NotImplementedError(
f"{name} is not supported for catalog connections"
)
if region is not None:
warnings.warn(
"region is ignored by connect_catalog; the catalog endpoint "
"is selected by host_override or uri.",
UserWarning,
stacklevel=2,
)
if request_thread_pool is not None:
warnings.warn(
"request_thread_pool is no longer used and will be removed in "
"a future release.",
DeprecationWarning,
stacklevel=2,
)
if isinstance(client_config, dict):
client_config = ClientConfig(**client_config)
if client_config is None:
client_config = ClientConfig()
for name, field in (
("connection_timeout", "connect_timeout"),
("read_timeout", "read_timeout"),
):
if kwargs.get(name) is not None:
warnings.warn(
f"{name} is deprecated and will be removed in a future release. "
f"Please use client_config.timeout_config.{field} instead.",
DeprecationWarning,
stacklevel=2,
)
setattr(
client_config.timeout_config,
field,
timedelta(seconds=kwargs[name]),
)
if (
api_key is None
and oauth_config is None
and client_config.header_provider is None
):
api_key = os.environ.get("LANCEDB_API_KEY")
return Catalog(
LOOP.run(
connect_catalog_async(
endpoint,
uri,
api_key=api_key,
host_override=host_override,
client_config=client_config,
sql_host_override=sql_host_override,
read_consistency_interval=read_consistency_interval,
storage_options=storage_options,
session=session,
manifest_enabled=manifest_enabled,
namespace_client_properties=namespace_client_properties,
oauth_config=oauth_config,
)
),
@@ -291,4 +424,5 @@ def connect_catalog(
client_config=client_config,
sql_host_override=sql_host_override,
oauth_config=oauth_config,
storage_options=storage_options,
)
+213 -35
View File
@@ -58,6 +58,7 @@ from lance_namespace import (
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
from . import __version__
from .server_info import ServerInfo
from ._lancedb import _append_doc_url, connect as lancedb_connect # type: ignore
from .functions import FunctionVersion, FunctionDefinition
from .graph import (
@@ -67,7 +68,7 @@ from .graph import (
PropertyGraph,
_definition_json,
)
from .job import AsyncJob, Job, _typed_job
from .job import AsyncJob, Job, _opened_job, _typed_job
from .storage_integration import SecretReference, StorageIntegrationInfo
from .sql import AsyncQuery as AsyncSqlQuery
from .sql import Query as SqlQuery
@@ -78,6 +79,7 @@ from .materialized_view import (
MaterializedViewSource,
SelectArg,
normalize_select,
_validate_create_materialized_view,
)
from .secrets import (
EnvVarSecret,
@@ -430,8 +432,12 @@ class DBConnection(EnforceOverrides):
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> StorageIntegrationInfo:
"""Register storage access, preserving existing configuration with
``exist_ok=True``. Existing names are errors by default.
"""
raise NotImplementedError
def describe_storage_integration(
@@ -697,17 +703,22 @@ class DBConnection(EnforceOverrides):
def create_materialized_view(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: SelectArg = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> MaterializedView:
"""Define a materialized view named ``name`` over the table ``source``.
``exist_ok=True`` preserves an existing view's definition, data and
refresh settings without refreshing it. Existing names error by default.
LanceDB Embedded creation and refresh require a source build with the
``experimental-functions`` Cargo feature. Published packages leave it
disabled; LanceDB Enterprise operations remain available.
@@ -721,8 +732,12 @@ class DBConnection(EnforceOverrides):
----------
name: str
The name of the view.
source: str
The name of the source table.
source: str, optional
The name of the source table. Required when ``query`` is omitted.
query: str, optional
The complete defining SQL query, including any GROUP BY or FROM
Function. Mutually exclusive with ``source``, ``select``, ``where``
and ``limit``. Supported query shapes depend on the backend.
select: list or dict, optional
The view's columns: column names, ``(alias, SQL expression)``
pairs, or a dict of the same. Omitting it selects every source
@@ -744,6 +759,13 @@ class DBConnection(EnforceOverrides):
Returns
-------
MaterializedView
Examples
--------
>>> view = db.create_materialized_view( # doctest: +SKIP
... "events_by_kind",
... query="SELECT kind, count(*) AS n FROM events GROUP BY kind",
... )
"""
raise NotImplementedError(
_append_doc_url(
@@ -755,17 +777,22 @@ class DBConnection(EnforceOverrides):
def create_materialized_view_async(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: SelectArg = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
"""Submit materialized-view creation and return its job.
``exist_ok=True`` preserves an existing view without refreshing it.
A skipped creation returns a completed job without a registry job ID.
The job may already be complete in LanceDB Embedded. In LanceDB
Distributed, creation submits CREATE MATERIALIZED VIEW through the SQL
server and the returned ``id`` is the registry job ID. That ID can be
@@ -989,10 +1016,14 @@ class DBConnection(EnforceOverrides):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> FunctionVersion:
"""Build and register a scalar Python function, then return its version.
``exist_ok=True`` returns the existing named Function version unchanged.
By default, registration retains its existing version-creation behavior.
The server builds the OCI image and registers the completed artifact.
This is the blocking counterpart of :meth:`create_function_async`.
LanceDB Embedded connections raise ``NotImplementedError``.
@@ -1025,7 +1056,10 @@ class DBConnection(EnforceOverrides):
```
"""
return self.create_function_async(
definition, secrets=secrets, namespace_path=namespace_path
definition,
secrets=secrets,
exist_ok=exist_ok,
namespace_path=namespace_path,
).wait()
def create_function_async(
@@ -1033,10 +1067,14 @@ class DBConnection(EnforceOverrides):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> Job[FunctionVersion]:
"""Submit a scalar Python function for building and registration.
``exist_ok=True`` preserves an existing named version and its metadata.
The default retains the existing version-creation behavior.
The server-side job builds the OCI image, then registers the completed
artifact. The returned job has type ``query`` and the SQL query UUID as
its ID. Waiting on it returns the immutable Function version.
@@ -1158,14 +1196,24 @@ class DBConnection(EnforceOverrides):
)
def create_secret(
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> None:
"""Create a named Secret in this database.
Fails if the name is taken, so a create never silently becomes a
rotation. Nothing reads the value back: it is bound to a Function by
Fails if the name is taken unless ``exist_ok=True``, which leaves the
existing value unchanged. Use :meth:`alter_secret` to rotate a Secret.
Nothing reads the value back: it is bound to a Function by
name and resolved by the service when that Function runs. Local
connections raise ``NotImplementedError``.
Examples
--------
>>> db.create_secret("api-key", "credential", exist_ok=True) # doctest: +SKIP
"""
raise NotImplementedError(
_append_doc_url(
@@ -1248,7 +1296,12 @@ class DBConnection(EnforceOverrides):
)
def create_view(
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> ViewDescription:
"""Create a view: a named query the database plans on every read.
@@ -1256,9 +1309,10 @@ class DBConnection(EnforceOverrides):
is refused now rather than at the first read. A view holds no rows, and
its readers see its sources as they are at read time.
There is no replace: a name already taken is an error, and changing a
view is a drop followed by a create. LanceDB Embedded connections raise
``NotImplementedError``.
A name already taken is an error unless ``exist_ok=True``, which returns
the existing view's stored query and schema without changing them.
Changing a view is a drop followed by a create. LanceDB Embedded
connections raise ``NotImplementedError``.
>>> import lancedb
>>> db = lancedb.connect("db://my_database") # doctest: +SKIP
@@ -1450,6 +1504,12 @@ class DBConnection(EnforceOverrides):
specification, result, failure and event history, so there is no
separate connection-level call for any of them.
For a column refresh, ``wait()`` returns a
[RefreshColumnResult][lancedb.functions.RefreshColumnResult], including
when the refresh was started through SQL. Other job types return
``None`` from ``wait()``; their persisted result is available through
``job.result`` after ``job.refresh()``.
Raises `JobNotFoundError` when the server has no such job, the way
`open_table` does for a missing table.
"""
@@ -1460,6 +1520,22 @@ class DBConnection(EnforceOverrides):
)
)
def server_info(self) -> ServerInfo:
"""Return the responding server's build and Function runtime information.
This call submits no query, Function, or job. The response is a
JSON-compatible dictionary, convenient to include in a bug report::
info = db.server_info()
print(info["query_node"]) # release, git_sha, build_date
Requires System Usage permission. Embedded connections and older
servers without this endpoint raise ``NotImplementedError``.
Different calls can reach different builds during a rolling upgrade.
Configured images do not identify the version of a running job.
"""
raise NotImplementedError("Server build discovery requires a remote connection")
def list_gpu_classes(self) -> List[GpuClass]:
"""List the operator-configured Function GPU classes.
@@ -2075,17 +2151,22 @@ class LanceDBConnection(DBConnection):
def create_materialized_view(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: SelectArg = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> MaterializedView:
"""Define a materialized view named ``name`` over the table ``source``.
``exist_ok=True`` preserves an existing view's definition, data and
refresh settings without refreshing it. Existing names error by default.
LanceDB Embedded creation and refresh require a source build with the
``experimental-functions`` Cargo feature. Published packages leave it
disabled; LanceDB Enterprise operations remain available.
@@ -2111,10 +2192,12 @@ class LanceDBConnection(DBConnection):
self._conn.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
@@ -2125,12 +2208,14 @@ class LanceDBConnection(DBConnection):
def create_materialized_view_async(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: SelectArg = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
@@ -2138,10 +2223,12 @@ class LanceDBConnection(DBConnection):
self._conn.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
@@ -2199,6 +2286,7 @@ class LanceDBConnection(DBConnection):
source_version: Optional[int] = None,
source_tag: Optional[str] = None,
is_shallow: bool = True,
exist_ok: bool = False,
) -> LanceTable:
"""Clone a table from a source table.
@@ -2223,6 +2311,8 @@ class LanceDBConnection(DBConnection):
is_shallow: bool, default True
Whether to perform a shallow clone (True) or deep clone (False).
Currently only shallow clone is supported.
exist_ok: bool, default False
Return the existing target unchanged instead of cloning over it.
Returns
-------
@@ -2238,6 +2328,7 @@ class LanceDBConnection(DBConnection):
source_version=source_version,
source_tag=source_tag,
is_shallow=is_shallow,
exist_ok=exist_ok,
)
)
return LanceTable.open(
@@ -2339,11 +2430,15 @@ class LanceDBConnection(DBConnection):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> Job[FunctionVersion]:
job = LOOP.run(
self._conn.create_function_async(
definition, secrets=secrets, namespace_path=namespace_path
definition,
secrets=secrets,
exist_ok=exist_ok,
namespace_path=namespace_path,
)
)
return Job(job)
@@ -2431,6 +2526,7 @@ class LanceDBConnection(DBConnection):
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> StorageIntegrationInfo:
return LOOP.run(
@@ -2448,6 +2544,7 @@ class LanceDBConnection(DBConnection):
azure_client_secret_secret=azure_client_secret_secret,
gcp_credentials_json_secret=gcp_credentials_json_secret,
huggingface_token_secret=huggingface_token_secret,
exist_ok=exist_ok,
namespace_path=namespace_path,
)
)
@@ -2486,9 +2583,18 @@ class LanceDBConnection(DBConnection):
@override
def create_secret(
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> None:
LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path))
LOOP.run(
self._conn.create_secret(
name, value, exist_ok=exist_ok, namespace_path=namespace_path
)
)
@override
def alter_secret(
@@ -2532,10 +2638,17 @@ class LanceDBConnection(DBConnection):
@override
def create_view(
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> ViewDescription:
return LOOP.run(
self._conn.create_view(name, query, namespace_path=namespace_path)
self._conn.create_view(
name, query, exist_ok=exist_ok, namespace_path=namespace_path
)
)
@override
@@ -3348,26 +3461,37 @@ class AsyncConnection(object):
async def create_materialized_view(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: SelectArg = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> AsyncMaterializedView:
"""Define a materialized view named ``name`` over the table ``source``.
``exist_ok=True`` preserves an existing view's definition, data and
refresh settings without refreshing it. Existing names error by default.
LanceDB Embedded creation and refresh require a source build with the
``experimental-functions`` Cargo feature. Published packages leave it
disabled; LanceDB Enterprise operations remain available.
See
[DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view].
"""
source, native_options = await self._materialized_view_source(
source, select, where, limit
)
_validate_create_materialized_view(source, query, select, where, limit)
if source is not None:
source, native_options = await self._materialized_view_source(
source, select, where, limit
)
else:
native_options = {}
if query is not None:
native_options["query"] = query
inner = await self._inner.create_materialized_view(
name,
source,
@@ -3375,6 +3499,7 @@ class AsyncConnection(object):
filter=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
**native_options,
@@ -3384,24 +3509,35 @@ class AsyncConnection(object):
async def create_materialized_view_async(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: SelectArg = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> AsyncJob[None]:
"""Submit materialized-view creation and return its job.
``exist_ok=True`` preserves an existing view without refreshing it.
A skipped creation returns a completed job without a registry job ID.
Wait for the returned job before opening or querying the view. In LanceDB
Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id``
identifies that query on this connection.
"""
source, native_options = await self._materialized_view_source(
source, select, where, limit
)
_validate_create_materialized_view(source, query, select, where, limit)
if source is not None:
source, native_options = await self._materialized_view_source(
source, select, where, limit
)
else:
native_options = {}
if query is not None:
native_options["query"] = query
inner = await self._inner.create_materialized_view_async(
name,
source,
@@ -3409,6 +3545,7 @@ class AsyncConnection(object):
filter=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
**native_options,
@@ -3487,6 +3624,7 @@ class AsyncConnection(object):
source_version: Optional[int] = None,
source_tag: Optional[str] = None,
is_shallow: bool = True,
exist_ok: bool = False,
) -> AsyncTable:
"""Clone a table from a source table.
@@ -3511,6 +3649,8 @@ class AsyncConnection(object):
is_shallow: bool, default True
Whether to perform a shallow clone (True) or deep clone (False).
Currently only shallow clone is supported.
exist_ok: bool, default False
Return the existing target unchanged instead of cloning over it.
Returns
-------
@@ -3525,6 +3665,7 @@ class AsyncConnection(object):
source_version=source_version,
source_tag=source_tag,
is_shallow=is_shallow,
exist_ok=exist_ok,
)
return AsyncTable(table)
@@ -3626,7 +3767,13 @@ class AsyncConnection(object):
"""Open a server-side job by id. See
[DBConnection.open_job][lancedb.db.DBConnection.open_job].
"""
return AsyncJob(await self._inner.open_job(job_id))
return _opened_job(await self._inner.open_job(job_id))
async def server_info(self) -> ServerInfo:
"""Read the responding server's build information. See
[DBConnection.server_info][lancedb.db.DBConnection.server_info].
"""
return json.loads(await self._inner.server_info())
async def list_gpu_classes(self) -> List[GpuClass]:
"""List configured Function GPU classes. See
@@ -3639,10 +3786,14 @@ class AsyncConnection(object):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> AsyncJob[FunctionVersion]:
"""Submit a scalar Python function for building and registration.
``exist_ok=True`` preserves an existing named version and its metadata.
The default retains the existing version-creation behavior.
The server-side job builds the OCI image, then registers the completed
artifact. The returned job has type ``query`` and the SQL query UUID as
its ID. Waiting on it returns the immutable Function version.
@@ -3656,7 +3807,7 @@ class AsyncConnection(object):
raise TypeError("create_function_async requires a @function definition")
request = definition.bind_secrets(secrets)
inner = await self._inner.create_function_async(
request.to_canonical_json(), namespace_path
request.to_canonical_json(), namespace_path, exist_ok=exist_ok
)
return _typed_job(inner, FunctionVersion.from_json)
@@ -3776,6 +3927,7 @@ class AsyncConnection(object):
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> StorageIntegrationInfo:
"""Register cloud storage access using database-owned credential Secrets.
@@ -3790,6 +3942,10 @@ class AsyncConnection(object):
optionally set ``huggingface_token_secret`` to a Secret containing the
token; omitting it selects anonymous access at the default rate limits.
Registration returns setup instructions without verifying storage access.
``exist_ok=True`` returns the stored configuration unchanged when the
integration exists, preserving its provider, prefix and credential
bindings. Existing names are errors by default.
"""
azure_options = (
azure_tenant_id_secret,
@@ -3898,6 +4054,8 @@ class AsyncConnection(object):
"aws_access_key_id_secret": reference(aws_access_key_id_secret),
"aws_secret_access_key_secret": reference(aws_secret_access_key_secret),
}
if exist_ok:
request["exist_ok"] = True
info = await self._inner.create_storage_integration(
validate_secret_name(name),
json.dumps(request),
@@ -3943,17 +4101,30 @@ class AsyncConnection(object):
)
async def create_secret(
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> None:
"""Create a named Secret in this database.
Fails if the name is taken, so a create never silently becomes a
rotation. Nothing reads the value back.
Fails if the name is taken unless ``exist_ok=True``, which leaves the
existing value unchanged. Use :meth:`alter_secret` to rotate a Secret.
Nothing reads the value back.
Examples
--------
>>> await db.create_secret( # doctest: +SKIP
... "api-key", "credential", exist_ok=True
... )
"""
await self._inner.create_secret(
validate_secret_name(name),
value,
list(validate_namespace_path(namespace_path)),
exist_ok=exist_ok,
)
async def alter_secret(
@@ -4014,7 +4185,12 @@ class AsyncConnection(object):
)
async def create_view(
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> ViewDescription:
"""Create a view: a named query the database plans on every read.
@@ -4022,7 +4198,9 @@ class AsyncConnection(object):
[DBConnection.create_view][lancedb.DBConnection.create_view].
"""
return _view_description(
await self._inner.create_view(name, query, list(namespace_path or []))
await self._inner.create_view(
name, query, list(namespace_path or []), exist_ok=exist_ok
)
)
async def describe_view(
+127 -55
View File
@@ -22,6 +22,7 @@ import symtable
import json
import linecache
import math
import os
import re
import sys
import textwrap
@@ -29,6 +30,7 @@ import types
import warnings
from collections.abc import Mapping, Sequence
from datetime import date, datetime
from pathlib import Path
from typing import (
Annotated,
Any,
@@ -1529,6 +1531,17 @@ def _infer_signature(
return FunctionSignature(inputs=tuple(inputs), output=output)
def _is_vectorized_callable(function: Callable[..., Any], *, method: bool) -> bool:
parameters = _callable_parameters(function)
if method:
parameters = parameters[1:]
annotations = get_type_hints(function, include_extras=True)
annotated = tuple(annotations.get(parameter.name) for parameter in parameters)
return (len(annotated) == 1 and annotated[0] is pa.RecordBatch) or (
bool(annotated) and all(annotation is pa.Array for annotation in annotated)
)
# Both spellings strip from packaged source; `udf` is the deprecated alias.
_DECORATOR_NAMES = frozenset({"function", "udf"})
@@ -1570,10 +1583,23 @@ _NAMESPACE_MODULES = frozenset(
)
def _namespace_acquisition(
definition: ast.FunctionDef, references: set[str]
) -> list[str]:
found = set(references & _DYNAMIC_NAMESPACE_ACCESS)
_NAMESPACE_HELPER_HINT = (
"Move this code into an importable helper module supplied with code=, pip=, "
"or conda=, then import and call the helper from the Function."
)
def _namespace_import_error(modules: Sequence[str]) -> ValueError:
return ValueError(
f"@function cannot package imports from namespace-access modules: {modules!r}. "
f"Imports of {', '.join(sorted(_NAMESPACE_MODULES))} (including submodules) "
"are blocked because they can access names outside the packaged "
"Function's reconstructed module namespace. " + _NAMESPACE_HELPER_HINT
)
def _namespace_imports(definition: Union[ast.FunctionDef, ast.ClassDef]) -> list[str]:
found: set[str] = set()
for node in ast.walk(definition):
if isinstance(node, ast.Import):
found.update(
@@ -1883,11 +1909,17 @@ class _SourcePackager:
)
source = ast.unparse(definition)
references = _module_references(f"{_SOURCE_HEADER}\n\n{source}\n")
dynamic = _namespace_acquisition(definition, references)
dynamic = sorted(references & _DYNAMIC_NAMESPACE_ACCESS)
if dynamic:
raise ValueError(
f"@function cannot package dynamic namespace access: {dynamic!r}"
f"@function cannot package dynamic namespace access: {dynamic!r}. "
"These operations can access names outside the packaged "
"Function's reconstructed module namespace. Reference dependencies "
"explicitly. " + _NAMESPACE_HELPER_HINT
)
namespace_imports = _namespace_imports(definition)
if namespace_imports:
raise _namespace_import_error(namespace_imports)
self._warn_unshipped_direct_imports(definition)
self._packaged.add(id(target))
self._claim(target.__name__, ("definition", id(target)))
@@ -1982,10 +2014,7 @@ class _SourcePackager:
return f"from lance_blob import BlobReader as {name}"
if isinstance(value, types.ModuleType):
if value.__name__.split(".")[0] in _NAMESPACE_MODULES:
raise ValueError(
"@function cannot package dynamic namespace access: "
f"{value.__name__!r}"
)
raise _namespace_import_error([value.__name__])
try:
imported = importlib.import_module(value.__name__)
except ImportError:
@@ -2077,18 +2106,12 @@ class _SourcePackager:
self._require_importable(node.module)
def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]:
"""The Python source files of the modules and packages in ``code=``,
keyed by their path on the Function's import path.
Package resources are not part of the source artifact. Warn about files
and excluded directories that the walk leaves behind instead of silently
producing a Function that will fail later on the worker.
"""
import os
from pathlib import Path
def _code_files(
modules: Sequence[Any],
) -> tuple[dict[str, str], dict[str, str], frozenset[str]]:
"""Source and byte-preserving package resources on the Function import path."""
files: dict[str, str] = {}
resources: dict[str, str] = {}
names: set[str] = set()
for module in modules:
if not isinstance(module, types.ModuleType):
@@ -2122,35 +2145,50 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]
sources = []
skipped = set()
for directory, subdirectories, filenames in os.walk(root):
# Only importable modules travel: data files, caches, and
# directories that are not identifiers cannot be imported.
kept = []
for child in sorted(subdirectories):
if child == "__pycache__":
path = Path(directory) / child
if child == "__pycache__" or child.startswith("."):
continue
if _SOURCE_PATH_COMPONENT.fullmatch(child):
if not path.is_symlink() and re.fullmatch(
r"[A-Za-z0-9_][A-Za-z0-9_.-]*", child
):
kept.append(child)
else:
relative = (Path(directory) / child).relative_to(root)
relative = path.relative_to(root)
skipped.add(f"{name}/{relative.as_posix()}/")
subdirectories[:] = kept
for filename in sorted(filenames):
path = Path(directory) / filename
stem, suffix = os.path.splitext(filename)
if suffix in {".pyc", ".pyo"}:
if suffix in {".pyc", ".pyo"} or filename.startswith("."):
continue
if suffix == ".py" and _SOURCE_PATH_COMPONENT.fullmatch(stem):
sources.append(Path(directory) / filename)
relative = path.relative_to(root)
key = f"{name}/{relative.as_posix()}"
if (
path.is_symlink()
or not path.is_file()
or not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", filename)
):
skipped.add(key)
elif suffix == ".py":
if all(
_SOURCE_PATH_COMPONENT.fullmatch(part)
for part in relative.with_suffix("").parts
):
sources.append(path)
else:
skipped.add(key)
else:
relative = (Path(directory) / filename).relative_to(root)
skipped.add(f"{name}/{relative.as_posix()}")
resources[key] = base64.b64encode(path.read_bytes()).decode(
"ascii"
)
if skipped:
skipped_paths = ", ".join(sorted(skipped))
warnings.warn(
f"code= ships Python .py modules only; package {name!r} "
f"will not include: {skipped_paths}. Install a package that "
"includes the required resources with pip= or conda=, and "
f"remove {name!r} from code= so the copied package cannot "
"shadow the installed distribution.",
"code= cannot ship these package paths: "
f"{', '.join(sorted(skipped))}. "
"Use regular files with safe relative names and importable "
"Python module names.",
UserWarning,
)
for path in sources:
@@ -2161,12 +2199,12 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]
if not file or not file.endswith(".py"):
raise ValueError(f"code= ships Python source; module {name!r} has none")
files[f"{name}.py"] = _source_text(Path(file))
return files, frozenset(names)
return files, resources, frozenset(names)
def _source_text(path) -> str:
try:
return path.read_text(encoding="utf-8")
return path.read_bytes().decode("utf-8")
except UnicodeDecodeError as error:
raise ValueError(f"code= ships UTF-8 source; {path} is not UTF-8") from error
@@ -2286,7 +2324,9 @@ class FunctionDefinition:
once per row. A callable whose parameters are all annotated as
``pyarrow.Array`` receives whole Arrow arrays and returns a
``pyarrow.Array`` instead. This authoring choice is independent of the
internal artifact adapter in the registration request.
internal artifact adapter in the registration request. GPU Functions should
use the Arrow form when the model supports batches: a scalar GPU callable is
invoked once per row and leaves the model's own batching unavailable.
"""
def __init__(
@@ -2408,14 +2448,29 @@ class FunctionDefinition:
signature = signature._copy(update={"initialization": initialization})
else:
signature = _infer_signature(function, input_schema, output_schema)
code_files, code_modules = _code_files(code)
if gpu_marker is not None:
call = _class_call(function) if is_class else function
if not _is_vectorized_callable(call, method=is_class):
warnings.warn(
f"GPU Function {function_name!r} uses a scalar callable, so each "
"row invokes it separately and its model batch is not inferred. "
"For GPU throughput, annotate every input as pyarrow.Array or "
"take one pyarrow.RecordBatch, provide input_schema and "
"output_schema, and batch inside that callable.",
UserWarning,
stacklevel=3,
)
code_files, code_resources, code_modules = _code_files(code)
entry_source = _SourcePackager(
code_modules, frozenset(_requirement_name(package) for package in packages)
).package(function, signature)
if code_files:
kind = _PYTHON_BUNDLE_ARTIFACT
bundle = {"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}}
if code_resources:
bundle["resources"] = code_resources
source = json.dumps(
{"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}},
bundle,
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
@@ -2663,13 +2718,28 @@ def function(
Other global values, including Arrow types and schemas, lists, dictionaries,
sets, and NumPy arrays, cannot be captured as literals. Define them inside
the function or class body instead.
Closures, lambdas, nested definitions, mutable module-level
objects, code that reaches the module namespace another way
(``globals()``/``eval``, ``sys.modules``, ``builtins``), and a
Closures, lambdas, nested definitions, mutable module-level objects, and a
non-standard ``__builtins__`` are rejected where they can be seen and
otherwise unsupported. Changing any packaged source, including a module in
``code``, produces a new Function version; the environment built from
``pip`` or ``conda`` is reused.
otherwise unsupported.
**Namespace restrictions.** The packaged source cannot import ``sys``,
``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``,
including submodules such as ``ctypes.util`` and ``importlib.metadata``.
Referencing a module-level alias for one of these modules is also rejected.
References to ``globals``, ``locals``, ``vars``, ``eval``, ``exec``,
``compile``, or ``__import__`` are rejected as dynamic namespace access.
These restrictions are conservative: even ordinary uses such as
``ctypes.util.find_library`` or ``sys.version`` are blocked because these
modules can reach names outside the reconstructed Function namespace.
Move such code into an importable helper module supplied with ``code=``,
``pip=``, or ``conda=``, then import and call the helper from the Function.
Helpers imported normally keep their own module namespace; these checks do
not scan their bodies. A helper defined in ``__main__`` is packaged by source
and is subject to the same checks.
Changing any packaged source, including a module in ``code``, produces a
new Function version; the environment built from ``pip`` or ``conda`` is
reused.
Parameters
----------
@@ -2746,13 +2816,15 @@ def function(
immutable Function version; per-refresh aggregate GPU budgets are
selected through ``refresh_column`` instead of registration.
code : sequence of module, optional
Top-level modules or packages whose importable ``.py`` files ship
with the Function and are importable by their own names. Package data
files are not copied. To use a package that includes required data
resources, install it with ``pip=`` or ``conda=`` and remove that
package from ``code=`` so the copied Python package cannot shadow the
installed distribution. ``@function`` warns when it skips files from a
package in ``code=``.
Top-level modules or packages shipped with the Function and importable
by their own names. Package resources, including binary data and
vendored subpackages, retain their relative paths and exact bytes.
Source and resource changes both create a new Function version.
Caches and hidden paths are excluded. Symlinks and unsafe paths are
skipped with a warning. Compiled dependencies must match the remote
runtime; use ``pip=`` or ``conda=`` for platform-specific distributions
and ``models=`` for large model snapshots. Resource bundles require
server support for the ``python_bundle.resources`` field.
models : sequence of HuggingFaceModel, optional
Immutable Hugging Face repository snapshots prepared in the worker
node cache before user code starts. A Function may declare a
+48
View File
@@ -17,6 +17,7 @@ from lancedb.background_loop import LOOP
from . import _lancedb
from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url
from .functions import RefreshColumnResult
from .remote.errors import HttpError, RetryError
T = TypeVar("T")
@@ -424,6 +425,32 @@ class AsyncJob(Generic[T]):
description = self._inner._description if self._inner is not None else None
return getattr(description, name) if description is not None else None
async def stats(self) -> Optional[str]:
"""Return a printable run report for this Function job.
The report includes recorded phase timings, finishing-supervisor slot
occupancy, all-attempt split execution and batch latency, and accepted-row
throughput. Each call reads the current server report.
Returns ``None`` while the job is running or if no recorded profile is
available, without waiting for completion. Missing measurements remain
unavailable rather than becoming zero. The server formats the report;
the SDK returns it verbatim.
Requires a server-side Function job and a server supporting run reports.
Local operations and SQL query handles do not support this operation.
Unsupported operations raise ``NotImplementedError`` or a server error.
This method returns text; use ``print`` to display it.
Examples
--------
>>> print(await job.stats()) # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"job statistics require a server-side Function job"
)
return await self._inner.stats()
async def export_timeline(self, path: str | PathLike[str]) -> None:
"""Write a fresh recorded Function job timeline as Chrome trace JSON.
@@ -648,6 +675,21 @@ class Job(Generic[T]):
def _field(self, name: str) -> Optional[Any]:
return getattr(self._inner, name) if self._inner is not None else None
def stats(self) -> Optional[str]:
"""Return a printable Function job run report.
See [AsyncJob.stats][lancedb.job.AsyncJob.stats] for metrics and availability.
Examples
--------
>>> print(job.stats()) # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"job statistics require a server-side Function job"
)
return LOOP.run(self._inner.stats())
def export_timeline(self, path: str | PathLike[str]) -> None:
"""Write Chrome trace JSON for this Function job.
@@ -692,3 +734,9 @@ def _typed_job(
) -> AsyncJob[T]:
"""Bind an internal JSON-producing job to its public result model."""
return AsyncJob(inner, result_decoder)
def _opened_job(inner: "_lancedb.Job") -> AsyncJob:
if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"):
return _typed_job(inner, RefreshColumnResult.from_json)
return AsyncJob(inner)
@@ -134,6 +134,16 @@ def _quote_identifier(name: str) -> str:
return f"`{escaped}`"
def _validate_create_materialized_view(source, query, select, where, limit):
if query is not None:
if any(value is not None for value in (source, select, where, limit)):
raise ValueError(
"query cannot be combined with source, select, where or limit"
)
elif source is None:
raise ValueError("either source or query must be provided")
def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]:
"""``select`` items may be a column name, an ``(alias, expression)`` pair,
or a dict of the same. A bare name projects itself and is quoted, so any
+20 -4
View File
@@ -696,14 +696,16 @@ class LanceNamespaceDBConnection(DBConnection):
def create_materialized_view(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: "SelectArg" = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
exist_ok: bool = False,
) -> "MaterializedView":
"""Define a materialized view over a table in the root namespace.
See
@@ -715,12 +717,14 @@ class LanceNamespaceDBConnection(DBConnection):
self._inner.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
).name
)
@@ -730,25 +734,29 @@ class LanceNamespaceDBConnection(DBConnection):
def create_materialized_view_async(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: "SelectArg" = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
exist_ok: bool = False,
) -> Job[None]:
job = LOOP.run(
self._inner.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
)
return Job(job)
@@ -1339,25 +1347,29 @@ class AsyncLanceNamespaceDBConnection:
async def create_materialized_view(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: "SelectArg" = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
exist_ok: bool = False,
) -> "AsyncMaterializedView":
"""Define a materialized view over a table in the root namespace."""
view = await self._inner.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
# Reopen through the namespace so the view's table carries the
# namespace client and pushdown configuration a bare inner table lacks.
@@ -1366,25 +1378,29 @@ class AsyncLanceNamespaceDBConnection:
async def create_materialized_view_async(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: "SelectArg" = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
exist_ok: bool = False,
) -> AsyncJob[None]:
"""Submit materialized-view creation and return its job."""
return await self._inner.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
async def open_materialized_view(self, name: str) -> "AsyncMaterializedView":
+110 -28
View File
@@ -4,6 +4,7 @@
from __future__ import annotations
import asyncio
import re
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
@@ -194,20 +195,57 @@ def _unsupported_blob_pandas_error(reason: str) -> RuntimeError:
)
def _supports_local_blob_fetch(
def _supports_blob_fetch(
async_table: "AsyncTable", pushdown_operations: Iterable[str]
) -> bool:
# Remote tables and QueryTable pushdown answer queries on a server, so a
# fetch through this handle could read another version.
return async_table._inner._is_native() and "QueryTable" not in pushdown_operations
# Remote queries carry their producing snapshot in response metadata.
# Namespace QueryTable pushdown has no equivalent snapshot contract.
return (
not async_table._inner._is_native() or "QueryTable" not in pushdown_operations
)
def _remote_blob_snapshot(schema: pa.Schema) -> tuple[int, str]:
value = (schema.metadata or {}).get(b"lancedb:query_version", b"")
if not value.isdigit() or not 0 < int(value) < 2**64:
raise NotImplementedError(
"blob_mode='bytes' requires a stable table snapshot: the query response "
"has a missing, invalid, or inconsistent x-lancedb-query-version header. "
"Upgrade the server and use a table without Realtime/MemWAL, or use "
"blob_mode='descriptions'."
)
identity = (schema.metadata or {}).get(b"lancedb:query_snapshot", b"")
if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
raise NotImplementedError(
"blob_mode='bytes' requires a trustworthy query snapshot identity: "
"missing or unsupported x-lancedb-query-snapshot. Upgrade the server "
"on every serving node, or use blob_mode='descriptions'."
)
return int(value), identity.decode("ascii")
def _merge_query_snapshot(result: pa.Table, *sources: pa.Table) -> pa.Table:
"""Preserve a snapshot only when every query leg used the same identity."""
keys = (b"lancedb:query_version", b"lancedb:query_snapshot")
snapshots = {
tuple((source.schema.metadata or {}).get(key) for key in keys)
for source in sources
}
metadata = dict(result.schema.metadata or {})
for key in keys:
metadata.pop(key, None)
snapshot = next(iter(snapshots)) if len(snapshots) == 1 else None
if snapshot is not None and all(value is not None for value in snapshot):
metadata.update(zip(keys, snapshot))
return result.replace_schema_metadata(metadata)
def _blob_bytes_without_snapshot_error() -> NotImplementedError:
return NotImplementedError(
"blob_mode='bytes' cannot safely materialize blob columns without a "
"stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown "
"run the query on a server, so the blob fetch could read another table "
"version. Use blob_mode='descriptions' to inspect descriptors. To read "
"stable table snapshot. Namespace QueryTable pushdown does not bind "
"the query and blob fetches to one table version. "
"Use blob_mode='descriptions' to inspect descriptors. To read "
"payloads, select row IDs with with_row_id(True), then call "
"table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, "
"row_ids). Keep the source unchanged between selection and fetching."
@@ -1297,9 +1335,9 @@ class LanceQueryBuilder(ABC):
columns without pylance. Other local blob v2 queries return
descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads
in ``"bytes"`` mode, through :meth:`to_arrow`.
LanceDB Enterprise blob queries support only ``"descriptions"`` until a
stable
table snapshot can bind the query and blob fetches.
Enterprise queries support ``"bytes"`` at the query response's
snapshot and ``"descriptions"`` without payload reads. Remote
``"lazy"`` handles are not supported.
**kwargs
Forwarded to pyarrow.Table.to_pandas after query execution and
optional flattening.
@@ -1307,6 +1345,10 @@ class LanceQueryBuilder(ABC):
validate_blob_mode(blob_mode)
if _is_remote_query_table(self._table):
blob_sources = self._validated_blob_sources(blob_mode)
if blob_mode == "bytes":
return flatten_columns(
self.to_arrow(timeout=timeout, blob_mode=blob_mode), flatten
).to_pandas(**kwargs)
return _finish_remote_pandas(
self.to_arrow(timeout=timeout),
blob_mode=blob_mode,
@@ -1629,7 +1671,8 @@ class LanceQueryBuilder(ABC):
_query_is_plain_blob_scan(query)
and getattr(self, "_reranker", None) is None
and not _query_needs_lance_scanner(self)
and _supports_local_blob_fetch(
and self._table._table._inner._is_native()
and _supports_blob_fetch(
self._table._table,
getattr(self._table, "_pushdown_operations", ()),
)
@@ -1650,11 +1693,12 @@ class LanceQueryBuilder(ABC):
if blob_mode != "bytes":
return blob_sources
reject_unfetchable_blob_columns(schema, self._columns, blob_sources)
if blob_sources and not _supports_local_blob_fetch(
if blob_sources and not _supports_blob_fetch(
self._table._table, getattr(self._table, "_pushdown_operations", ())
):
raise _blob_bytes_without_snapshot_error()
reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources)
if not _is_remote_query_table(self._table):
reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources)
return blob_sources
def _blob_output_schema(self) -> pa.Schema:
@@ -1667,9 +1711,20 @@ class LanceQueryBuilder(ABC):
return tbl
if blob_mode == "descriptions":
return strip_auto_row_ids(tbl, blob_sources)
return replace_blob_columns_with_bytes_sync(
tbl, blob_sources, self._table.fetch_blobs
)
reject_unmatched_blob_outputs(tbl.schema, blob_sources)
if _is_remote_query_table(self._table) and blob_sources:
version, identity = _remote_blob_snapshot(tbl.schema)
async def fetch_at_version(column, row_ids):
return await self._table._table._inner.fetch_blobs(
column, row_ids, version=version, snapshot_identity=identity
)
def fetch_blobs(column, row_ids):
return LOOP.run(fetch_at_version(column, row_ids))
else:
fetch_blobs = self._table.fetch_blobs
return replace_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs)
def _finalize_blob_query_table(
self,
@@ -2386,6 +2441,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
rs_table = result_set.read_all()
result_set = self._reranker.rerank_vector(self._str_query, rs_table)
check_reranker_result(result_set)
result_set = _merge_query_snapshot(result_set, rs_table)
# convert result_set back to RecordBatchReader
result_set = pa.RecordBatchReader.from_batches(
result_set.schema, result_set.to_batches()
@@ -2599,8 +2655,10 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
query = self._query_for_scan(blob_sources)
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)
check_reranker_result(results)
results = _merge_query_snapshot(results, source)
return self._finalize_blob_query_table(
results, blob_mode=blob_mode, blob_sources=blob_sources
)
@@ -2847,6 +2905,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
with_row_ids=True,
offset=self._offset,
)
results = _merge_query_snapshot(results, fts_results, vector_results)
return self._finish_hybrid_results(
results, blob_mode=blob_mode, blob_sources=blob_sources
)
@@ -3559,9 +3618,8 @@ class AsyncQueryBase(object):
_query_is_plain_blob_scan(query)
and getattr(self, "_reranker", None) is None
and not _query_needs_lance_scanner(self)
and _supports_local_blob_fetch(
self._table, self._table._pushdown_operations
)
and self._table._inner._is_native()
and _supports_blob_fetch(self._table, self._table._pushdown_operations)
)
def select(self, columns: Union[List[str], dict[str, str]]) -> Self:
@@ -3766,11 +3824,14 @@ class AsyncQueryBase(object):
if blob_mode != "bytes":
return blob_sources
reject_unfetchable_blob_columns(schema, projection, blob_sources)
if blob_sources and not _supports_local_blob_fetch(
if blob_sources and not _supports_blob_fetch(
self._table, self._table._pushdown_operations
):
raise _blob_bytes_without_snapshot_error()
reject_unmatched_blob_outputs(await self._blob_output_schema(), blob_sources)
if self._table._inner._is_native():
reject_unmatched_blob_outputs(
await self._blob_output_schema(), blob_sources
)
return blob_sources
async def _blob_output_schema(self) -> pa.Schema:
@@ -3783,9 +3844,21 @@ class AsyncQueryBase(object):
return tbl
if blob_mode == "descriptions":
return strip_auto_row_ids(tbl, blob_sources)
return await replace_blob_columns_with_bytes(
tbl, blob_sources, self._table.fetch_blobs
)
reject_unmatched_blob_outputs(tbl.schema, blob_sources)
if (
self._table is not None
and not self._table._inner._is_native()
and blob_sources
):
version, identity = _remote_blob_snapshot(tbl.schema)
async def fetch_blobs(column, row_ids):
return await self._table._inner.fetch_blobs(
column, row_ids, version=version, snapshot_identity=identity
)
else:
fetch_blobs = self._table.fetch_blobs
return await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs)
async def to_arrow(
self,
@@ -3811,7 +3884,8 @@ class AsyncQueryBase(object):
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``.
Enterprise queries fetch bytes at the version reported by the query
response. Namespace query pushdown refuses ``"bytes"``.
"""
blob_sources = await self._validated_blob_sources(blob_mode)
if blob_mode == "bytes" and blob_sources:
@@ -3893,9 +3967,9 @@ class AsyncQueryBase(object):
columns without pylance. Other local blob v2 queries return
descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads
in ``"bytes"`` mode, through :meth:`to_arrow`.
LanceDB Enterprise blob queries support only ``"descriptions"`` until a
stable
table snapshot can bind the query and blob fetches.
Enterprise queries support ``"bytes"`` at the query response's
snapshot and ``"descriptions"`` without payload reads. Remote
``"lazy"`` handles are not supported.
**kwargs
Forwarded to pyarrow.Table.to_pandas after query execution and
optional flattening.
@@ -3903,6 +3977,9 @@ class AsyncQueryBase(object):
validate_blob_mode(blob_mode)
if self._table is not None and not self._table._inner._is_native():
await self._validated_blob_sources(blob_mode)
if blob_mode == "bytes":
tbl = await self.to_arrow(timeout=timeout, blob_mode=blob_mode)
return flatten_columns(tbl, flatten).to_pandas(**kwargs)
return await self._remote_to_pandas(
flatten=flatten, timeout=timeout, blob_mode=blob_mode, **kwargs
)
@@ -4508,7 +4585,9 @@ class AsyncFTSQuery(AsyncStandardQuery):
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
source = results
results = self._reranker.rerank_fts(self.get_query(), results)
results = _merge_query_snapshot(results, source)
return AsyncRecordBatchReader(results, max_batch_length=max_batch_length)
@@ -4835,7 +4914,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
source = results
results = self._reranker.rerank_vector(self._query_string, results)
results = _merge_query_snapshot(results, source)
return AsyncRecordBatchReader(results, max_batch_length=max_batch_length)
@@ -5027,6 +5108,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
):
result = result.drop(["_rowid"])
result = _merge_query_snapshot(result, fts_results, vector_results)
return AsyncRecordBatchReader(result, max_batch_length=max_batch_length)
async def explain_plan(self, verbose: Optional[bool] = False):
+52 -8
View File
@@ -4,6 +4,8 @@
from __future__ import annotations
from lancedb.server_info import ServerInfo
from dataclasses import replace
from datetime import timedelta
import json
@@ -214,6 +216,7 @@ class RemoteDBConnection(DBConnection):
client_config,
oauth_config,
sql_host_override,
storage_options,
):
config = (
ClientConfig(**client_config)
@@ -233,7 +236,7 @@ class RemoteDBConnection(DBConnection):
result.region = "us-east-1"
result.host_override = endpoint
result.sql_host_override = sql_host_override
result.storage_options = None
result.storage_options = storage_options
result.client_config = replace(config, extra_headers=headers)
result._catalog_oauth = oauth_config is not None
result._conn = inner
@@ -573,6 +576,7 @@ class RemoteDBConnection(DBConnection):
source_version: Optional[int] = None,
source_tag: Optional[str] = None,
is_shallow: bool = True,
exist_ok: bool = False,
) -> Table:
"""Clone a table from a source table.
@@ -592,6 +596,8 @@ class RemoteDBConnection(DBConnection):
is_shallow: bool, default True
Whether to perform a shallow clone (True) or deep clone (False).
Currently only shallow clone is supported.
exist_ok: bool, default False
Return the existing target unchanged instead of cloning over it.
Returns
-------
@@ -609,6 +615,7 @@ class RemoteDBConnection(DBConnection):
source_version=source_version,
source_tag=source_tag,
is_shallow=is_shallow,
exist_ok=exist_ok,
)
)
return RemoteTable(
@@ -789,12 +796,14 @@ class RemoteDBConnection(DBConnection):
def create_materialized_view(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: SelectArg = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> MaterializedView:
@@ -804,10 +813,12 @@ class RemoteDBConnection(DBConnection):
self._conn.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
@@ -825,12 +836,14 @@ class RemoteDBConnection(DBConnection):
def create_materialized_view_async(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: SelectArg = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
@@ -838,10 +851,12 @@ class RemoteDBConnection(DBConnection):
self._conn.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
@@ -965,6 +980,13 @@ class RemoteDBConnection(DBConnection):
"""
return Job(LOOP.run(self._conn.open_job(job_id)))
@override
def server_info(self) -> ServerInfo:
"""Read the responding server's build information. See
[DBConnection.server_info][lancedb.db.DBConnection.server_info].
"""
return LOOP.run(self._conn.server_info())
@override
def list_gpu_classes(self) -> List[GpuClass]:
"""List configured Function GPU classes. See
@@ -978,11 +1000,15 @@ class RemoteDBConnection(DBConnection):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> Job[FunctionVersion]:
job = LOOP.run(
self._conn.create_function_async(
definition, secrets=secrets, namespace_path=namespace_path
definition,
secrets=secrets,
exist_ok=exist_ok,
namespace_path=namespace_path,
)
)
return Job(job)
@@ -1073,6 +1099,7 @@ class RemoteDBConnection(DBConnection):
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> StorageIntegrationInfo:
return LOOP.run(
@@ -1090,6 +1117,7 @@ class RemoteDBConnection(DBConnection):
azure_client_secret_secret=azure_client_secret_secret,
gcp_credentials_json_secret=gcp_credentials_json_secret,
huggingface_token_secret=huggingface_token_secret,
exist_ok=exist_ok,
namespace_path=namespace_path,
)
)
@@ -1128,9 +1156,18 @@ class RemoteDBConnection(DBConnection):
@override
def create_secret(
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> None:
LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path))
LOOP.run(
self._conn.create_secret(
name, value, exist_ok=exist_ok, namespace_path=namespace_path
)
)
@override
def alter_secret(
@@ -1174,10 +1211,17 @@ class RemoteDBConnection(DBConnection):
@override
def create_view(
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> ViewDescription:
return LOOP.run(
self._conn.create_view(name, query, namespace_path=namespace_path)
self._conn.create_view(
name, query, exist_ok=exist_ok, namespace_path=namespace_path
)
)
@override
+25 -3
View File
@@ -369,6 +369,7 @@ class RemoteTable(Table):
index_type: ScalarIndexType = "BTREE",
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a scalar index on a column.
@@ -395,6 +396,7 @@ class RemoteTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -433,6 +435,7 @@ class RemoteTable(Table):
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a full-text search index on a column.
@@ -492,6 +495,7 @@ class RemoteTable(Table):
self._table.create_index(
field_names,
replace=replace,
exist_ok=exist_ok,
config=config,
name=name,
wait_timeout=wait_timeout,
@@ -516,6 +520,7 @@ class RemoteTable(Table):
replace: bool = ...,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
) -> None: ...
@@ -541,6 +546,7 @@ class RemoteTable(Table):
*,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
target_partition_size: Optional[int] = ...,
) -> None: ...
@@ -572,6 +578,7 @@ class RemoteTable(Table):
config: Optional[IndexConfigType] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
target_partition_size: Optional[int] = None,
):
@@ -675,6 +682,7 @@ class RemoteTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -690,6 +698,7 @@ class RemoteTable(Table):
replace: Optional[bool] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> Job:
"""Create an index, returning a handle to the indexing job.
@@ -702,6 +711,7 @@ class RemoteTable(Table):
self._table.create_index_async(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -719,6 +729,7 @@ class RemoteTable(Table):
progress: Optional[Union[bool, Callable, Any]] = None,
write_parallelism: Optional[int] = None,
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult:
"""Add more data to the [Table][lancedb.table.Table].
@@ -753,6 +764,9 @@ class RemoteTable(Table):
using too much memory.
allow_external_blob_outside_bases: bool, default False
Not supported in LanceDB Enterprise. Setting this raises.
retries: int, optional
Override the retry budget for this call (0 to 255). Zero disables
retries, including multipart parts. Ambiguous commits are never replayed.
Returns
-------
@@ -770,6 +784,7 @@ class RemoteTable(Table):
progress=progress,
write_parallelism=write_parallelism,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
retries=retries,
)
)
finally:
@@ -1420,13 +1435,20 @@ class RemoteTable(Table):
self,
column: str,
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
return LOOP.run(self._table.fetch_blob_files(column, row_ids))
return LOOP.run(
self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size)
)
def open_blob_file(
self, descriptor: Union[dict, pa.StructScalar, None]
self,
descriptor: Union[dict, pa.StructScalar, None],
*,
buffer_size: Optional[int] = None,
) -> Optional[BlobFile]:
return LOOP.run(self._table.open_blob_file(descriptor))
return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size))
def head(self, n=5) -> pa.Table:
"""
+33
View File
@@ -0,0 +1,33 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Remote server build information returned as JSON-compatible dictionaries."""
from typing import Optional, TypedDict
class ServerBuildInfo(TypedDict):
"""Immutable identity compiled into a server executable."""
release: str
git_sha: str
build_date: Optional[str]
class ServerInfo(TypedDict):
"""The responding query node and its configured Function runtime.
``query_node`` can be ``None`` when the executable has no build metadata.
``build_date`` is a UTC RFC 3339 timestamp when known. During a rolling
upgrade, separate requests can reach different query-node builds.
Configured images do not establish the version of a running job.
"""
query_node: Optional[ServerBuildInfo]
lance_version: str
lancedb_version: str
function_worker_protocol_version: int
configured_query_node_image: Optional[str]
configured_job_worker_image: Optional[str]
configured_sql_job_image: Optional[str]
configured_gpu_worker_image: Optional[str]
+139 -17
View File
@@ -40,6 +40,7 @@ from ._blob import (
BlobFile,
_normalize_blob_descriptor,
_normalize_blob_row_ids,
_validate_blob_buffer_size,
_wrap_blob_files,
strip_auto_row_ids,
validate_blob_mode,
@@ -167,6 +168,36 @@ def _validate_index_accelerator(accelerator: Any) -> None:
raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err
def _create_accelerated_index(dataset, *, exist_ok=False, name=None, **options):
if exist_ok:
parts = _parse_field_path(options["column"])
default_name = ".".join(parts)
if any("." in part for part in parts):
default_name = ".".join(
"`" + part.replace("`", "``") + "`"
if any(
not character.isalnum() and character != "_" for character in part
)
else part
for part in parts
)
name = name or f"{default_name}_idx"
dataset.checkout_latest()
if any(index["name"] == name for index in dataset.list_indices()):
return
options["replace"] = False
options["name"] = name
_validate_index_accelerator(options.get("accelerator"))
try:
dataset.create_index(**options)
except Exception:
if exist_ok:
dataset.checkout_latest()
if any(index["name"] == name for index in dataset.list_indices()):
return
raise
def _polars_predicate_pushdown_barrier(frame: Any) -> Any:
"""Return a Polars frame unchanged while blocking predicate pushdown."""
return frame
@@ -1833,6 +1864,7 @@ class Table(ABC):
replace: bool = ...,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
) -> None: ...
@@ -1858,6 +1890,7 @@ class Table(ABC):
*,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
target_partition_size: Optional[int] = ...,
) -> None: ...
@@ -1889,6 +1922,7 @@ class Table(ABC):
config: Optional[IndexConfigType] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
target_partition_size: Optional[int] = None,
):
@@ -1912,6 +1946,9 @@ class Table(ABC):
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
exist_ok : bool, default False
Preserve the existing index with the requested or derived name.
Takes precedence over replace and keeps its definition and build.
wait_timeout : timedelta, optional
LanceDB Enterprise only: how long to wait for the index build to finish.
If not set, the call returns once the build is scheduled.
@@ -1967,6 +2004,7 @@ class Table(ABC):
replace: Optional[bool] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> Job:
"""Create an index, returning a handle to the indexing job.
@@ -2059,6 +2097,7 @@ class Table(ABC):
index_type: ScalarIndexType = "BTREE",
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a scalar index on a column.
@@ -2143,6 +2182,7 @@ class Table(ABC):
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a full-text search index on the table.
@@ -2255,6 +2295,7 @@ class Table(ABC):
progress: Optional[Union[bool, Callable, Any]] = None,
write_parallelism: Optional[int] = None,
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult:
"""Add more data to the [Table][lancedb.table.Table].
@@ -2315,6 +2356,10 @@ class Table(ABC):
Store blob URIs that sit outside registered blob bases. The row
keeps a reference, so the object has to stay readable. Local
tables only.
retries: int, optional
Override the remote retry budget for this call (0 to 255). Zero
disables retries, including multipart parts. Ambiguous commits are
never replayed. Ignored by LanceDB Embedded.
Returns
-------
@@ -2655,8 +2700,12 @@ class Table(ABC):
results are returned.
Row IDs can be obtained from a query with ``with_row_id(True)``.
LanceDB Enterprise reads the requested ranges through version-pinned blob
handles using HTTP byte-range requests.
LanceDB Enterprise uses the batched endpoint when the server advertises
support, partitioning at 1024 ranges and 64 MiB, including individual
larger ranges. Older servers use descriptor queries and BlobFile range
reads. Both protocols read one exact branch and version without changing
the table's checkout. Errors from an advertised endpoint propagate without
switching protocols. The final output occupies memory.
"""
@abstractmethod
@@ -2664,6 +2713,8 @@ class Table(ABC):
self,
column: str,
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
"""Open lazy, seekable :class:`~lancedb._blob.BlobFile` handles.
@@ -2673,6 +2724,8 @@ class Table(ABC):
``pyarrow.Table`` carrying row identity via ``_rowid`` or a
``_lance_row_id`` field on the blob descriptor. Null blob values return
``None``. LanceDB Enterprise requires server version 0.5.0 or newer.
``buffer_size`` controls sequential read-ahead in bytes (default 512 KiB).
Set it to 0 for sparse reads. Explicit range reads bypass this buffer.
``_rowid`` values stay valid after compaction when the table has stable
row ids.
@@ -2682,7 +2735,10 @@ class Table(ABC):
@abstractmethod
def open_blob_file(
self, descriptor: Union[dict, pa.StructScalar, None]
self,
descriptor: Union[dict, pa.StructScalar, None],
*,
buffer_size: Optional[int] = None,
) -> Optional[BlobFile]:
"""Open a seekable file from a SQL ``blob_descriptor`` result.
@@ -2691,6 +2747,7 @@ class Table(ABC):
not change this table's checkout. Null descriptors return ``None``.
Payload bytes load only when the returned handle is read. An external
blob with an unspecified size may require a metadata request on opening.
``buffer_size`` controls sequential read-ahead (default 512 KiB; 0 disables).
```python
rows = db.execute_query(
@@ -2701,7 +2758,9 @@ class Table(ABC):
```
"""
def open_blob_files(self, descriptors: Iterable) -> Iterator[Optional[BlobFile]]:
def open_blob_files(
self, descriptors: Iterable, *, buffer_size: Optional[int] = None
) -> Iterator[Optional[BlobFile]]:
"""Iterate over lazy files from descriptor dictionaries or Arrow scalars.
Accepts an Arrow array/chunked array or any iterable. Opens each handle
@@ -2716,7 +2775,10 @@ class Table(ABC):
```
"""
for descriptor in descriptors:
yield self.open_blob_file(descriptor)
if buffer_size is None:
yield self.open_blob_file(descriptor)
else:
yield self.open_blob_file(descriptor, buffer_size=buffer_size)
@abstractmethod
def _execute_query(
@@ -3998,13 +4060,20 @@ class LanceTable(Table):
self,
column: str,
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
return LOOP.run(self._table.fetch_blob_files(column, row_ids))
return LOOP.run(
self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size)
)
def open_blob_file(
self, descriptor: Union[dict, pa.StructScalar, None]
self,
descriptor: Union[dict, pa.StructScalar, None],
*,
buffer_size: Optional[int] = None,
) -> Optional[BlobFile]:
return LOOP.run(self._table.open_blob_file(descriptor))
return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size))
@property
def tags(self) -> Tags:
@@ -4288,6 +4357,7 @@ class LanceTable(Table):
replace: bool = ...,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
) -> None: ...
@@ -4313,6 +4383,7 @@ class LanceTable(Table):
*,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
target_partition_size: Optional[int] = ...,
) -> None: ...
@@ -4344,6 +4415,7 @@ class LanceTable(Table):
config: Optional[IndexConfigType] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
target_partition_size: Optional[int] = None,
):
@@ -4367,6 +4439,9 @@ class LanceTable(Table):
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
exist_ok : bool, default False
Preserve the existing index with the requested or derived name.
Takes precedence over replace and keeps its definition and build.
wait_timeout : timedelta, optional
Timeout to wait for async indexing to complete.
name : str, optional
@@ -4435,8 +4510,10 @@ class LanceTable(Table):
# Handle accelerator through pylance
if accelerator is not None:
dataset = self.to_lance()
_validate_index_accelerator(accelerator)
dataset.create_index(
_create_accelerated_index(
dataset,
exist_ok=exist_ok,
name=name,
column=column,
index_type=index_type,
metric=metric,
@@ -4462,7 +4539,6 @@ class LanceTable(Table):
if acc is not None:
# Dispatch to pylance for GPU acceleration
dataset = self.to_lance()
_validate_index_accelerator(acc)
index_type_map = {
"IvfFlat": "IVF_FLAT",
"IvfSq": "IVF_SQ",
@@ -4479,7 +4555,10 @@ class LanceTable(Table):
if num_bits is not None:
quantization_kwargs["num_bits"] = num_bits
dataset.create_index(
_create_accelerated_index(
dataset,
exist_ok=exist_ok,
name=name,
column=column,
index_type=lance_index_type,
metric=getattr(config, "distance_type", "l2"),
@@ -4501,6 +4580,7 @@ class LanceTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -4516,6 +4596,7 @@ class LanceTable(Table):
replace: Optional[bool] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> Job:
"""Create an index, returning a handle to the indexing job.
@@ -4534,6 +4615,7 @@ class LanceTable(Table):
self._table.create_index_async(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -4654,6 +4736,7 @@ class LanceTable(Table):
index_type: ScalarIndexType = "BTREE",
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a scalar index on a column.
@@ -4680,6 +4763,7 @@ class LanceTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -4717,6 +4801,7 @@ class LanceTable(Table):
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a full-text search index on a column.
@@ -4778,6 +4863,7 @@ class LanceTable(Table):
self._table.create_index(
field_names,
replace=replace,
exist_ok=exist_ok,
config=config,
name=name,
wait_timeout=wait_timeout,
@@ -4800,6 +4886,7 @@ class LanceTable(Table):
progress: Optional[Union[bool, Callable, Any]] = None,
write_parallelism: Optional[int] = None,
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult:
"""Add data to the table.
If vector columns are missing and the table
@@ -4831,6 +4918,10 @@ class LanceTable(Table):
allow_external_blob_outside_bases: bool, default False
Allow blob URIs outside registered bases. See :meth:`Table.add`.
LanceDB Embedded only.
retries: int, optional
Override the remote retry budget for this call (0 to 255). Zero
disables retries, including multipart parts. Ambiguous commits are
never replayed. Ignored by LanceDB Embedded.
Returns
-------
@@ -4848,6 +4939,7 @@ class LanceTable(Table):
progress=progress,
write_parallelism=write_parallelism,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
retries=retries,
)
)
finally:
@@ -6770,6 +6862,7 @@ class AsyncTable:
] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
):
"""Create an index to speed up queries
@@ -6800,6 +6893,9 @@ class AsyncTable:
If not set, the call returns once the build is scheduled.
name: str, optional
The name of the index. If not provided, a default name will be generated.
exist_ok: bool, default False
Preserve an existing index with the requested or derived name. This
takes precedence over replace and keeps its definition and build.
train: bool, default True
Whether to train the index with existing data. Vector indices always train
with existing data.
@@ -6855,6 +6951,7 @@ class AsyncTable:
column,
index=config,
replace=replace,
exist_ok=exist_ok,
wait_timeout=wait_timeout,
name=name,
train=train,
@@ -6892,6 +6989,7 @@ class AsyncTable:
] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> AsyncJob:
"""Create an index, returning a handle to the indexing job.
@@ -6910,6 +7008,7 @@ class AsyncTable:
column,
index=config,
replace=replace,
exist_ok=exist_ok,
wait_timeout=wait_timeout,
name=name,
train=train,
@@ -7059,6 +7158,7 @@ class AsyncTable:
progress: Optional[Union[bool, Callable, Any]] = None,
write_parallelism: Optional[int] = None,
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult:
"""Add more data to the [AsyncTable][lancedb.table.AsyncTable].
@@ -7097,6 +7197,10 @@ class AsyncTable:
allow_external_blob_outside_bases: bool, default False
Allow blob URIs outside registered bases. See :meth:`Table.add`.
LanceDB Embedded only.
retries: int, optional
Override the remote retry budget for this call (0 to 255). Zero
disables retries, including multipart parts. Ambiguous commits are
never replayed. Ignored by LanceDB Embedded.
"""
schema = await self.schema()
@@ -7151,6 +7255,7 @@ class AsyncTable:
progress=progress,
write_parallelism=write_parallelism,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
retries=retries,
)
except RuntimeError as e:
if "Cast error" in str(e):
@@ -8614,32 +8719,49 @@ class AsyncTable:
column: str,
requests: Sequence[Sequence[int]],
) -> pa.LargeBinaryArray:
"""Materialize row-specific byte ranges.
See [Table.fetch_blob_ranges][lancedb.table.Table.fetch_blob_ranges].
"""
return await self._inner.fetch_blob_ranges(column, list(requests))
async def fetch_blob_files(
self,
column: str,
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
"""Open handles with configurable read-ahead.
See [Table.fetch_blob_files][lancedb.table.Table.fetch_blob_files].
"""
buffer_size = _validate_blob_buffer_size(buffer_size)
handles = await self._inner.fetch_blob_files(
column, _normalize_blob_row_ids(row_ids, column)
column, _normalize_blob_row_ids(row_ids, column), buffer_size
)
return _wrap_blob_files(handles)
async def open_blob_file(
self, descriptor: Union[dict, pa.StructScalar, None]
self,
descriptor: Union[dict, pa.StructScalar, None],
*,
buffer_size: Optional[int] = None,
) -> Optional[BlobFile]:
"""Open a snapshot-bound descriptor as a seekable file.
See [Table.open_blob_file][lancedb.table.Table.open_blob_file].
"""
buffer_size = _validate_blob_buffer_size(buffer_size)
descriptor = _normalize_blob_descriptor(descriptor)
if descriptor is None:
return None
return BlobFile(await self._inner.open_blob_file(json.dumps(descriptor)))
return BlobFile(
await self._inner.open_blob_file(json.dumps(descriptor), buffer_size)
)
async def open_blob_files(
self, descriptors: Iterable
self, descriptors: Iterable, *, buffer_size: Optional[int] = None
) -> AsyncIterator[Optional[BlobFile]]:
"""Asynchronously iterate over files in descriptor order, preserving nulls.
@@ -8654,7 +8776,7 @@ class AsyncTable:
```
"""
for descriptor in descriptors:
yield await self.open_blob_file(descriptor)
yield await self.open_blob_file(descriptor, buffer_size=buffer_size)
@property
def tags(self) -> AsyncTags:
+236
View File
@@ -0,0 +1,236 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import threading
from contextlib import contextmanager
from urllib.parse import urlparse
import pyarrow as pa
import pytest
import lancedb
from test_remote_db import (
BLOB_DESCRIBE_RESPONSE,
blob_descriptor_take_table,
mock_lancedb_connection,
)
@contextmanager
def remote_buffer_table(*, http_requests=None, truncate_first=False):
payload = bytes(range(256)) * 4096
requests = []
def handler(request):
path = urlparse(request.path).path
if http_requests is not None:
http_requests.append(path)
if path.endswith("/describe/"):
body = json.dumps(BLOB_DESCRIBE_RESPONSE).encode()
content_type = "application/json"
elif path.endswith("/query/"):
data = json.loads(
request.rfile.read(int(request.headers["Content-Length"]))
)
assert data["columns"] == ["image"]
table = blob_descriptor_take_table().slice(0, 1)
images = table["image"].combine_chunks()
images = pa.StructArray.from_arrays(
[
images.field("kind"),
images.field("position"),
pa.array([len(payload)], pa.uint64()),
images.field("blob_id"),
images.field("blob_uri"),
],
fields=list(images.type),
)
table = table.set_column(0, table.schema.field(0), images)
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, table.schema) as writer:
writer.write_table(table)
body = sink.getvalue().to_pybytes()
content_type = "application/vnd.apache.arrow.stream"
else:
assert path == "/v1/table/test/blob/image/10/bytes"
assert "version=1" in request.path
start, end = map(int, request.headers["Range"][6:].split("-"))
requests.append((start, end + 1))
body = payload[start : end + 1]
if truncate_first and len(requests) == 1:
body = body[:5]
request.send_response(206)
request.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
request.send_header("Content-Length", str(len(body)))
request.end_headers()
request.wfile.write(body)
return
request.send_response(200)
request.send_header("Content-Type", content_type)
request.send_header("Content-Length", str(len(body)))
request.send_header("phalanx-version", "0.5.0")
request.send_header("x-lancedb-version", "1")
request.end_headers()
request.wfile.write(body)
with mock_lancedb_connection(handler, blob_request_concurrency=1) as db:
yield db.open_table("test"), payload, requests
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("buffer_size", [None, 0, 8, 512 * 1024])
async def test_remote_read_ahead_over_http(use_async, buffer_size):
with remote_buffer_table() as (table, payload, requests):
if use_async:
files = await table._table.fetch_blob_files(
"image", [10], buffer_size=buffer_size
)
else:
files = table.fetch_blob_files("image", [10], buffer_size=buffer_size)
file = files[0]
assert requests == []
assert file.read(2) == payload[:2]
window = 512 * 1024 if buffer_size is None else max(buffer_size, 2)
assert requests == [(0, window)]
assert file.read(2) == payload[2:4]
assert len(requests) == (2 if buffer_size == 0 else 1)
file.seek(1)
assert file.read(1) == payload[1:2]
assert len(requests) == (3 if buffer_size == 0 else 1)
before = len(requests)
assert file.read_range(0, 1) == payload[:1]
assert len(requests) == before + 1
assert requests[-1] == (0, 1)
assert file.tell() == 2
file.set_buffer_size(0)
assert file.read(1) == payload[2:3]
assert requests[-1] == (2, 3)
file.set_buffer_size(16)
assert file.read(1) == payload[3:4]
assert requests[-1] == (3, 19)
file.seek(len(payload) - 1)
assert file.read(4) == payload[-1:]
assert requests[-1] == (len(payload) - 1, len(payload))
before = len(requests)
assert file.read(1) == b""
assert len(requests) == before
file.close()
with pytest.raises(ValueError, match="closed"):
file.set_buffer_size(0)
def test_short_prefetch_over_http_preserves_cursor():
with remote_buffer_table(truncate_first=True) as (table, payload, requests):
file = table.fetch_blob_files("image", [10], buffer_size=8)[0]
with pytest.raises(RuntimeError, match="returned 5 bytes, expected 8"):
file.read(6)
assert file.tell() == 0
assert file.read(3) == payload[:3]
assert file.tell() == 3
assert requests == [(0, 8), (0, 8)]
file.close()
def test_idle_prefetch_releases_http_concurrency_slot():
with remote_buffer_table() as (table, payload, requests):
first, second = table.fetch_blob_files("image", [10, 10])
assert first.read(1) == payload[:1]
results = []
errors = []
def read_other():
try:
results.append(second.read(1))
except Exception as error:
errors.append(error)
reader = threading.Thread(target=read_other, daemon=True)
reader.start()
reader.join(timeout=2)
completed_while_first_idle = not reader.is_alive()
first.close()
reader.join(timeout=2)
second.close()
assert completed_while_first_idle, (
"idle prefetch retained the HTTP request slot"
)
assert not errors
assert results == [payload[:1]]
assert requests == [(0, 512 * 1024), (0, 512 * 1024)]
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_local_buffer_configuration_through_python(tmp_path, use_async):
db = lancedb.connect(tmp_path)
table = db.create_table(
"blobs", [{"image": b"0123456789"}], schema=pa.schema([lancedb.blob("image")])
)
row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
if use_async:
files = await table._table.fetch_blob_files("image", row_ids, buffer_size=0)
else:
files = table.fetch_blob_files("image", row_ids, buffer_size=0)
file = files[0]
assert file.read(2) == b"01"
file.set_buffer_size(4)
assert file.read(2) == b"23"
file.seek(1)
assert file.read(3) == b"123"
assert file.read_range(8, 2) == b"89"
with pytest.raises(ValueError, match="non-negative"):
file.set_buffer_size(-1)
with pytest.raises(TypeError):
file.set_buffer_size(1.5)
file.close()
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_open_descriptor_files_forward_buffer_size(use_async):
with remote_buffer_table() as (table, payload, requests):
descriptor = {
"kind": 1,
"position": 0,
"size": len(payload),
"blob_id": 0,
"blob_uri": "",
"source": {
"uri": "s3://bucket/test.lance",
"version": 1,
"committed_at_micros": 1,
"column": "image",
"row_reference": 10,
"row_is_address": False,
},
}
if use_async:
files = [
file
async for file in table._table.open_blob_files(
[None, descriptor], buffer_size=8
)
]
else:
files = list(table.open_blob_files([None, descriptor], buffer_size=8))
assert files[0] is None
assert files[1].read(1) == payload[:1]
assert requests == [(0, 8)]
files[1].close()
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_invalid_buffer_size_rejects_before_http(use_async):
http_requests = []
with remote_buffer_table(http_requests=http_requests) as (table, _, requests):
http_requests.clear()
with pytest.raises(ValueError, match="non-negative"):
if use_async:
await table._table.fetch_blob_files("image", [10], buffer_size=-1)
else:
table.fetch_blob_files("image", [10], buffer_size=-1)
assert requests == []
assert http_requests == []
+380
View File
@@ -0,0 +1,380 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Exercise the public sync/async range APIs over bounded loopback HTTP."""
import asyncio
import hashlib
import json
from pathlib import Path
import socket
import threading
import lancedb._lancedb as native
import pyarrow as pa
import pytest
from lancedb.remote.errors import HttpError, TableNotFoundError
from test_remote_db import mock_lancedb_connection
MIB = 1024 * 1024
IDENTITY = "v1:" + "a" * 64
ROUTE = "/v1/table/test/fetch_blob_ranges/"
def payload(row, offset, length, version):
pattern = bytes((row * 17 + i + version) % 251 for i in range(251))
start = offset % 251
return (pattern * ((start + length + 250) // 251))[start : start + length]
class RangeServer:
def __init__(self, fault=None):
self.fault = fault
self.calls = []
self.fetches = []
self.identities = []
self.stalled = threading.Event()
self.release = threading.Event()
def __call__(self, request):
request.connection.settimeout(15)
size = int(request.headers.get("Content-Length", 0))
assert size <= 256 * 1024
body = json.loads(request.rfile.read(size) or b"{}")
self.calls.append((request.command, request.path, body))
if request.path in (
"/v1/table/test/describe/",
"/v1/table/test/branches/list/",
):
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.send_header("phalanx-version", "1.13.0-beta.0")
if request.path.endswith("/describe/"):
request.send_header("x-lancedb-blob-ranges", "1")
request.end_headers()
response = (
{
"branches": {
"experiment": {
"parentBranch": None,
"parentVersion": 1,
"createAt": 1,
"manifestSize": 1,
}
}
}
if request.path.endswith("branches/list/")
else {"version": 8, "schema": {"fields": []}}
)
request.wfile.write(json.dumps(response).encode())
return
assert (request.command, request.path) == ("POST", ROUTE)
self.fetches.append(body)
self.identities.append(request.headers.get("x-lancedb-query-snapshot"))
assert body["column"] == "image"
assert body["branch"] == "experiment"
ranges = body["ranges"]
assert len(ranges) <= 1024
assert sum(r["length"] for r in ranges) <= 64 * MIB
version = body["version"] or (7 if len(self.fetches) == 1 else 8)
values = [
None
if r["row_id"] == 20
else payload(r["row_id"], r["offset"], r["length"], version)
for r in ranges
]
fault = (
self.fault
if len(self.fetches) > 1 or str(self.fault).startswith("first-")
else None
)
if fault in ("recreated", "gone"):
request.send_response(400 if fault == "recreated" else 404)
request.end_headers()
request.wfile.write(
b"query snapshot identity mismatch: source gone or replaced"
)
return
if fault == "stall" and len(self.fetches) == 2:
request.send_response(200)
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
request.send_header("x-lancedb-version", str(version))
request.send_header("x-lancedb-query-snapshot", IDENTITY)
request.end_headers()
request.wfile.flush()
self.stalled.set()
assert self.release.wait(15), "test did not release stalled response"
return
if fault == "structured400":
request.send_response(400)
request.send_header("x-lancedb-error-code", "invalid_input")
request.end_headers()
request.wfile.write(b'{"error":"range exceeds blob size"}')
return
if isinstance(fault, int):
request.send_response(fault)
request.end_headers()
request.wfile.write(b"ordinary server failure")
return
if fault == "disconnect":
request.connection.shutdown(socket.SHUT_RDWR)
return
column = "wrong" if fault == "column" else "value"
data_type = pa.binary() if fault == "type" else pa.large_binary()
if fault == "count":
values = []
elif fault == "length":
values = [b""]
batch = pa.table({column: pa.array(values, type=data_type)})
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, batch.schema) as writer:
writer.write_table(batch, max_chunksize=257)
ipc = sink.getvalue().to_pybytes()
if fault == "eos":
ipc = ipc[:-8]
elif fault == "body":
ipc = ipc[: len(ipc) // 2]
request.send_response(200)
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
if fault != "version":
request.send_header("x-lancedb-version", str(version))
if fault not in ("missing-identity", "first-missing-identity"):
identity = (
"broken"
if fault == "first-invalid-identity"
else "v1:" + "b" * 64
if fault == "wrong-identity"
else IDENTITY
)
request.send_header("x-lancedb-query-snapshot", identity)
request.send_header(
"Content-Length", str(len(ipc) + (10 if fault == "transport" else 0))
)
request.end_headers()
for i in range(0, len(ipc), 8192):
request.wfile.write(ipc[i : i + 8192])
async def fetch(table, requests, use_async):
result = table.fetch_blob_ranges("image", requests)
return await result if use_async else result
def api(db, use_async, version=None):
table = db.open_table("test", branch="experiment", version=version)
return table._table if use_async else table
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("version", [None, 3])
async def test_range_sdk_order_snapshot_and_overwrite(use_async, version):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
table = api(db, use_async, version)
requests = [(20 if i % 9 == 0 else 10 + i % 7, i, i % 4) for i in range(1025)]
requests += [(10, 0, 0), (10, 2, 3), (10, 2, 3)]
result = await fetch(table, requests, use_async)
assert isinstance(result, pa.LargeBinaryArray)
assert result.to_pylist() == [
None if row == 20 else payload(row, offset, length, version or 7)
for row, offset, length in requests
]
assert [b["version"] for b in handler.fetches] == [version, version or 7]
result = await fetch(table, [(10, 0, 1)], use_async)
assert result.to_pylist() == [payload(10, 0, 1, version or 8)]
assert handler.fetches[-1]["version"] == version
assert len(handler.fetches) == 3
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_cached_reopen_negotiates_capability(use_async):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
for version in (7, 8):
table = api(db, use_async)
result = await fetch(table, [(10, 0, 1)], use_async)
assert result.to_pylist() == [payload(10, 0, 1, version)]
assert len(handler.fetches) == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_large_single_and_aggregate_budget(use_async):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
requests = [
(10, 3, 33 * MIB),
(30, 7, 33 * MIB),
(40, 11, 70 * MIB),
(20, 0, 2**64 - 1),
]
# The loopback server advances latest after the first partition.
result = await fetch(table, requests, use_async)
assert len(result) == 4
for i, (row, offset, length) in enumerate(requests[:3]):
expected = payload(row, offset, length, 7)
assert (
hashlib.sha256(result[i].as_buffer()).digest()
== hashlib.sha256(expected).digest()
)
assert len(result[i].as_buffer()) == length
assert result[3].as_py() is None
assert len(handler.fetches) == 3
assert [b["version"] for b in handler.fetches] == [None, 7, 7]
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize(
"fault",
[
"type",
"column",
"count",
"length",
"eos",
"body",
"transport",
"version",
"disconnect",
401,
403,
404,
429,
500,
],
)
async def test_range_sdk_later_failure_rejects_entire_call(use_async, fault):
handler = RangeServer(fault=fault)
with mock_lancedb_connection(
handler, retry_config={"retries": 2, "connect_retries": 2, "read_retries": 2}
) as db:
table = api(db, use_async)
with pytest.raises(Exception) as exc:
await fetch(table, [(10, 0, 1)] * 1025, use_async)
if fault == 404:
assert isinstance(exc.value, TableNotFoundError)
assert isinstance(exc.value.__cause__, HttpError)
assert exc.value.__cause__.status_code == 404
else:
assert not isinstance(exc.value, ValueError)
if isinstance(fault, int):
assert exc.value.status_code == fault
assert len(handler.fetches) == 2
assert all(
path in ("/v1/table/test/describe/", "/v1/table/test/branches/list/", ROUTE)
for _, path, _ in handler.calls
)
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_structured_400_preserves_value_error(use_async):
handler = RangeServer(fault="structured400")
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
with pytest.raises(ValueError, match="range exceeds blob size"):
await fetch(table, [(10, 0, 1)] * 1025, use_async)
assert len(handler.fetches) == 2
@pytest.mark.asyncio
async def test_range_sdk_async_cancel_releases_only_request_permit():
handler = RangeServer(fault="stall")
with mock_lancedb_connection(handler, blob_request_concurrency=1) as db:
table = api(db, True)
pending = asyncio.create_task(fetch(table, [(10, 0, 1)] * 2049, True))
try:
assert await asyncio.to_thread(handler.stalled.wait, 10)
pending.cancel()
with pytest.raises(asyncio.CancelledError):
await pending
assert len(handler.fetches) == 2
result = await asyncio.wait_for(fetch(table, [(10, 0, 1)], True), 5)
assert result.to_pylist() == [payload(10, 0, 1, 8)]
assert len(handler.fetches) == 3
finally:
pending.cancel()
handler.release.set()
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_integer_validation_and_empty_zero_io(use_async):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
before = len(handler.calls)
assert (await fetch(table, [], use_async)).to_pylist() == []
for request in [
(-1, 0, 1),
(2**64, 0, 1),
(10, -1, 1),
(10, 0, -1),
(10, 0, 2**64),
(10, 0.5, 1),
(20, 2**64 - 1, 1),
(10, 0),
]:
with pytest.raises((ValueError, OverflowError, TypeError)):
await fetch(table, [request], use_async)
assert len(handler.calls) == before
def test_range_sdk_loaded_artifact_identity():
artifact = Path(native.__file__).resolve()
digest = hashlib.sha256()
with artifact.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
print(f"loaded native artifact={artifact} sha256={digest.hexdigest()}")
assert artifact.is_file()
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize(
"fault", ["missing-identity", "wrong-identity", "recreated", "gone"]
)
@pytest.mark.parametrize("huge", [False, True])
async def test_range_sdk_original_identity_survives_every_partition(
use_async, fault, huge
):
handler = RangeServer(fault=fault)
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
requests = [(10, 0, 64 * MIB + 1)] if huge else [(10, 0, 1)] * 1025
error = (
ValueError
if fault == "recreated"
else TableNotFoundError
if fault == "gone"
else NotImplementedError
)
with pytest.raises(
error, match="snapshot identity" if fault != "gone" else None
):
await fetch(table, requests, use_async)
assert handler.identities == [None, IDENTITY]
assert len(handler.fetches) == 2
assert [body["version"] for body in handler.fetches] == [None, 7]
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("fault", ["first-missing-identity", "first-invalid-identity"])
async def test_range_sdk_bulk_requires_identity_before_payload_acceptance(
use_async, fault
):
handler = RangeServer(fault=fault)
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
before = len(handler.calls)
with pytest.raises(NotImplementedError, match="snapshot identity"):
await fetch(table, [(10, 0, 1)] * 1025, use_async)
assert len(handler.fetches) == 1
assert len(handler.calls) == before + 1
+175 -1
View File
@@ -2,7 +2,9 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from datetime import timedelta
import json
import warnings
import pytest
@@ -62,6 +64,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
endpoint,
api_key="secret",
sql_host_override="invalid://localhost",
storage_options={"azure_storage_account_name": "catalog-account"},
client_config={
"extra_headers": {
"X-LanceDB-Database": "wrong",
@@ -80,6 +83,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
assert db.table_names() == []
restored = lancedb.deserialize_conn(db.serialize())
assert restored.sql_host_override == "invalid://localhost"
assert restored.storage_options == {"azure_storage_account_name": "catalog-account"}
for connection in (db, restored):
with pytest.raises(ValueError, match="sql_host_override must use"):
connection.execute_query_async("SELECT 1")
@@ -98,6 +102,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
)
assert "x-lancedb-database-prefix" not in headers
assert headers["x-api-key"] == "secret"
assert headers["x-azure-storage-account-name"] == "catalog-account"
@pytest.mark.asyncio
@@ -114,7 +119,9 @@ async def test_catalog_async_and_errors(catalog_server):
]
)
catalog = await lancedb.connect_catalog_async(
endpoint, sql_host_override="invalid://localhost"
endpoint,
sql_host_override="invalid://localhost",
storage_options={"account_name": "async-account"},
)
assert isinstance(catalog, lancedb.AsyncCatalog)
db = await catalog.connect_database("analytics")
@@ -130,6 +137,9 @@ async def test_catalog_async_and_errors(catalog_server):
await catalog.drop_database("full")
await catalog.drop_database("missing", ignore_missing=True)
assert requests[4][2] == {"mode": "Fail", "behavior": "Restrict"}
for _, headers, _ in requests:
headers = {key.lower(): value for key, value in headers.items()}
assert headers["x-azure-storage-account-name"] == "async-account"
@pytest.mark.parametrize("endpoint", ["/tmp/catalog", "s3://bucket", "db://db"])
@@ -138,6 +148,170 @@ def test_catalog_requires_remote_endpoint(endpoint):
lancedb.connect_catalog(endpoint)
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("region", ["us-east-1", "not-a-region"])
@pytest.mark.asyncio
async def test_catalog_accepts_database_connection_settings(
catalog_server, asynchronous, region
):
endpoint, requests, responses = catalog_server
responses.extend([(200, {"namespaces": []}), (200, {"tables": []})])
settings = {
"uri": "db://analytics",
"api_key": "shared-secret",
"region": region,
"host_override": endpoint,
"sql_host_override": "invalid://localhost",
"read_consistency_interval": timedelta(seconds=5),
"client_config": {"extra_headers": {"x-shared-setting": "shared"}},
"storage_options": {"azure_storage_account_name": "shared-account"},
"session": None,
"manifest_enabled": False,
"namespace_client_properties": None,
}
if not asynchronous:
settings.update(
request_thread_pool=None,
namespace_client_impl=None,
namespace_client_pushdown_operations=None,
)
with pytest.warns(
UserWarning, match="region is ignored by connect_catalog"
) as caught:
catalog = (
await lancedb.connect_catalog_async(**settings)
if asynchronous
else lancedb.connect_catalog(**settings)
)
assert len(caught) == 1
assert catalog.uri == endpoint
assert (
[name async for name in catalog.list_databases()]
if asynchronous
else list(catalog.list_databases())
) == []
db = (
await lancedb.connect_async(**settings)
if asynchronous
else lancedb.connect(**settings)
)
assert (await db.table_names() if asynchronous else db.table_names()) == []
root_headers = {key.lower(): value for key, value in requests[0][1].items()}
db_headers = {key.lower(): value for key, value in requests[1][1].items()}
for headers in (root_headers, db_headers):
assert headers["x-api-key"] == "shared-secret"
assert headers["x-shared-setting"] == "shared"
assert headers["x-azure-storage-account-name"] == "shared-account"
assert "x-lancedb-database" not in root_headers
assert db_headers["x-lancedb-database"] == "analytics"
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("host_only", [False, True])
@pytest.mark.asyncio
async def test_catalog_default_region_is_silent_and_api_key_uses_environment(
catalog_server, monkeypatch, asynchronous, host_only
):
endpoint, requests, responses = catalog_server
monkeypatch.setenv("LANCEDB_API_KEY", "environment-secret")
responses.extend([(200, {}), (200, {"tables": []})])
settings = {"host_override": endpoint} if host_only else {"uri": endpoint}
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
catalog = (
await lancedb.connect_catalog_async(**settings)
if asynchronous
else lancedb.connect_catalog(**settings)
)
assert caught == []
assert catalog.uri == endpoint
db = (
await catalog.connect_database("analytics")
if asynchronous
else catalog.connect_database("analytics")
)
if not asynchronous:
db = lancedb.deserialize_conn(db.serialize())
assert (await db.table_names() if asynchronous else db.table_names()) == []
for _, headers, _ in requests:
headers = {key.lower(): value for key, value in headers.items()}
assert headers["x-api-key"] == "environment-secret"
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.asyncio
async def test_catalog_host_override_selects_endpoint(catalog_server, asynchronous):
endpoint, _, _ = catalog_server
settings = {"uri": "https://unused.example", "host_override": endpoint}
catalog = (
await lancedb.connect_catalog_async(**settings)
if asynchronous
else lancedb.connect_catalog(**settings)
)
assert catalog.uri == endpoint
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
"options, message",
[
({}, "uri or host_override is required"),
({"session": object()}, "session"),
({"manifest_enabled": True}, "manifest_enabled"),
({"namespace_client_properties": {}}, "namespace_client_properties"),
],
)
@pytest.mark.asyncio
async def test_catalog_rejects_unsupported_connection_settings(
catalog_server, asynchronous, options, message
):
_, requests, _ = catalog_server
error = NotImplementedError if options else ValueError
with pytest.raises(error, match=message):
if asynchronous:
await lancedb.connect_catalog_async(**options)
else:
lancedb.connect_catalog(**options)
assert requests == []
@pytest.mark.parametrize(
"options, error, message",
[
(
{"namespace_client_impl": "dir"},
NotImplementedError,
"namespace_client_impl",
),
(
{"namespace_client_pushdown_operations": []},
NotImplementedError,
"namespace_client_pushdown_operations",
),
({"unknown_option": True}, ValueError, "Unknown keyword arguments"),
],
)
def test_catalog_rejects_unsupported_sync_settings(options, error, message):
with pytest.raises(error, match=message):
lancedb.connect_catalog(**options)
def test_catalog_accepts_deprecated_sync_settings(catalog_server):
endpoint, _, responses = catalog_server
responses.append((200, {}))
with pytest.warns(DeprecationWarning) as caught:
catalog = lancedb.connect_catalog(
endpoint,
request_thread_pool=2,
connection_timeout=5,
read_timeout=10,
)
assert len(caught) == 3
db = catalog.connect_database("analytics")
assert db.client_config.timeout_config.connect_timeout == timedelta(seconds=5)
assert db.client_config.timeout_config.read_timeout == timedelta(seconds=10)
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.asyncio
@pytest.mark.parametrize("page_token,page_limit", [(None, None), ("start/token", 2)])
@@ -0,0 +1,36 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import pytest
import lancedb
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
async def test_clone_exist_ok_preserves_target(tmp_path, asynchronous):
source_uri = str(tmp_path / "source.lance")
if asynchronous:
db = await lancedb.connect_async(tmp_path)
await db.create_table("source", [{"id": 1}])
table = await db.clone_table("target", source_uri, exist_ok=True)
assert (await table.to_arrow()).to_pylist() == [{"id": 1}]
await table.add([{"id": 2}])
version = await table.version()
with pytest.raises(ValueError, match="already exists"):
await db.clone_table("target", source_uri)
kept = await db.clone_table("target", "missing.lance", exist_ok=True)
assert await kept.version() == version
assert (await kept.to_arrow()).to_pylist() == [{"id": 1}, {"id": 2}]
else:
db = lancedb.connect(tmp_path)
db.create_table("source", [{"id": 1}])
table = db.clone_table("target", source_uri, exist_ok=True)
assert table.to_arrow().to_pylist() == [{"id": 1}]
table.add([{"id": 2}])
version = table.version
with pytest.raises(ValueError, match="already exists"):
db.clone_table("target", source_uri)
kept = db.clone_table("target", "missing.lance", exist_ok=True)
assert kept.version == version
assert kept.to_arrow().to_pylist() == [{"id": 1}, {"id": 2}]
@@ -18,6 +18,7 @@ import subprocess
import sys
import typing
import urllib.parse
import warnings
from typing import Optional
import pyarrow as pa
@@ -658,9 +659,11 @@ def test_function_image_requires_digest_reference(image):
def test_function_gpu_marker_uses_gpu_runtime():
@function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g")
def double_on_gpu(value: int) -> int:
return value * 2
with pytest.warns(UserWarning, match="uses a scalar callable"):
@function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g")
def double_on_gpu(value: int) -> int:
return value * 2
request = json.loads(double_on_gpu.registration_request.to_canonical_json())
assert request["runtime"]["kind"] == "python_v2"
@@ -710,6 +713,60 @@ def test_function_gpu_marker_uses_gpu_runtime():
)
class _GpuScalarFunction:
def __call__(self, value: str) -> int:
return len(value)
class _GpuArrayFunction:
def __call__(self, value: pa.Array) -> pa.Array:
return value
def test_gpu_scalar_warning_names_the_vectorized_alternative():
with pytest.warns(UserWarning, match="model batch is not inferred"):
@function(gpu=True)
def scalar_embedding(value: str) -> list[int]:
return [len(value)]
input_schema = pa.schema([pa.field("value", pa.string(), nullable=False)])
with pytest.warns(UserWarning, match="uses a scalar callable"):
class_scalar = function(_GpuScalarFunction, gpu=True)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
@function(
gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64())
)
def array_embedding(value: pa.Array) -> pa.Array:
return value
@function(
gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64())
)
def record_batch_embedding(value: pa.RecordBatch) -> pa.Array:
return value.column(0)
@function
def cpu_scalar(value: str) -> int:
return len(value)
class_embedding = function(
_GpuArrayFunction,
gpu=True,
input_schema=input_schema,
output_schema=pa.list_(pa.int64()),
)
assert not caught
assert array_embedding.registration_request.batch_size is None
assert record_batch_embedding.registration_request.batch_size is None
assert cpu_scalar.registration_request.batch_size is None
assert class_scalar.registration_request.batch_size is None
assert class_embedding.registration_request.batch_size is None
def test_unknown_runtime_discards_payload_before_known_field_validation():
for payload in [
{
@@ -888,7 +945,7 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path):
spec = importlib.util.spec_from_file_location("aliasing_udfs", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
with pytest.raises(ValueError, match="dynamic namespace access"):
with pytest.raises(ValueError, match="imports from namespace-access modules"):
function(module.score)
@@ -899,7 +956,6 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path):
"eval('THRESHOLD')",
"(lambda g: g()['THRESHOLD'])(globals)",
"__import__('sys').modules[__name__].THRESHOLD",
"sys.modules[__name__].THRESHOLD",
],
)
def test_function_rejects_dynamic_namespace_access(access):
@@ -911,9 +967,7 @@ def test_function_rejects_dynamic_namespace_access(access):
)
with pytest.raises(ValueError, match="dynamic namespace access"):
_package_from_text(
"def score(value: int) -> int:\n"
" import sys\n"
f" return value + {access}\n"
f"def score(value: int) -> int:\n return value + {access}\n"
)
@@ -0,0 +1,63 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
from pathlib import Path
import pyarrow as pa
import pytest
import lancedb
from lancedb.functions import function
@pytest.mark.asyncio
@pytest.mark.parametrize("entry", ["sync", "sync_job", "async_job"])
@pytest.mark.parametrize("exist_ok", [None, False, True])
async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok):
flight = pytest.importorskip("pyarrow.flight")
fixture = (
Path(__file__).parents[3]
/ "rust/lancedb/tests/fixtures/first_class_functions/v1"
/ "remote_function_version.canonical.json"
)
stored = json.loads(fixture.read_text())
result = pa.table({"definition": [json.dumps(stored)]})
@function(name=stored["name"])
def replacement(value: float) -> float:
return value * 2
class FunctionServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.requests = []
def do_get(self, context, ticket):
self.requests.append(ticket.ticket)
return flight.RecordBatchStream(result)
with FunctionServer() as server:
options = {
"api_key": "test-key",
"host_override": "http://localhost:10024",
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
}
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
kwargs["namespace_path"] = ["team"]
if entry == "async_job":
db = await lancedb.connect_async("db://analytics", **options)
job = await db.create_function_async(replacement, **kwargs)
version = await job.wait()
else:
db = lancedb.connect("db://analytics", **options)
if entry == "sync_job":
version = db.create_function_async(replacement, **kwargs).wait()
else:
version = db.create_function(replacement, **kwargs)
(request,) = server.requests
prefix = "CREATE FUNCTION IF NOT EXISTS" if exist_ok else "CREATE FUNCTION"
assert f'{prefix} "{stored["name"]}" FROM '.encode() in request
assert b'"exist_ok"' not in request
assert json.loads(version.to_canonical_json()) == stored
+227 -13
View File
@@ -7,6 +7,7 @@ from __future__ import annotations
import base64
import importlib
import hashlib
import json
import subprocess
import sys
@@ -466,6 +467,126 @@ def test_nested_class_and_closure_are_rejected_with_the_reason():
return value * factor
@pytest.mark.parametrize(
"module_name",
[
"sys",
"builtins",
"importlib",
"inspect",
"gc",
"ctypes",
"types",
"ctypes.util",
"importlib.metadata",
],
)
@pytest.mark.parametrize("import_style", ["import", "from", "global"])
@pytest.mark.parametrize("class_function", [False, True])
def test_namespace_module_errors_explain_the_rule_and_remedy(
helper_package, module_name, import_style, class_function
):
statement = f"import {module_name} as namespace_module"
body = f"{statement}\nreturn value\n"
preamble = ""
if import_style == "from":
body = f"from {module_name} import __name__\nreturn value\n"
elif import_style == "global":
preamble = statement + "\n"
body = "return str(namespace_module)\n"
if class_function:
definition = "class blocked:\n def __call__(self, value: str) -> str:\n"
source = preamble + definition + textwrap.indent(body, " ")
else:
definition = "def blocked(value: str) -> str:\n"
source = preamble + definition + textwrap.indent(body, " ")
module = helper_package("fx_namespace_import", {"__init__.py": source})
with pytest.raises(ValueError) as error:
function(module.blocked)
message = str(error.value)
assert "imports from namespace-access modules" in message
assert repr(module_name) in message
assert "builtins, ctypes, gc, importlib, inspect, sys, types" in message
assert "including submodules" in message
assert "reconstructed module namespace" in message
assert "importable helper module" in message
assert "code=, pip=, or conda=" in message
assert "dynamic namespace access" not in message
@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
def test_udf_namespace_import_error_explains_the_helper_alternative():
with pytest.raises(ValueError, match="ctypes.util.*importable helper module"):
@udf
def probe(value: str) -> str:
import ctypes.util
return str(ctypes.util.find_library(value))
@pytest.mark.parametrize(
"operation", ["globals", "locals", "vars", "eval", "exec", "compile", "__import__"]
)
def test_dynamic_namespace_errors_name_the_operation_and_remedy(
helper_package, operation
):
module = helper_package(
"fx_namespace_operation",
{
"__init__.py": (
f"def blocked(value: str) -> str:\n return str({operation})\n"
)
},
)
with pytest.raises(ValueError) as error:
function(module.blocked)
message = str(error.value)
assert f"dynamic namespace access: ['{operation}']" in message
assert "Reference dependencies explicitly" in message
assert "importable helper module" in message
@pytest.mark.parametrize("ship_source", [False, True])
def test_namespace_access_in_importable_helpers_keeps_its_module_namespace(
helper_package, ship_source
):
helpers = helper_package(
"fx_namespace_helper",
{
"__init__.py": """
import ctypes.util
def module_name():
return ctypes.util.__name__
""",
},
)
entry = helper_package(
"fx_namespace_entry",
{
"__init__.py": """
from fx_namespace_helper import module_name
def probe(value: str) -> str:
return module_name() + value
""",
},
)
options = {"code": [helpers]} if ship_source else {"pip": ["fx-namespace-helper"]}
definition = function(**options)(entry.probe)
if ship_source:
files = bundle_files(definition)
assert "import ctypes.util" in files["fx_namespace_helper/__init__.py"]
source = files["user_function.py"]
else:
source = artifact(definition).decode()
namespace = {}
exec(compile(source, "user_function.py", "exec"), namespace)
assert namespace["probe"]("!") == "ctypes.util!"
def test_binding_passes_initialization_as_constants():
version = FunctionVersion.from_json(
json.dumps(
@@ -508,6 +629,102 @@ def test_binding_passes_initialization_as_constants():
version(text=col("body"), model=object())
def test_vendored_package_resources_survive_an_isolated_import(
tmp_path, helper_package
):
package = helper_package(
"fx_vendor",
{
"__init__.py": "from .vendor.model import predict",
"vendor/__init__.py": "",
"vendor/model.py": """
import hashlib
import json
from importlib.resources import files
def predict(value):
root = files("fx_vendor")
payload = root.joinpath("label-maps/payload.bin").read_bytes()
metadata = json.loads(root.joinpath("models.json").read_text())
source = root.joinpath("vendor/model.py").read_bytes()
source_digest = hashlib.sha256(source).hexdigest()
assert source_digest == metadata["source_sha256"]
assert hashlib.sha256(payload).hexdigest() == metadata["sha256"]
return value + metadata["offset"]
""",
"models.json": "{}",
},
)
payload = b"\x00\xff\r\nvendored model data"
package_root = Path(package.__file__).parent
(package_root / "label-maps").mkdir()
(package_root / "label-maps/payload.bin").write_bytes(payload)
module_path = package_root / "vendor/model.py"
module_bytes = (
module_path.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")
)
module_path.write_bytes(module_bytes)
(package_root / "models.json").write_bytes(
json.dumps(
{
"sha256": hashlib.sha256(payload).hexdigest(),
"source_sha256": hashlib.sha256(module_bytes).hexdigest(),
"offset": 7,
}
).encode()
+ b"\r\n"
)
entry = helper_package(
"fx_vendor_entry",
{
"__init__.py": """
import fx_vendor
from lancedb import function
@function(code=[fx_vendor])
def vendored(value: int) -> int:
return fx_vendor.predict(value)
"""
},
)
vendored = entry.vendored
first_digest = vendored.registration_request.artifact.digest
bundle = json.loads(artifact(vendored))
isolated = tmp_path / "isolated"
isolated.mkdir()
for name, content in bundle["files"].items():
target = isolated / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content.encode("utf-8"))
for name, content in bundle["resources"].items():
target = isolated / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(base64.b64decode(content))
assert (isolated / "fx_vendor/models.json").read_bytes().endswith(b"\r\n")
result = subprocess.run(
[
sys.executable,
"-I",
"-c",
"import sys; sys.path.insert(0, sys.argv[1]); "
"from user_function import vendored; assert vendored(3) == 10",
str(isolated),
],
capture_output=True,
text=True,
)
assert result.returncode == 0, result.stderr
(package_root / "models.json").write_text('{"offset": 8}')
assert (
function(code=[package])(
vendored._function
).registration_request.artifact.digest
!= first_digest
)
def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
tmp_path, helper_package
):
@@ -552,14 +769,13 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
first = define()
assert len(caught) == 1
warning = str(caught[0].message)
assert "fx_helpers/fixtures/data.json" in warning
assert "fx_helpers/fixtures/data.json" not in warning
assert "fx_helpers/not-a-module.py" in warning
assert warning.index("fx_helpers/fixtures/data.json") < warning.index(
"fx_helpers/not-a-module.py"
)
assert "remove 'fx_helpers' from code=" in warning
assert "pip=" in warning
assert "conda=" in warning
assert "safe relative names" in warning
assert "importable Python module names" in warning
resources = json.loads(artifact(first))["resources"]
assert base64.b64decode(resources["fx_helpers/fixtures/data.json"]) == b"{}"
assert "__pycache__" not in warning
assert ".pyc" not in warning
shipped = bundle_files(first)
@@ -612,7 +828,7 @@ def test_code_package_cache_artifacts_do_not_warn(helper_package):
]
def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_package):
def test_code_package_resources_keep_nonidentifier_directories(helper_package):
resources = helper_package(
"fx_resources",
{
@@ -628,11 +844,9 @@ def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_packag
def resource_boundary(value: int) -> int:
return value
assert len(caught) == 1
warning = str(caught[0].message)
assert "fx_resources/label-maps/" in warning
assert "remove 'fx_resources' from code=" in warning
assert "labels.json" not in warning
assert not caught
resources = json.loads(artifact(resource_boundary))["resources"]
assert base64.b64decode(resources["fx_resources/label-maps/labels.json"]) == b"{}"
assert sorted(bundle_files(resource_boundary)) == [
"fx_resources/__init__.py",
"user_function.py",
+42
View File
@@ -621,3 +621,45 @@ def test_index_statistics_index_type_lists_all_supported_values():
set(get_args(get_type_hints(IndexStatistics)["index_type"]))
== expected_index_types
)
@pytest.mark.asyncio
@pytest.mark.parametrize("background", [False, True])
@pytest.mark.parametrize(
"column,config", [("id", BTree()), ("vector", IvfFlat(num_partitions=1))]
)
async def test_index_exist_ok_preserves_existing_index(
some_table, background, column, config
):
await some_table.create_index(column, config=config, exist_ok=True)
version = await some_table.version()
original = await some_table.list_indices()
if background:
job = await some_table.create_index_async(
column, config=config, replace=True, exist_ok=True
)
await job.wait()
else:
await some_table.create_index(
column, config=config, replace=True, exist_ok=True
)
assert await some_table.version() == version
assert [(i.name, i.index_type) for i in await some_table.list_indices()] == [
(i.name, i.index_type) for i in original
]
@pytest.mark.asyncio
@pytest.mark.parametrize("background", [False, True])
async def test_named_index_exist_ok_checks_before_column_validation(
some_table, background
):
await some_table.create_index("id", config=BTree(), name="kept")
version = await some_table.version()
method = some_table.create_index_async if background else some_table.create_index
result = await method("missing", config=BTree(), name="kept", exist_ok=True)
if background:
assert result.id is None
await result.wait()
assert await some_table.version() == version
assert [index.name for index in await some_table.list_indices()] == ["kept"]
+40
View File
@@ -754,6 +754,46 @@ async def test_query_wait_timeout_requires_keeping_original_handle():
assert "db.open_job" not in message
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_stats_returns_fresh_report_without_waiting_or_printing(sync, capsys):
reports = [
None,
"Function job: finished\nWorker utilization: unavailable\n",
"Function job: finished\nWorker utilization: 25.0%\n",
]
inner = SimpleNamespace(
stats=AsyncMock(side_effect=reports),
wait=AsyncMock(),
cancel=AsyncMock(),
)
job = AsyncJob(inner)
for expected in reports:
actual = await asyncio.to_thread(Job(job).stats) if sync else await job.stats()
assert actual == expected
inner.wait.assert_not_awaited()
inner.cancel.assert_not_awaited()
assert capsys.readouterr().out == ""
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_stats_preserves_errors_and_rejects_untracked_jobs(sync):
error = RuntimeError("run reports are unavailable on this server")
job = AsyncJob(SimpleNamespace(stats=AsyncMock(side_effect=error)))
with pytest.raises(RuntimeError) as exc:
if sync:
await asyncio.to_thread(Job(job).stats)
else:
await job.stats()
assert exc.value is error
with pytest.raises(NotImplementedError, match="server-side Function job"):
if sync:
Job(None).stats()
else:
await AsyncJob(None).stats()
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path):

Some files were not shown because too many files have changed in this diff Show More