mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge branch 'merge-insert-source-stats' into merge-insert-source-stats-bindings
# Conflicts: # nodejs/src/merge.rs # python/python/lancedb/merge.py
This commit is contained in:
@@ -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
@@ -1,5 +1,5 @@
|
||||
[tool.bumpversion]
|
||||
current_version = "0.42.0-beta.10"
|
||||
current_version = "0.42.0-beta.16"
|
||||
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
|
||||
|
||||
@@ -23,6 +23,8 @@ jobs:
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
|
||||
with:
|
||||
components: clippy
|
||||
# Use only the downloads-only cache configured below.
|
||||
cache: false
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2
|
||||
with:
|
||||
# Restoring compiled targets can exhaust the hosted runner disk.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -234,7 +234,8 @@ jobs:
|
||||
NODE_OPTIONS: "--experimental-vm-modules"
|
||||
run: node_modules/.bin/jest --verbose
|
||||
macos:
|
||||
timeout-minutes: 30
|
||||
# Cold native builds can take 28 minutes; reserve time for setup and Jest.
|
||||
timeout-minutes: 35
|
||||
# macos-15 ships a newer linker; the older macos-14 linker fails to insert
|
||||
# branch islands when the debug cdylib's __text section exceeds the 128 MB
|
||||
# AArch64 B/BL branch range.
|
||||
@@ -257,7 +258,11 @@ jobs:
|
||||
node-version: 24
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: nodejs/pnpm-lock.yaml
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
# Use the same pinned compiler for cache selection and the native build.
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
cache: false
|
||||
rustflags: ""
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
# Restore everywhere, but only save from main. Per-PR saves are
|
||||
|
||||
@@ -66,7 +66,8 @@ jobs:
|
||||
choco install --no-progress protoc
|
||||
rustup target add aarch64-pc-windows-msvc
|
||||
- target: x86_64-unknown-linux-gnu
|
||||
host: ubuntu-latest
|
||||
# Fat LTO reached 15.1 GiB before rustc was killed on the 15 GiB runner.
|
||||
host: ubuntu-2404-8x-x64
|
||||
features: fp16kernels
|
||||
# https://github.com/napi-rs/napi-rs/blob/main/debian.Dockerfile
|
||||
docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-debian
|
||||
@@ -161,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:
|
||||
|
||||
@@ -36,8 +36,8 @@ concurrency:
|
||||
jobs:
|
||||
linux:
|
||||
name: Python ${{ matrix.config.package_name }} ${{ matrix.config.platform }} manylinux${{ matrix.config.manylinux }}
|
||||
# The ARM64 release build can exceed an hour with fat LTO on a cold runner.
|
||||
timeout-minutes: ${{ matrix.config.platform == 'aarch64' && 120 || 60 }}
|
||||
# ARM64 and compatibility release builds can exceed an hour with cold fat LTO.
|
||||
timeout-minutes: ${{ (matrix.config.platform == 'aarch64' || matrix.config.package_name == 'lancedb-compat') && 120 || 60 }}
|
||||
strategy:
|
||||
matrix:
|
||||
config:
|
||||
@@ -64,7 +64,8 @@ jobs:
|
||||
- platform: x86_64
|
||||
manylinux: "2_28"
|
||||
extra_args: ""
|
||||
runner: ubuntu-22.04
|
||||
# Keep fat LTO on the same larger runner as the standard x64 wheel.
|
||||
runner: ubuntu-2404-8x-x64
|
||||
package_name: "lancedb-compat"
|
||||
rustflags: "-Ctarget-cpu=x86-64-v2"
|
||||
runs-on: ${{ matrix.config.runner }}
|
||||
@@ -102,7 +103,8 @@ jobs:
|
||||
path: target/wheels/*.whl
|
||||
if-no-files-found: error
|
||||
mac:
|
||||
timeout-minutes: 90
|
||||
# Cold fat LTO was still compiling when the 90-minute limit was reached.
|
||||
timeout-minutes: 150
|
||||
runs-on: ${{ matrix.config.runner }}
|
||||
strategy:
|
||||
matrix:
|
||||
|
||||
@@ -130,7 +130,8 @@ jobs:
|
||||
run: pytest --doctest-modules python/lancedb
|
||||
linux:
|
||||
name: "Linux: python-3.${{ matrix.python-minor-version }}"
|
||||
timeout-minutes: 30
|
||||
# A cold native build plus both test passes can exhaust 30 minutes.
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
matrix:
|
||||
python-minor-version: ["10", "13"]
|
||||
@@ -179,7 +180,8 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
features: ["default", "experimental-functions"]
|
||||
timeout-minutes: 30
|
||||
# A cold native build plus experimental-functions tests can exceed 30 minutes.
|
||||
timeout-minutes: 60
|
||||
runs-on: macos-15
|
||||
defaults:
|
||||
run:
|
||||
|
||||
@@ -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
|
||||
@@ -289,16 +291,16 @@ jobs:
|
||||
sudo apt update
|
||||
sudo apt install -y protobuf-compiler libssl-dev
|
||||
- uses: rui314/setup-mold@v1
|
||||
- name: Test the default local Functions gate
|
||||
run: cargo test --profile ci -p lancedb --features remote --test experimental_functions --locked
|
||||
- name: Run remote tests
|
||||
run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests
|
||||
|
||||
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 +322,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 +347,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 +386,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
+427
-287
File diff suppressed because it is too large
Load Diff
+15
-15
@@ -19,21 +19,21 @@ categories = ["database-implementations"]
|
||||
rust-version = "1.95.0"
|
||||
|
||||
[workspace.dependencies]
|
||||
lance = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-core = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-datagen = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-file = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-io = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-index = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-jsonb = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-linalg = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-namespace = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-namespace-impls = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-table = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-testing = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-datafusion = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-encoding = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-arrow = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-core = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-datagen = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-file = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-io = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-index = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-jsonb = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-linalg = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-namespace = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-namespace-impls = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-table = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-testing = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-datafusion = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-encoding = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-arrow = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lancedb = { path = "rust/lancedb", default-features = false }
|
||||
ahash = "0.8"
|
||||
anyhow = "1"
|
||||
|
||||
+2
-1
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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.10</version>
|
||||
<version>0.42.0-beta.16</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
|
||||
@@ -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`<(`null` \| `Buffer`)[]>
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
const bytes = await table.fetchBlobRanges("image", [
|
||||
{ rowId: 10n, offset: 0n, length: 1024n },
|
||||
]);
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### fetchBlobs()
|
||||
|
||||
```ts
|
||||
@@ -704,6 +746,47 @@ so this is safe to call repeatedly.
|
||||
|
||||
***
|
||||
|
||||
### functionColumnStatus()
|
||||
|
||||
```ts
|
||||
abstract functionColumnStatus(column): Promise<FunctionColumnStatus>
|
||||
```
|
||||
|
||||
Return exact freshness status for one Function-backed output column.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **column**: `string`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)>
|
||||
|
||||
***
|
||||
|
||||
### functionColumnStatuses()
|
||||
|
||||
```ts
|
||||
abstract functionColumnStatuses(column?): Promise<FunctionColumnStatus[]>
|
||||
```
|
||||
|
||||
Return exact freshness status for Function-backed output columns.
|
||||
|
||||
All results describe one server table version. Omit `column` for every
|
||||
Function output. Rows already failed remain visible and do not prevent
|
||||
`waitFresh` from completing. A handle pinned to an exact version requests
|
||||
that version; a latest handle retains normal read-freshness behavior.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **column?**: `string`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)[]>
|
||||
|
||||
***
|
||||
|
||||
### functionErrors()
|
||||
|
||||
```ts
|
||||
@@ -1142,12 +1225,18 @@ LanceDB Enterprise it is the server's backfill job.
|
||||
`REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows,
|
||||
`errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds`
|
||||
and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`,
|
||||
`maxConcurrency`, `resourceBudget` and
|
||||
`maxExecutorProcessesPerWorker` size registered Function refreshes.
|
||||
`maxConcurrency`, `resourceBudget`, `supervisorResources`,
|
||||
`planningWorkers` and `maxExecutorProcessesPerWorker` size registered
|
||||
Function refreshes. `retryPolicy` overrides user-code retries only when
|
||||
repeating partial work is safe; set `maxAttempts: 1` to disable retries.
|
||||
`maxConcurrency` overrides the registered default for this logical
|
||||
execution only and is a positive integer; it is not an account-wide
|
||||
quota. A `resourceBudget` requires `cpuMillis` and
|
||||
`memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function.
|
||||
`supervisorResources` and each `planningWorkers.resources` entry require
|
||||
positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`.
|
||||
`planningWorkers` also requires positive `maxWorkers`,
|
||||
`rowsPerWorker` and `fragmentsPerWorker`.
|
||||
The budget applies only to this explicit refresh and does not configure
|
||||
a later automatic refresh.
|
||||
`gpuCount` at the top level is the shorthand that preserves the
|
||||
@@ -1156,6 +1245,11 @@ LanceDB Enterprise it is the server's backfill job.
|
||||
`resourceBudget` for registered Functions. All are LanceDB Enterprise
|
||||
only; a LanceDB Embedded refresh rejects every option other than
|
||||
`batchSize`, `gpuClass` and `gpuCount`.
|
||||
`publicationIntervalRows` opts into publishing completed Function split
|
||||
ranges once their accumulated unpublished rows reach the threshold.
|
||||
It must be a positive safe integer and requires non-Blob Function outputs.
|
||||
Omit it for whole-fragment publication. Publications can exceed the
|
||||
threshold, and remaining rows publish at completion.
|
||||
|
||||
#### Returns
|
||||
|
||||
@@ -1171,6 +1265,7 @@ const job = await table.refreshColumnAsync("embedding", {
|
||||
memoryBytes: 16 * 1024 ** 3,
|
||||
},
|
||||
maxConcurrency: 4,
|
||||
publicationIntervalRows: 10000,
|
||||
errorPolicy: "skip",
|
||||
maxFailedFraction: 0.01,
|
||||
rowTimeoutSeconds: 30,
|
||||
@@ -1598,3 +1693,26 @@ Waits for asynchronous indexing to complete on the table.
|
||||
#### Returns
|
||||
|
||||
`Promise`<`void`>
|
||||
|
||||
***
|
||||
|
||||
### waitFresh()
|
||||
|
||||
```ts
|
||||
abstract waitFresh(column, timeoutSeconds?): Promise<FunctionColumnStatus>
|
||||
```
|
||||
|
||||
Poll until no stale or never-computed rows remain.
|
||||
|
||||
Only HTTP 503 with the exact finalization-pending error code is retried;
|
||||
every other error propagates. Failed rows do not block completion.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **column**: `string`
|
||||
|
||||
* **timeoutSeconds?**: `number`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)>
|
||||
|
||||
@@ -95,10 +95,17 @@
|
||||
- [FtsToken](interfaces/FtsToken.md)
|
||||
- [FullTextQuery](interfaces/FullTextQuery.md)
|
||||
- [FullTextSearchOptions](interfaces/FullTextSearchOptions.md)
|
||||
- [FunctionColumnAutoRefreshStatus](interfaces/FunctionColumnAutoRefreshStatus.md)
|
||||
- [FunctionColumnLastRefreshJob](interfaces/FunctionColumnLastRefreshJob.md)
|
||||
- [FunctionColumnStatus](interfaces/FunctionColumnStatus.md)
|
||||
- [FunctionColumnVersionStatus](interfaces/FunctionColumnVersionStatus.md)
|
||||
- [FunctionErrorFragment](interfaces/FunctionErrorFragment.md)
|
||||
- [FunctionErrorRecord](interfaces/FunctionErrorRecord.md)
|
||||
- [FunctionErrors](interfaces/FunctionErrors.md)
|
||||
- [FunctionErrorsOptions](interfaces/FunctionErrorsOptions.md)
|
||||
- [FunctionRefreshPlanningConfig](interfaces/FunctionRefreshPlanningConfig.md)
|
||||
- [FunctionRefreshPodResources](interfaces/FunctionRefreshPodResources.md)
|
||||
- [FunctionRetryPolicy](interfaces/FunctionRetryPolicy.md)
|
||||
- [FunctionWorkerResourceBudget](interfaces/FunctionWorkerResourceBudget.md)
|
||||
- [HnswPqOptions](interfaces/HnswPqOptions.md)
|
||||
- [HnswSqOptions](interfaces/HnswSqOptions.md)
|
||||
@@ -165,6 +172,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)
|
||||
|
||||
@@ -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,98 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionColumnAutoRefreshStatus
|
||||
|
||||
# Interface: FunctionColumnAutoRefreshStatus
|
||||
|
||||
Automatic-refresh projection for a Function output.
|
||||
|
||||
## Properties
|
||||
|
||||
### activeJobId?
|
||||
|
||||
```ts
|
||||
optional activeJobId: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### blockedReason?
|
||||
|
||||
```ts
|
||||
optional blockedReason:
|
||||
| "table_has_mem_wal"
|
||||
| "inputs_not_settled"
|
||||
| "dependency_in_flight"
|
||||
| "table_capacity"
|
||||
| "cancelled"
|
||||
| "preparation_backoff"
|
||||
| "failure_threshold_reached"
|
||||
| "binding_revision_missing";
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### effectiveCooldownMillis?
|
||||
|
||||
```ts
|
||||
optional effectiveCooldownMillis: bigint;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### enabled
|
||||
|
||||
```ts
|
||||
enabled: boolean;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### failureStreak
|
||||
|
||||
```ts
|
||||
failureStreak: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### intervalSeconds?
|
||||
|
||||
```ts
|
||||
optional intervalSeconds: bigint;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### nextRunAtMillis
|
||||
|
||||
```ts
|
||||
nextRunAtMillis: null | bigint;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### nextRunAtReason?
|
||||
|
||||
```ts
|
||||
optional nextRunAtReason: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### state
|
||||
|
||||
```ts
|
||||
state:
|
||||
| "running"
|
||||
| "queued"
|
||||
| "disabled"
|
||||
| "ready"
|
||||
| "up_to_date"
|
||||
| "waiting_interval"
|
||||
| "waiting_backoff"
|
||||
| "blocked"
|
||||
| "unobservable";
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionColumnLastRefreshJob
|
||||
|
||||
# Interface: FunctionColumnLastRefreshJob
|
||||
|
||||
Latest matching refresh Job projected for a Function output.
|
||||
|
||||
## Properties
|
||||
|
||||
### automatic?
|
||||
|
||||
```ts
|
||||
optional automatic: boolean;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### completedAtMillis?
|
||||
|
||||
```ts
|
||||
optional completedAtMillis: bigint;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### failure?
|
||||
|
||||
```ts
|
||||
optional failure: JobFailureInfo;
|
||||
```
|
||||
|
||||
Structured failure details for a failed Job.
|
||||
|
||||
***
|
||||
|
||||
### jobId
|
||||
|
||||
```ts
|
||||
jobId: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### state
|
||||
|
||||
```ts
|
||||
state: string;
|
||||
```
|
||||
@@ -0,0 +1,108 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionColumnStatus
|
||||
|
||||
# Interface: FunctionColumnStatus
|
||||
|
||||
Exact four-way status of one Function output at one table version.
|
||||
|
||||
## Properties
|
||||
|
||||
### autoRefresh
|
||||
|
||||
```ts
|
||||
autoRefresh: FunctionColumnAutoRefreshStatus;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### bindingId
|
||||
|
||||
```ts
|
||||
bindingId: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### column
|
||||
|
||||
```ts
|
||||
column: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### failed
|
||||
|
||||
```ts
|
||||
failed: bigint;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### fresh
|
||||
|
||||
```ts
|
||||
fresh: bigint;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### function
|
||||
|
||||
```ts
|
||||
function: FunctionColumnVersionStatus;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### lastFailureJob?
|
||||
|
||||
```ts
|
||||
optional lastFailureJob: FunctionColumnLastRefreshJob;
|
||||
```
|
||||
|
||||
Newest failed refresh Job. This remains present when `lastRefreshJob`
|
||||
is a later cancellation.
|
||||
|
||||
***
|
||||
|
||||
### lastRefreshJob?
|
||||
|
||||
```ts
|
||||
optional lastRefreshJob: FunctionColumnLastRefreshJob;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### neverComputed
|
||||
|
||||
```ts
|
||||
neverComputed: bigint;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### rows
|
||||
|
||||
```ts
|
||||
rows: bigint;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### stale
|
||||
|
||||
```ts
|
||||
stale: bigint;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### tableVersion
|
||||
|
||||
```ts
|
||||
tableVersion: bigint;
|
||||
```
|
||||
@@ -0,0 +1,57 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionColumnVersionStatus
|
||||
|
||||
# Interface: FunctionColumnVersionStatus
|
||||
|
||||
Exact immutable Function revision attached to a table output.
|
||||
|
||||
## Properties
|
||||
|
||||
### location
|
||||
|
||||
```ts
|
||||
location: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### manifestDigest
|
||||
|
||||
```ts
|
||||
manifestDigest: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### name
|
||||
|
||||
```ts
|
||||
name: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### namespacePath
|
||||
|
||||
```ts
|
||||
namespacePath: string[];
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### objectId
|
||||
|
||||
```ts
|
||||
objectId: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### version
|
||||
|
||||
```ts
|
||||
version: string;
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionRefreshPlanningConfig
|
||||
|
||||
# Interface: FunctionRefreshPlanningConfig
|
||||
|
||||
Resources and sizing policy for the planning fleet of one registered
|
||||
Function refresh.
|
||||
|
||||
## Properties
|
||||
|
||||
### fragmentsPerWorker
|
||||
|
||||
```ts
|
||||
fragmentsPerWorker: number;
|
||||
```
|
||||
|
||||
Maximum fragments assigned to one planning worker.
|
||||
|
||||
***
|
||||
|
||||
### maxWorkers
|
||||
|
||||
```ts
|
||||
maxWorkers: number;
|
||||
```
|
||||
|
||||
Maximum number of planning workers.
|
||||
|
||||
***
|
||||
|
||||
### resources
|
||||
|
||||
```ts
|
||||
resources: FunctionRefreshPodResources;
|
||||
```
|
||||
|
||||
CPU, memory, and ephemeral-storage limits for one planning worker.
|
||||
|
||||
***
|
||||
|
||||
### rowsPerWorker
|
||||
|
||||
```ts
|
||||
rowsPerWorker: number;
|
||||
```
|
||||
|
||||
Maximum rows assigned to one planning worker.
|
||||
@@ -0,0 +1,40 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionRefreshPodResources
|
||||
|
||||
# Interface: FunctionRefreshPodResources
|
||||
|
||||
CPU, memory, and ephemeral-storage limits for one Function refresh
|
||||
control-plane pod.
|
||||
|
||||
## Properties
|
||||
|
||||
### cpuMillis
|
||||
|
||||
```ts
|
||||
cpuMillis: number;
|
||||
```
|
||||
|
||||
CPU limit in millicores; 1000 is one CPU.
|
||||
|
||||
***
|
||||
|
||||
### ephemeralStorageBytes
|
||||
|
||||
```ts
|
||||
ephemeralStorageBytes: number;
|
||||
```
|
||||
|
||||
Ephemeral storage limit in bytes.
|
||||
|
||||
***
|
||||
|
||||
### memoryBytes
|
||||
|
||||
```ts
|
||||
memoryBytes: number;
|
||||
```
|
||||
|
||||
Memory limit in bytes.
|
||||
@@ -0,0 +1,91 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionRetryPolicy
|
||||
|
||||
# Interface: FunctionRetryPolicy
|
||||
|
||||
Overrides retries of failed user-code calls for one refresh. Omitted
|
||||
fields use the Function refresh defaults.
|
||||
|
||||
## Properties
|
||||
|
||||
### errorCodes?
|
||||
|
||||
```ts
|
||||
optional errorCodes: string[];
|
||||
```
|
||||
|
||||
Structured provider error codes or HTTP status codes.
|
||||
|
||||
***
|
||||
|
||||
### exceptionTypes?
|
||||
|
||||
```ts
|
||||
optional exceptionTypes: string[];
|
||||
```
|
||||
|
||||
Exception class names, preferably qualified.
|
||||
|
||||
***
|
||||
|
||||
### honorRetryAfter?
|
||||
|
||||
```ts
|
||||
optional honorRetryAfter: boolean;
|
||||
```
|
||||
|
||||
Honor Retry-After within the configured maximum.
|
||||
|
||||
***
|
||||
|
||||
### initialBackoffSeconds?
|
||||
|
||||
```ts
|
||||
optional initialBackoffSeconds: number;
|
||||
```
|
||||
|
||||
Initial exponential-backoff ceiling, in seconds.
|
||||
|
||||
***
|
||||
|
||||
### maxAttempts?
|
||||
|
||||
```ts
|
||||
optional maxAttempts: number;
|
||||
```
|
||||
|
||||
Total calls, including the first; 1 disables retries, maximum 100.
|
||||
|
||||
***
|
||||
|
||||
### maxBackoffSeconds?
|
||||
|
||||
```ts
|
||||
optional maxBackoffSeconds: number;
|
||||
```
|
||||
|
||||
Maximum backoff, in seconds.
|
||||
|
||||
***
|
||||
|
||||
### messagePattern?
|
||||
|
||||
```ts
|
||||
optional messagePattern: string;
|
||||
```
|
||||
|
||||
Regular expression matched against the exception class and message.
|
||||
|
||||
***
|
||||
|
||||
### transient?
|
||||
|
||||
```ts
|
||||
optional transient: boolean;
|
||||
```
|
||||
|
||||
Match connection/timeouts, HTTP 429/503, SlowDown and
|
||||
ServiceUnavailable.
|
||||
@@ -34,6 +34,16 @@ optional retryable: boolean;
|
||||
|
||||
***
|
||||
|
||||
### sqlJobId?
|
||||
|
||||
```ts
|
||||
optional sqlJobId: string;
|
||||
```
|
||||
|
||||
Isolated SQL job that raised this failure, when supplied by the server.
|
||||
|
||||
***
|
||||
|
||||
### traceback?
|
||||
|
||||
```ts
|
||||
|
||||
@@ -29,8 +29,10 @@ Selecting a parent struct or directly aliasing a blob or struct also returns
|
||||
bytes. Blobs inside lists keep their descriptors. Arbitrary projection
|
||||
expressions are not materialized as bytes.
|
||||
|
||||
The rows and the bytes come from the same table version. If the table
|
||||
changes while the query runs, the query runs again, up to three times.
|
||||
The rows and bytes come from the same snapshot. Remote queries require
|
||||
authoritative query version and snapshot identity headers, verified again
|
||||
by the blob response. Older servers can still return `"descriptions"`.
|
||||
Local queries retry up to three times if the table changes while they run.
|
||||
|
||||
#### Example
|
||||
|
||||
|
||||
@@ -117,6 +117,29 @@ Worker count for an expression column; Function columns reject it.
|
||||
|
||||
***
|
||||
|
||||
### planningWorkers?
|
||||
|
||||
```ts
|
||||
optional planningWorkers: FunctionRefreshPlanningConfig;
|
||||
```
|
||||
|
||||
Resources and sizing for the refresh planning fleet.
|
||||
|
||||
***
|
||||
|
||||
### publicationIntervalRows?
|
||||
|
||||
```ts
|
||||
optional publicationIntervalRows: number;
|
||||
```
|
||||
|
||||
Row-count threshold for publishing completed Function split ranges.
|
||||
Must be a positive safe integer. Omit for whole-fragment publication.
|
||||
Actual publications can be larger; remaining rows publish at completion.
|
||||
Requires LanceDB Enterprise with non-Blob Function outputs.
|
||||
|
||||
***
|
||||
|
||||
### resourceBudget?
|
||||
|
||||
```ts
|
||||
@@ -128,6 +151,16 @@ refresh. `gpuCount` inside the budget defaults to zero.
|
||||
|
||||
***
|
||||
|
||||
### retryPolicy?
|
||||
|
||||
```ts
|
||||
optional retryPolicy: FunctionRetryPolicy;
|
||||
```
|
||||
|
||||
Override retries of failed user-code calls for this refresh.
|
||||
|
||||
***
|
||||
|
||||
### rowTimeoutSeconds?
|
||||
|
||||
```ts
|
||||
@@ -138,6 +171,16 @@ Deadline for one Function call, in seconds.
|
||||
|
||||
***
|
||||
|
||||
### supervisorResources?
|
||||
|
||||
```ts
|
||||
optional supervisorResources: FunctionRefreshPodResources;
|
||||
```
|
||||
|
||||
CPU, memory, and ephemeral-storage limits for the refresh supervisor.
|
||||
|
||||
***
|
||||
|
||||
### where?
|
||||
|
||||
```ts
|
||||
|
||||
@@ -8,6 +8,26 @@
|
||||
|
||||
## Properties
|
||||
|
||||
### retries?
|
||||
|
||||
```ts
|
||||
optional retries: number;
|
||||
```
|
||||
|
||||
Override the remote retry budget for this execution only (an integer from
|
||||
0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after
|
||||
precommit conflicts (409) or rate limits (429). This does not change
|
||||
connection-wide/read budgets or local transaction conflict retries.
|
||||
|
||||
By default, remote calls use the connection's `clientConfig.retryConfig`
|
||||
([RetryConfig](RetryConfig.md)). Its `statuses` (also set through
|
||||
`LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget;
|
||||
it never permits replay of ambiguous merge outcomes. In particular, 502,
|
||||
ordinary 503, and 504 are never replayed, even if configured. Reconcile table
|
||||
contents before manually repeating a merge whose commit outcome is unknown.
|
||||
|
||||
***
|
||||
|
||||
### timeoutMs?
|
||||
|
||||
```ts
|
||||
@@ -24,3 +44,6 @@ the second attempt will be cancelled after 10 seconds, hitting the
|
||||
first attempt will not be cancelled.
|
||||
|
||||
When this is set, the timeout is enforced on all attempts, including the first.
|
||||
For remote tables this is sent as a server execution timeout. It does not
|
||||
extend HTTP read or proxy idle timeouts, or prove that a failed request did
|
||||
not commit.
|
||||
|
||||
@@ -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.
|
||||
@@ -37,11 +37,35 @@ 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
|
||||
patterns apply to `list_namespaces()`. Other resource listings use `page_limit`.
|
||||
|
||||
For existence checks, use `db.table_exists(["events"])` or `"events" in db`.
|
||||
These look up the table directly and work even when the database has more than
|
||||
100 tables. For a table in a namespace, include the namespace segments:
|
||||
|
||||
```python
|
||||
exists = db.table_exists(["analytics", "events"])
|
||||
```
|
||||
|
||||
When migrating from `name in db.table_names()`, use `name in db` or
|
||||
`db.table_exists([name])`. Checking `name in db.list_tables().tables` only
|
||||
searches the first page and can miss an existing table.
|
||||
|
||||
Resource listings (`list_storage_integrations`, `list_secrets`, `list_views`, `list_jobs`, `list_functions`, and
|
||||
`list_materialized_views`) return lazy iterators. Use `list(db.list_views())` to
|
||||
collect synchronous results, or `[name async for name in db.list_views()]` with
|
||||
@@ -400,6 +424,25 @@ code that used the former LanceDB Enterprise-only argument order.
|
||||
|
||||
## Functions and Jobs
|
||||
|
||||
Use `progress=True` when waiting for Function registration in a notebook or
|
||||
terminal. A callback receives structured snapshots instead:
|
||||
|
||||
```python
|
||||
fn = db.create_function(my_function, progress=True)
|
||||
registration = db.create_function_async(other_function)
|
||||
fn = registration.wait(progress=lambda snapshot: print(snapshot))
|
||||
print(fn.image.describe())
|
||||
```
|
||||
|
||||
Registration uses the existing SQL query handle. The current handle reports
|
||||
lifecycle state and `client_elapsed_time_millis` since the handle was created;
|
||||
detailed build phases and build logs are unavailable. Keep the same handle after
|
||||
a wait timeout to resume waiting. Failures retain the server error and request
|
||||
identifiers. `fn.image` has a concise representation; `describe()` exposes Python
|
||||
and CUDA requirements without inspecting Pydantic internals. Platforms, base image
|
||||
and size are `None` until the service reports them. The full image descriptor and
|
||||
canonical JSON remain available.
|
||||
|
||||
A `@function` definition is also a local callable. Call a decorated function
|
||||
directly with row inputs, or call a decorated class with its initialization fields
|
||||
and then call the returned instance; call `close()` if the class defines it. This
|
||||
@@ -435,6 +478,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
|
||||
@@ -495,6 +583,14 @@ with BlobReader(read_range, len(payload)) as reader:
|
||||
|
||||
::: lancedb.functions.FunctionVersion
|
||||
|
||||
::: lancedb.functions.FunctionEnvironment
|
||||
|
||||
::: lancedb.functions.ResolvedEnvironment
|
||||
|
||||
::: lancedb.functions.ResolvedPackage
|
||||
|
||||
::: lancedb.functions.ResolvedEnvironmentProvenance
|
||||
|
||||
::: lancedb.functions.HuggingFaceModel
|
||||
|
||||
::: lancedb.functions.PythonRuntimeSpec
|
||||
@@ -509,6 +605,8 @@ with BlobReader(read_range, len(payload)) as reader:
|
||||
|
||||
::: lancedb.functions.InputBinding
|
||||
|
||||
::: lancedb.functions.LiteralInputBinding
|
||||
|
||||
::: lancedb.functions.OutputMapping
|
||||
|
||||
::: lancedb.functions.AssignmentMapping
|
||||
@@ -523,6 +621,14 @@ with BlobReader(read_range, len(payload)) as reader:
|
||||
|
||||
::: lancedb.FunctionErrorFragment
|
||||
|
||||
::: lancedb.FunctionColumnStatus
|
||||
|
||||
::: lancedb.FunctionColumnVersionStatus
|
||||
|
||||
::: lancedb.FunctionColumnLastRefreshJob
|
||||
|
||||
::: lancedb.FunctionColumnAutoRefreshStatus
|
||||
|
||||
::: lancedb.job.Job
|
||||
|
||||
::: lancedb.job.AsyncJob
|
||||
@@ -550,6 +656,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`:
|
||||
|
||||
@@ -728,6 +848,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:
|
||||
@@ -1047,6 +1176,11 @@ the page list does not consume the iterator. `page.page_token` is the token for
|
||||
the next request; drain cached results before using it to resume in a new
|
||||
listing. The same behavior applies to namespaces.
|
||||
|
||||
Use `await db.table_exists(["events"])` to check for a table in the root
|
||||
namespace, or `await db.table_exists(["analytics", "events"])` for a table in
|
||||
a namespace. Checking membership in an awaited listing's `.tables` attribute
|
||||
only searches one page.
|
||||
|
||||
::: lancedb.listing.AsyncTableListing
|
||||
|
||||
::: lancedb.listing.AsyncNamespaceListing
|
||||
@@ -1315,3 +1449,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.
|
||||
|
||||
@@ -154,13 +154,27 @@ def test_function_output_nullability():
|
||||
("note", True),
|
||||
]
|
||||
|
||||
# A scalar output, and a struct declared as one nullable field, may not be.
|
||||
for nullable in (
|
||||
pa.field("result", pa.float64(), nullable=True),
|
||||
pa.field("result", pa.struct(fields), nullable=True),
|
||||
):
|
||||
with pytest.raises(ValueError, match="non-nullable"):
|
||||
function(input_schema=inputs, output_schema=nullable)(describe)
|
||||
# A scalar output may be nullable.
|
||||
@function(input_schema=inputs)
|
||||
def maybe_double(value: float) -> float | None:
|
||||
return None if value == 0 else value * 2
|
||||
|
||||
output = maybe_double.registration_request.signature.output
|
||||
assert (output.kind, output.arrow_type, output.nullable) == (
|
||||
"scalar",
|
||||
"float64",
|
||||
True,
|
||||
)
|
||||
assert json.loads(maybe_double.registration_request.signature.to_canonical_json())[
|
||||
"output"
|
||||
] == {"kind": "scalar", "arrow_type": "float64", "nullable": True}
|
||||
|
||||
# A struct declared as one nullable field may not be.
|
||||
with pytest.raises(ValueError, match="non-nullable"):
|
||||
function(
|
||||
input_schema=inputs,
|
||||
output_schema=pa.field("result", pa.struct(fields), nullable=True),
|
||||
)(describe)
|
||||
|
||||
|
||||
def test_function_registration_is_remote(tmp_path):
|
||||
|
||||
Generated
+68
-233
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
+125
-3
@@ -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
|
||||
@@ -42,9 +82,21 @@ print(job.status())
|
||||
result. If it failed or was cancelled, inspect the failure details and any
|
||||
results it committed before stopping.
|
||||
|
||||
In Python, `job.status()` reports the current state and `job.wait()` waits for
|
||||
completion, raising if the job fails or is cancelled. Both `Job.wait()` and
|
||||
`AsyncJob.wait()` retry transient connection and read errors with capped
|
||||
In Python, `job.status()` returns the current state:
|
||||
|
||||
| State | Meaning |
|
||||
| --- | --- |
|
||||
| `running` | The operation is in progress. |
|
||||
| `finished` | The operation completed successfully. |
|
||||
| `failed` | The operation failed. |
|
||||
| `cancelled` | The operation was cancelled. |
|
||||
|
||||
`job.status()` checks the current state without waiting for completion.
|
||||
It returns `failed` or `cancelled` for unsuccessful jobs.
|
||||
|
||||
Use `job.wait()` to wait for completion and raise if the job fails or is
|
||||
cancelled. Both `Job.wait()` and `AsyncJob.wait()` retry transient connection
|
||||
and read errors with capped
|
||||
exponential backoff within the caller's timeout. Without a timeout, retries
|
||||
continue indefinitely.
|
||||
|
||||
@@ -121,6 +173,76 @@ 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. Use `list(db.list_jobs(...))` to collect all remaining results;
|
||||
there is no `.to_list()` method.
|
||||
|
||||
<Note>
|
||||
Job filters and synchronous `Listing` indexing, slicing, and `len()` require
|
||||
a Python SDK release that includes these APIs. Older SDKs expose only
|
||||
`page_token` and `page_limit`; collect results with `list(...)` before indexing
|
||||
or counting them. Filtering also requires a matching Enterprise server that
|
||||
supports the requested filters.
|
||||
</Note>
|
||||
|
||||
Filter jobs on the server before pagination with `table`, `state`, `job_type`
|
||||
or `job_types`, and creation-time bounds. `table` names a table in
|
||||
`namespace_path` (the root by default) and includes all its branches. Requests
|
||||
stay scoped to the connected database. Creation times are Unix milliseconds:
|
||||
`created_at_gte_millis` is inclusive and `created_at_lt_millis` is exclusive.
|
||||
Choose either `job_type` or `job_types`.
|
||||
|
||||
The `state` filter uses registry states: `in_progress`, `succeeded`, `failed`,
|
||||
`canceled`, and `timed_out`. These differ from the SDK lifecycle labels such
|
||||
as `running` and `finished` returned in `JobInfo.state`.
|
||||
|
||||
```python
|
||||
jobs = db.list_jobs(table="events", state="in_progress", page_limit=5)
|
||||
first_five = jobs[:5]
|
||||
for info in first_five:
|
||||
print(info.job_id, info.state)
|
||||
```
|
||||
|
||||
Synchronous indexing and slicing refer to the remaining results without
|
||||
consuming them. A bounded forward slice such as `jobs[:5]` fetches only enough
|
||||
pages to reach its stop. `len(jobs)` returns the remaining count by fetching
|
||||
and caching every remaining result. Negative indexes and open-ended or reverse
|
||||
slices also fetch and cache all remaining results. These operations can raise
|
||||
request errors; later iteration drains their cache. `AsyncListing` remains an
|
||||
async iterator: use `async for` to read it.
|
||||
|
||||
`Listing.num_page_results()` reports cached items available without another
|
||||
request, including items retained by indexing, slicing, or counting.
|
||||
`Listing.page_token()` reports the next request's token. Drain all cached
|
||||
items before saving that token, or resuming can skip them. Resume with the same
|
||||
filters, for example `db.list_jobs(table="events", state="in_progress",
|
||||
page_token=saved_token, page_limit=5)`. 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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -240,11 +295,12 @@ extract_frame_version = db.create_function_async(extract_frame).wait(
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
An empty byte string is a filled result. A scalar output cannot be nullable,
|
||||
because a physical NULL marks an unfilled computed row. To return a nullable
|
||||
blob as a value, use a named-struct output schema with a nullable blob field;
|
||||
the struct itself records whether the result has been filled. Read a nested
|
||||
blob with `table.fetch_blobs("payload.image", hits)`.
|
||||
An empty byte string is a filled result. A top-level Blob v2 output cannot be
|
||||
nullable; to return a nullable blob as a value, use a named-struct output
|
||||
schema with a nullable blob field. The struct itself records whether the
|
||||
result has been filled. A nullable non-Blob scalar output is declared with
|
||||
`Optional[T]` or `T | None`; see [Functions](/management/function#define).
|
||||
Read a nested blob with `table.fetch_blobs("payload.image", hits)`.
|
||||
|
||||
A list or large-list output may also contain Blob v2 elements; inputs and
|
||||
fixed-size lists do not support this layout. List-nested values are queryable
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
+3
-1
@@ -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"
|
||||
]
|
||||
},
|
||||
@@ -542,6 +543,7 @@
|
||||
"group": "SQL Reference",
|
||||
"pages": [
|
||||
"sql/index",
|
||||
"sql/pagination",
|
||||
"sql/data-types",
|
||||
{
|
||||
"group": "DDL",
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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>
|
||||
@@ -150,6 +238,93 @@ does not raise, which is what makes it safe in a loop; `wait()` raises
|
||||
A long backfill can therefore be started, left, and checked on from a different
|
||||
process.
|
||||
|
||||
{/*
|
||||
Draft for the Function freshness release. Keep this section hidden until the
|
||||
Enterprise status endpoint and its integration acceptance are deployed.
|
||||
|
||||
### Check Function column freshness {#freshness}
|
||||
|
||||
For a Function-backed column, the SDK can report how many live rows are
|
||||
`fresh`, `stale`, `never_computed`, or `failed` at the table version it
|
||||
reads. `wait_fresh`, `waitFresh`, and `wait_for_function_column` poll until no
|
||||
stale or never-computed rows remain. Rows that already failed stay in the
|
||||
returned status and do not keep the wait pending, so inspect `failed` after a
|
||||
successful wait:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
status = table.column_status("embedding")
|
||||
print(status.fresh, status.stale, status.never_computed, status.failed)
|
||||
|
||||
final_status = table.wait_fresh("embedding")
|
||||
print(final_status.failed)
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="typescript"
|
||||
const status = await table.functionColumnStatus("embedding");
|
||||
console.log(
|
||||
status.fresh,
|
||||
status.stale,
|
||||
status.neverComputed,
|
||||
status.failed,
|
||||
);
|
||||
|
||||
const finalStatus = await table.waitFresh("embedding");
|
||||
console.log(finalStatus.failed);
|
||||
```
|
||||
|
||||
```rust Rust icon="rust"
|
||||
let status = table.function_column_status("embedding").await?;
|
||||
println!(
|
||||
"{} {} {} {}",
|
||||
status.fresh, status.stale, status.never_computed, status.failed
|
||||
);
|
||||
|
||||
let final_status = table.wait_for_function_column("embedding", None).await?;
|
||||
println!("{}", final_status.failed);
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`auto_refresh.state` reports `queued` while the scheduler has accepted the
|
||||
refresh but a worker has not started it; `running` means execution has started.
|
||||
`last_refresh_job` describes the most recent attempt, including a cancellation
|
||||
or a failure. If a later attempt was cancelled, `last_failure_job` retains the
|
||||
most recent job that actually failed, so its nested `failure` continues to
|
||||
explain the failed rows.
|
||||
|
||||
These fields require a matching Agent, Query Node, and SDK deployment. An older
|
||||
client cannot decode the `queued` state, and an older server can omit the new
|
||||
optional failure fields.
|
||||
|
||||
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
|
||||
@@ -167,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:
|
||||
|
||||
@@ -219,6 +400,101 @@ for changing only the aggregate GPU budget. It cannot be combined with the
|
||||
complete resource budget. Omitting both preserves the server's existing
|
||||
defaults.
|
||||
|
||||
{/*
|
||||
Draft for the Function refresh control-plane resource release.
|
||||
|
||||
`resource_budget` above sizes the Function workers. Two independent options
|
||||
size the refresh control plane for a registered Function.
|
||||
`supervisor_resources` sets the CPU, memory and ephemeral-storage limits of
|
||||
the supervisor pod. `planning_workers` sets the resources of one planning
|
||||
worker and the sizing of the CPU-only planning fleet: `max_workers`,
|
||||
`rows_per_worker` and `fragments_per_worker`. Every field is required and
|
||||
must be positive. Omitting either option leaves the server's configured
|
||||
defaults unchanged, and either can be combined with `resource_budget`.
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
job = table.refresh_column_async(
|
||||
"embedding",
|
||||
supervisor_resources={
|
||||
"cpu_millis": 2_000,
|
||||
"memory_bytes": 4 * 1024**3,
|
||||
"ephemeral_storage_bytes": 10 * 1024**3,
|
||||
},
|
||||
planning_workers={
|
||||
"resources": {
|
||||
"cpu_millis": 1_000,
|
||||
"memory_bytes": 2 * 1024**3,
|
||||
"ephemeral_storage_bytes": 5 * 1024**3,
|
||||
},
|
||||
"max_workers": 4,
|
||||
"rows_per_worker": 100_000,
|
||||
"fragments_per_worker": 8,
|
||||
},
|
||||
)
|
||||
job.wait()
|
||||
```
|
||||
|
||||
```rust Rust icon="rust"
|
||||
use lancedb::table::{
|
||||
FunctionRefreshPlanningConfig,
|
||||
FunctionRefreshPodResources,
|
||||
RefreshColumnOptions,
|
||||
};
|
||||
|
||||
let _job = table
|
||||
.refresh_column_async_with_options(
|
||||
"embedding",
|
||||
RefreshColumnOptions::default()
|
||||
.supervisor_resources(
|
||||
FunctionRefreshPodResources::new(
|
||||
2_000,
|
||||
4 * 1024 * 1024 * 1024,
|
||||
10 * 1024 * 1024 * 1024,
|
||||
),
|
||||
)
|
||||
.planning_workers(
|
||||
FunctionRefreshPlanningConfig::new(
|
||||
FunctionRefreshPodResources::new(
|
||||
1_000,
|
||||
2 * 1024 * 1024 * 1024,
|
||||
5 * 1024 * 1024 * 1024,
|
||||
),
|
||||
4,
|
||||
100_000,
|
||||
8,
|
||||
),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="typescript"
|
||||
const job = await table.refreshColumnAsync("embedding", {
|
||||
supervisorResources: {
|
||||
cpuMillis: 2_000,
|
||||
memoryBytes: 4 * 1024 ** 3,
|
||||
ephemeralStorageBytes: 10 * 1024 ** 3,
|
||||
},
|
||||
planningWorkers: {
|
||||
resources: {
|
||||
cpuMillis: 1_000,
|
||||
memoryBytes: 2 * 1024 ** 3,
|
||||
ephemeralStorageBytes: 5 * 1024 ** 3,
|
||||
},
|
||||
maxWorkers: 4,
|
||||
rowsPerWorker: 100_000,
|
||||
fragmentsPerWorker: 8,
|
||||
},
|
||||
});
|
||||
await job.wait();
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
The SDK validates the shape and sends these values only with this explicit
|
||||
refresh request. A supporting LanceDB Enterprise server is required.
|
||||
*/}
|
||||
|
||||
These examples configure only the explicit refresh shown. A registered
|
||||
Function declaration can separately set `auto_refresh_resource_budget` on
|
||||
`add_columns`; that declaration controls the budget for its automatic
|
||||
@@ -276,6 +552,39 @@ from `lancedb.functions`. Use `FunctionRetryPolicy(max_attempts=1)` to
|
||||
disable user-error retries. Omitting the override preserves the registered
|
||||
policy.
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
from lancedb.functions import FunctionRetryPolicy
|
||||
|
||||
job = table.refresh_column_async(
|
||||
"embedding",
|
||||
retry_policy=FunctionRetryPolicy(transient=True, max_attempts=3),
|
||||
)
|
||||
job.wait()
|
||||
```
|
||||
|
||||
```rust Rust icon="rust"
|
||||
use lancedb::{function::FunctionRetryPolicy, table::RefreshColumnOptions};
|
||||
|
||||
let mut retry_policy = FunctionRetryPolicy::transient();
|
||||
retry_policy.max_attempts = 3;
|
||||
|
||||
let _job = table
|
||||
.refresh_column_async_with_options(
|
||||
"embedding",
|
||||
RefreshColumnOptions::default().retry_policy(retry_policy),
|
||||
)
|
||||
.await?;
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="typescript"
|
||||
const job = await table.refreshColumnAsync("embedding", {
|
||||
retryPolicy: { transient: true, maxAttempts: 3 },
|
||||
});
|
||||
await job.wait();
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
This requires a supporting LanceDB Enterprise server as well as an SDK
|
||||
that exposes these options. An older Function image may need
|
||||
re-registration before it accepts a refresh override. Only enable retries
|
||||
@@ -352,8 +661,8 @@ and `gpuCount` in the `refreshColumnAsync` options.
|
||||
</Note>
|
||||
|
||||
Completed Function outputs publish with their fragment by default. To opt into
|
||||
a row-count publication threshold, set `publication_interval_rows` in Python or
|
||||
`publication_interval_rows()` in Rust:
|
||||
a row-count publication threshold, set `publication_interval_rows` in Python,
|
||||
`publicationIntervalRows` in TypeScript, or `publication_interval_rows()` in Rust:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
@@ -364,6 +673,13 @@ job = table.refresh_column_async(
|
||||
job.wait()
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="square-js"
|
||||
const job = await table.refreshColumnAsync("embedding", {
|
||||
publicationIntervalRows: 60,
|
||||
});
|
||||
await job.wait();
|
||||
```
|
||||
|
||||
```rust Rust icon="rust"
|
||||
use lancedb::table::RefreshColumnOptions;
|
||||
|
||||
@@ -381,7 +697,9 @@ individual publication can differ from this value depending on completed work
|
||||
and Function batching; this is not an exact-N contract. Omit it to keep
|
||||
whole-fragment publication.
|
||||
|
||||
The TypeScript SDK does not expose the publication threshold option yet.
|
||||
In TypeScript, the threshold must be a positive safe integer, at most
|
||||
`Number.MAX_SAFE_INTEGER`. This option requires a supporting LanceDB Enterprise
|
||||
server and Function outputs without Blob types; Blob inputs are allowed.
|
||||
|
||||
The job APIs also take the row filter and failure handling of the SQL
|
||||
`REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed
|
||||
|
||||
+43
-114
@@ -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).
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -150,6 +150,11 @@ 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, both rows and IPC bytes count acknowledged parts.
|
||||
Both start at zero; a retried part is counted once, after acknowledgement.
|
||||
Scanning input or sending a rejected part does not advance these counts.
|
||||
Acknowledged parts are staged and do not imply a successful 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 +169,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 +199,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 +241,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">
|
||||
|
||||
@@ -221,6 +221,13 @@ and check inserted or deleted counts when the SDK returns them. Repeating a
|
||||
merge is only safe when its keys, conditions and update values produce the
|
||||
intended result on retry.
|
||||
|
||||
To override the transport retry budget for one merge, pass `retries=0` to
|
||||
Python's synchronous or asynchronous `builder.execute(data, retries=0)`, or
|
||||
use TypeScript's `builder.execute(data, { retries: 0 })`. The override applies
|
||||
only to that execution. A larger budget does not make an ambiguous 5xx result
|
||||
safe to replay. See [write retry boundaries](/ingestion/insert#performance)
|
||||
for the distinction between retryable failures and an unknown commit outcome.
|
||||
|
||||
### Embeddings and expression predicates {#advanced}
|
||||
|
||||
When a table uses an [embedding definition](/embedding), behavior depends on
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -13,8 +13,8 @@ import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompac
|
||||
Every write commits a new table version, and versions accumulate: small files
|
||||
from frequent appends, superseded files from updates and deletes, and rows added
|
||||
since an index was built. In the embedded library, `optimize()` addresses all
|
||||
three; a deployment handles them in the background and does not support
|
||||
`optimize()`.
|
||||
three. Enterprise handles maintenance in the background and also supports
|
||||
on-demand compaction through `optimize()` on compatible servers.
|
||||
|
||||
Run optimization as regular table maintenance, particularly after many small
|
||||
writes or a large ingest.
|
||||
|
||||
@@ -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)
|
||||
@@ -66,11 +66,118 @@ your process, without the database, so unit tests stay ordinary tests:
|
||||
|
||||
Where annotations cannot express the Arrow type precisely, pass `input_schema`
|
||||
and `output_schema` together: one without the other is rejected. A scalar
|
||||
output must be non-nullable, because a physical NULL is what marks a
|
||||
computed-column row as unfilled. A named-struct output may declare nullable
|
||||
fields: whether a row has a result at all is the struct's own validity, which
|
||||
Enterprise keeps in a separate internal column when it expands the result into
|
||||
sibling columns, so a null field is a value rather than a missing row.
|
||||
output is non-nullable by default. Annotate the return as `Optional[T]` or
|
||||
`T | None`, or pass a nullable output field, to declare a nullable scalar:
|
||||
|
||||
```python
|
||||
import pyarrow as pa
|
||||
|
||||
from lancedb import function
|
||||
|
||||
|
||||
@function(
|
||||
input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
|
||||
output_schema=pa.field("result", pa.int64(), nullable=True),
|
||||
)
|
||||
def maybe_double(value: int) -> int | None:
|
||||
return None if value == 0 else value * 2
|
||||
```
|
||||
|
||||
The signature sent in the registration request then carries the nullable
|
||||
scalar:
|
||||
|
||||
```json
|
||||
{
|
||||
"inputs": [{"name": "value", "arrow_type": "int64", "nullable": false}],
|
||||
"output": {"kind": "scalar", "arrow_type": "int64", "nullable": true}
|
||||
}
|
||||
```
|
||||
|
||||
<Note>
|
||||
Nullable scalar outputs require an Enterprise server that supports them;
|
||||
older servers reject the registration. On a supporting server, a computed
|
||||
`NULL` counts as a filled result, independently of its stored value.
|
||||
</Note>
|
||||
|
||||
A named-struct output may declare nullable fields: whether a row has a result
|
||||
at all is the struct's own validity, which Enterprise keeps in a separate
|
||||
internal column when it expands the result into sibling columns, so a null
|
||||
field is a value rather than a missing row.
|
||||
|
||||
### Timestamps and durations {#timestamps-durations}
|
||||
|
||||
Bare `datetime` keeps its existing `timestamp[us]` default without a timezone.
|
||||
For any other unit or a timezone, declare the Arrow type explicitly:
|
||||
|
||||
```python
|
||||
from datetime import datetime
|
||||
from typing import Annotated
|
||||
|
||||
import pyarrow as pa
|
||||
|
||||
|
||||
@function
|
||||
def normalize(
|
||||
ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")],
|
||||
) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]:
|
||||
...
|
||||
```
|
||||
|
||||
`pa.timestamp` accepts `s`, `ms`, `us`, and `ns`, and a timezone such as
|
||||
`UTC`, `America/New_York`, or `+08:00`. The canonical signature uses
|
||||
`{"type":"timestamp:<unit>:<timezone>"}`, with `-` for no timezone; the
|
||||
microsecond/no-timezone case keeps the legacy `{"type":"timestamp"}` shape.
|
||||
A timezone string of `-` is reserved for "no timezone" and is rejected.
|
||||
|
||||
`pa.duration` accepts the same four units and uses
|
||||
`{"type":"duration:<unit>"}`; the microsecond case keeps the legacy
|
||||
`{"type":"duration"}` shape. A bare `timedelta` has no unit and is rejected;
|
||||
use `Annotated[timedelta, pa.duration("s")]` or an explicit schema.
|
||||
|
||||
Other units are never downgraded to microseconds. A reader that predates the
|
||||
compound temporal representation cannot read those signatures. A deployment
|
||||
must include the corresponding Lance Namespace and Sophon support; this
|
||||
client-side declaration does not add server support.
|
||||
|
||||
### Maps and decimals {#maps-decimals}
|
||||
|
||||
A `dict[str, T]` annotation declares an Arrow map with a non-nullable `utf8`
|
||||
key. A plain `T` value is non-nullable; annotate `dict[str, Optional[T]]` for
|
||||
nullable values. An explicit `pa.map_(...)` schema preserves the value field's
|
||||
own `nullable` flag:
|
||||
|
||||
```python
|
||||
@function
|
||||
def word_counts(text: str) -> dict[str, int]:
|
||||
...
|
||||
```
|
||||
|
||||
Map keys must be non-nullable `utf8`; `keys_sorted=True` is not supported, and
|
||||
Blob v2 values inside a map are not supported.
|
||||
|
||||
`Decimal` carries no precision or scale by itself, so a bare `Decimal`
|
||||
annotation is rejected. Declare both explicitly with `Annotated`, or use an
|
||||
explicit Arrow schema:
|
||||
|
||||
```python
|
||||
from decimal import Decimal
|
||||
from typing import Annotated
|
||||
|
||||
import pyarrow as pa
|
||||
|
||||
|
||||
@function
|
||||
def add_tax(
|
||||
amount: Annotated[Decimal, pa.decimal128(12, 2)],
|
||||
) -> Annotated[Decimal, pa.decimal128(12, 2)]:
|
||||
...
|
||||
```
|
||||
|
||||
`decimal128` and `decimal256` keep the declared precision and scale in the
|
||||
canonical signature; no default is chosen. Map and decimal signatures are sent
|
||||
as canonical Arrow JSON. A deployment must support those types; an older
|
||||
Enterprise server may reject the registration, and this client-side
|
||||
declaration does not add server support.
|
||||
|
||||
## Connect and create a table {#table}
|
||||
|
||||
@@ -111,6 +218,26 @@ 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.
|
||||
|
||||
Re-registering unchanged code reuses the published version and its resolved
|
||||
environment lock. Pass `refresh_lock=True` to `create_function` or
|
||||
`create_function_async` to request a fresh lock for this registration. It is a
|
||||
registration action, not part of the Function's source or runtime identity.
|
||||
A deployment must support the field; an older server rejects the unknown
|
||||
field rather than silently reusing the old lock.
|
||||
|
||||
{/* 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
|
||||
@@ -153,7 +280,9 @@ let latest = connection.get_function_latest("double", &[]).await?;
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW FUNCTIONS
|
||||
SHOW FUNCTIONS IN "analytics" WITH (name = 'double', limit = 100)
|
||||
SHOW FUNCTIONS IN "analytics" LIMIT 100
|
||||
SHOW FUNCTIONS HISTORY IN "analytics" LIMIT 100
|
||||
SHOW FUNCTIONS HISTORY IN "analytics" LIMIT 100 FROM '<page-token>'
|
||||
|
||||
DESCRIBE FUNCTION double WITH (version = '1')
|
||||
DESCRIBE FUNCTION double
|
||||
@@ -166,6 +295,117 @@ are not included; list each namespace separately. A version's
|
||||
`created_at_millis`, `metadata`, `disabled` flag, and `secret_bindings` are
|
||||
all readable this way without applying or calling the function.
|
||||
|
||||
### Inspect the resolved environment {#resolved-environment}
|
||||
|
||||
The version keeps the requested runtime separate from what the server actually
|
||||
installed. The typed catalog API is available in Python and Rust; TypeScript
|
||||
does not yet expose this readback API. `version.runtime` is the specification
|
||||
sent at registration. `version.resolved_environment` is measured data from the
|
||||
built image:
|
||||
|
||||
<CodeGroup>
|
||||
```python
|
||||
version = db.get_function("double")
|
||||
print(version.runtime) # requested runtime, or None for legacy
|
||||
print(version.environment.resolved) # measured environment, or None for legacy
|
||||
print(version.environment_report) # platform -> measured environment map
|
||||
|
||||
if version.environment.resolved is not None:
|
||||
for package in version.environment.resolved.packages:
|
||||
print(package.name, package.version) # versions keep labels such as +cu130
|
||||
```
|
||||
|
||||
{/* Draft for the typed Rust environment inspection release.
|
||||
```rust
|
||||
# async fn inspect_environment(connection: &lancedb::Connection) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let version = connection.get_function_latest("double", &[]).await?;
|
||||
println!("Requested runtime: {:?}", version.runtime());
|
||||
|
||||
if let Some(environment) = version.resolved_environment() {
|
||||
for package in &environment.packages {
|
||||
println!("{} {}", package.name, package.version);
|
||||
}
|
||||
}
|
||||
|
||||
for (platform, environment) in version.resolved_environments() {
|
||||
println!("{platform}: {} measured packages", environment.packages.len());
|
||||
for package in &environment.packages {
|
||||
println!("{} {}", package.name, package.version);
|
||||
}
|
||||
}
|
||||
# Ok(())
|
||||
# }
|
||||
```
|
||||
*/}
|
||||
</CodeGroup>
|
||||
|
||||
`version.environment.requested` and `version.environment.resolved` are
|
||||
convenience members over the same canonical fields; they do not add another
|
||||
wire shape. The canonical JSON exposes top-level `runtime` and
|
||||
`resolved_environment`. A missing `resolved_environment` means the version or
|
||||
environment cache predates measurement; it is unknown, not an empty installed
|
||||
package list. A package's `source` is present only when the submitted lock
|
||||
retained it, and provenance fields are reported without client-side guessing.
|
||||
|
||||
For a multiarchitecture image, the scalar field is absent and
|
||||
`version.resolved_environments` (also available as
|
||||
`version.environment_report`) maps OCI `os/architecture` keys to the measured
|
||||
environment for that platform. A missing platform key means its measurement is
|
||||
unknown; an empty `packages` list inside a key is a measured empty environment
|
||||
and is retained. The SDK never merges platforms or fabricates an aggregate
|
||||
package list.
|
||||
|
||||
The corresponding canonical payload has this shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"runtime": {
|
||||
"kind": "python",
|
||||
"python_version": "3.12",
|
||||
"environment": {"kind": "pip", "packages": ["vllm==0.11.0"]}
|
||||
},
|
||||
"resolved_environment": {
|
||||
"packages": [
|
||||
{
|
||||
"name": "torch",
|
||||
"version": "2.9.0+cu130",
|
||||
"source": "https://packages.example/simple"
|
||||
}
|
||||
],
|
||||
"provenance": {
|
||||
"configured_index_urls": ["https://packages.example/simple"],
|
||||
"resolved_indexes": ["https://packages.example/simple"],
|
||||
"cuda_toolkit": "12.8",
|
||||
"torch_version": "torch==2.9.0+cu130"
|
||||
},
|
||||
"warnings": [
|
||||
"torch resolved to torch==2.9.0+cu130 but is not pinned exactly; add torch==2.9.0+cu130 to pin it."
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The multiarchitecture form has the same package shape per platform:
|
||||
|
||||
```json
|
||||
{
|
||||
"resolved_environments": {
|
||||
"linux/amd64": {
|
||||
"packages": [{"name": "torch", "version": "2.9.0+cu130"}]
|
||||
},
|
||||
"linux/arm64": {
|
||||
"packages": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Environment warnings are part of the registration result. Waiting on
|
||||
`create_function_async(...)` (or calling `create_function`) emits each server
|
||||
warning from the scalar or per-platform measurements as a Python `UserWarning`;
|
||||
`get_function` and `list_functions` read the same version but do not
|
||||
replay those registration warnings.
|
||||
|
||||
## Try it in SQL {#try-sql}
|
||||
|
||||
A registered function is callable in SQL by its name, the same as any other
|
||||
@@ -200,6 +440,52 @@ function application keeps its scalar or named-struct result in the named
|
||||
column. A bare named-struct application expands its result fields as one atomic
|
||||
binding, with aliases from `rename(columns=...)`.
|
||||
|
||||
{/* Draft for the Function literal binding release.
|
||||
|
||||
### Bind a constant input {#literal-inputs}
|
||||
|
||||
<Note>
|
||||
Literal inputs require an SDK that supports binding metadata version 2 and an
|
||||
Enterprise deployment with matching literal declaration and execution support.
|
||||
Upgrading the SDK alone does not enable this server capability. Older clients
|
||||
reject version 2 bindings; column-only bindings continue to use version 1.
|
||||
</Note>
|
||||
|
||||
Use `lit(...)` to pass the same value for every row while another parameter
|
||||
reads a column. For example, using the table above:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
from lancedb import col, function, lit
|
||||
|
||||
|
||||
@function
|
||||
def multiply(value: float, factor: int) -> float:
|
||||
return value * factor
|
||||
|
||||
|
||||
multiplier = db.create_function_async(multiply).wait()
|
||||
table.add_columns(
|
||||
{"scaled": multiplier(value=col("value"), factor=lit(16))},
|
||||
auto_refresh_enabled=False,
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Supported scalar constants are booleans, strings, integers from `-(2**63)`
|
||||
through `2**64 - 1`, and `None` for a nullable parameter. Each value must match
|
||||
the parameter's declared type. Floating-point, binary, date, datetime and
|
||||
decimal constants are not supported in Function input bindings, even though
|
||||
`lit(...)` accepts them in other SQL expressions. Bind a direct literal;
|
||||
expressions such as `lit(16) + lit(8)` are not supported here.
|
||||
|
||||
The constant belongs to the column binding, so the Function version and its
|
||||
image stay the same. Only column inputs contribute table dependencies. Refresh
|
||||
`scaled` to fill it. To change the constant to `lit(8)`, drop and redeclare the
|
||||
column using the same `multiplier` version; the new binding needs a refresh.
|
||||
|
||||
*/}
|
||||
|
||||
### Bind more than one input, or fill more than one column {#multi}
|
||||
|
||||
Parameters bind by name, so a function that takes several arguments binds
|
||||
@@ -407,6 +693,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 +771,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 +829,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}
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@ enables them; the SDK methods send the view's SQL query to the deployment. See
|
||||
| --- | --- | --- | --- |
|
||||
| create | `create_function`, `create_function_async` | -- | `CREATE FUNCTION` |
|
||||
| get | `get_function` | -- | `DESCRIBE FUNCTION` |
|
||||
| list | `list_functions` | -- | `SHOW FUNCTIONS` |
|
||||
| list | `list_functions` | -- | `SHOW FUNCTIONS HISTORY` |
|
||||
| drop | `drop_function` | -- | `DROP FUNCTION` |
|
||||
|
||||
<Badge color="red">Enterprise</Badge> A function runs on the server, and only on
|
||||
|
||||
@@ -201,7 +201,7 @@ setting. See [Limits](/basics/limits#schema).
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
tbl = db.open_table("documents")
|
||||
db.table_names()
|
||||
names = list(db.list_tables())
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="square-js"
|
||||
@@ -230,6 +230,27 @@ listing. A missing table raises `ValueError` on a local directory and
|
||||
A listing returns one page of names at a time, so check every page. TypeScript
|
||||
has no `tableExists`.
|
||||
|
||||
{/*
|
||||
Draft for the table-existence lookup release (#4974). Once released, replace
|
||||
the two table-existence paragraphs above with this guidance:
|
||||
|
||||
For Python local, remote, and namespace connections, use
|
||||
`db.table_exists(["documents"])` or `"documents" in db` to check whether a root
|
||||
table exists. For an async connection, use
|
||||
`await db.table_exists(["documents"])`. Include namespace segments before the
|
||||
table name, for example `["analytics", "documents"]`. These checks return
|
||||
`False` when the table is missing and propagate other errors, including
|
||||
permission errors. They look up the table directly, regardless of the number
|
||||
of tables in the database.
|
||||
|
||||
When migrating from `name in db.table_names()`, use `name in db` or
|
||||
`db.table_exists([name])`. To collect every table name, use
|
||||
`list(db.list_tables())`, or `[name async for name in db.list_tables()]` on an
|
||||
async connection. The `.tables` attribute holds only one page (100 names by
|
||||
default), so membership checks against it can miss existing tables. TypeScript
|
||||
has no `tableExists`.
|
||||
*/}
|
||||
|
||||
## Rename and clone tables {#rename-clone}
|
||||
|
||||
<CodeGroup>
|
||||
@@ -249,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
|
||||
@@ -354,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).
|
||||
|
||||
@@ -479,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. |
|
||||
|
||||
@@ -524,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
|
||||
@@ -558,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`,
|
||||
@@ -595,6 +720,25 @@ table changes while the query runs, the query runs again, up to three times:
|
||||
</CodeBlock>
|
||||
</CodeGroup>
|
||||
|
||||
{/* Draft for the Enterprise TypeScript bytes release. Replace the retry guidance above only after SDK and serving-node rollout.
|
||||
|
||||
Local queries retry up to three times if the table changes while they run.
|
||||
Remote queries instead bind payload fetches to the version and immutable
|
||||
snapshot identity from the executed query response. They do not rerun the query
|
||||
against a newer version to recover missing payloads. Both `toArray()` and
|
||||
`toArrow()` discover Blob fields from that response, including fields added
|
||||
after the table handle was opened.
|
||||
|
||||
Every serving node must support `x-lancedb-query-version` and
|
||||
`x-lancedb-query-snapshot`, enforce the requested identity when fetching bytes,
|
||||
and echo it in the fetch response. Proxies must forward these headers. Missing
|
||||
or mismatched provenance fails explicitly; use `blobMode: "descriptions"` until
|
||||
the rollout is complete. Keep queried versions available for deferred reads:
|
||||
snapshot identities do not prevent version deletion. Dropping and recreating a
|
||||
table cannot substitute the replacement's bytes, even if its version is reused.
|
||||
Hybrid byte queries require matching snapshot provenance from both responses.
|
||||
*/}
|
||||
|
||||
#### Read blobs on demand {#multimodal-read-blobs}
|
||||
|
||||
Query the rows you want and pass their `_rowid` values to a fetch method.
|
||||
@@ -623,6 +767,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
|
||||
@@ -646,6 +794,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
|
||||
@@ -657,6 +820,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>
|
||||
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -57,15 +57,21 @@ properties and requires system `USAGE`.
|
||||
|
||||
## SHOW DATABASES {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW DATABASES
|
||||
```sql
|
||||
SHOW DATABASES LIMIT 100;
|
||||
SHOW DATABASES LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Returns a sorted `name` column containing the databases the caller has
|
||||
`USAGE` on, including `system` when permitted. `LIKE` and `WHERE` filters
|
||||
are unsupported.
|
||||
Returns one non-null `name` column, sorted by database name and filtered to
|
||||
databases the caller has `USAGE` on, including `system` when permitted.
|
||||
Databases are above namespaces, so this command does not accept `IN` or
|
||||
return a `namespace_path` column.
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## ATTACH DATABASE {#attach}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -126,20 +135,33 @@ from it.
|
||||
|
||||
## SHOW FUNCTIONS {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW FUNCTIONS
|
||||
SHOW FUNCTIONS HISTORY IN "analytics" WITH (name = 'embed', limit = 100)
|
||||
SHOW FUNCTIONS HISTORY WITH (after_name = 'embed', after_version = '1', limit = 100)
|
||||
```sql
|
||||
SHOW FUNCTIONS IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW FUNCTIONS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`SHOW FUNCTIONS` returns the highest published numeric revision for each name.
|
||||
Add `HISTORY` to list every published revision, as Python's `list_functions()`
|
||||
does. Rows are ordered by name and numeric revision, so `2` comes before `10`.
|
||||
`after_name` and `after_version` must be supplied together for keyset pagination.
|
||||
`limit` bounds
|
||||
the response; `include_definition = false` omits the optional definition JSON.
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
`SHOW FUNCTIONS` lists each function once. Add `HISTORY` to list every
|
||||
published revision with its metadata and definition, as `list_functions()`
|
||||
does. History uses the same pagination suffix; numeric revision order is
|
||||
encoded in the token, so revision `2` precedes `10`.
|
||||
|
||||
```sql
|
||||
SHOW FUNCTIONS HISTORY IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW FUNCTIONS HISTORY IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## DROP FUNCTION {#drop}
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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).
|
||||
@@ -60,16 +70,25 @@ automatic execution needs the same server-side switch enabled. Omitting
|
||||
|
||||
## SHOW MATERIALIZED VIEWS {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW MATERIALIZED VIEWS
|
||||
```sql
|
||||
SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
<Note>
|
||||
This asks the server for its views, as the SDK's `list_materialized_views` does
|
||||
on a `db://` connection.
|
||||
</Note>
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
The listing contains identifiers; use `DESCRIBE MATERIALIZED VIEW` for its defining query and refresh metadata.
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## Refreshing one {#refresh}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ backtick-quoted identifier with `$` between components, such as
|
||||
one path component, relative to an explicit parent schema or the session's
|
||||
current schema -- it cannot contain `$` or be qualified with a database.
|
||||
|
||||
`SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete
|
||||
For single-object commands, `SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete
|
||||
schema identifier. Names are lowercased unless quoted.
|
||||
|
||||
## CREATE SCHEMA and CREATE NAMESPACE {#create}
|
||||
@@ -126,27 +126,30 @@ Requires `USAGE` on the database and the namespace.
|
||||
|
||||
## SHOW SCHEMAS and SHOW NAMESPACES {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW SCHEMAS
|
||||
SHOW NAMESPACES
|
||||
SHOW NAMESPACES IN analytics.team
|
||||
```sql
|
||||
SHOW SCHEMAS LIMIT 100;
|
||||
SHOW SCHEMAS LIMIT 100 FROM '<page-token>';
|
||||
SHOW NAMESPACES IN analytics.team LIMIT 100;
|
||||
SHOW NAMESPACES IN analytics.team LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`SHOW SCHEMAS` returns complete paths in the current database, recursively,
|
||||
including `public` when the caller can use it. It does not accept `IN`.
|
||||
Both commands return two non-null string columns: `namespace_path`, the
|
||||
parent path as a compact JSON array, and `name`, the unqualified child name.
|
||||
Results are ordered by parent path components, then name, and omit namespaces
|
||||
the caller cannot use.
|
||||
|
||||
`SHOW NAMESPACES` lists only immediate child names under the session's
|
||||
current schema. `IN` selects a different parent schema, optionally in
|
||||
another database -- use `IN public` for the current database's root, or
|
||||
`IN analytics.public` for another database's root. A missing parent is an
|
||||
error.
|
||||
`SHOW SCHEMAS` and `SHOW NAMESPACES` are equivalent listings. Without `IN`,
|
||||
both list recursively in the current database, include the implicit `public`
|
||||
root, and ignore the session namespace. With `IN`, both list immediate children
|
||||
of the selected parent. A schema path can appear directly: `IN team$features`;
|
||||
a database qualifier is optional. `IN public` selects the current database root,
|
||||
and `IN analytics.public` selects another database's root.
|
||||
|
||||
Both forms return a sorted `name` column and omit namespaces the caller
|
||||
cannot use. Large listings that exceed 10,000 namespaces, or recursive
|
||||
listings deeper than 32 levels, return an error suggesting a narrower
|
||||
listing.
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## DROP SCHEMA and DROP NAMESPACE {#drop}
|
||||
|
||||
@@ -187,7 +190,6 @@ with `IF EXISTS`. Inspect a cascade drop's child jobs with
|
||||
| `CREATE SCHEMA child IN parent` | `CREATE NAMESPACE child IN parent` or `` CREATE SCHEMA `parent$child` `` |
|
||||
| `` DESCRIBE NAMESPACE `parent$child` `` | `` DESCRIBE SCHEMA `parent$child` `` or `DESCRIBE NAMESPACE child IN parent` |
|
||||
| `DROP NAMESPACE analytics.child` | `DROP NAMESPACE child IN analytics.public` |
|
||||
| `SHOW SCHEMAS IN parent` | `SHOW NAMESPACES IN parent` |
|
||||
|
||||
## What to read next {#next}
|
||||
|
||||
|
||||
+17
-13
@@ -98,21 +98,25 @@ picked up by every Function still bound to that name.
|
||||
|
||||
## SHOW SECRETS {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW SECRETS
|
||||
SHOW SECRETS IN platform
|
||||
SHOW SECRETS IN analytics.`ml$vision`
|
||||
SHOW SECRETS IN public
|
||||
SHOW SECRETS IN platform WHERE name > 'model-api-key' LIMIT 50
|
||||
```sql
|
||||
SHOW SECRETS IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW SECRETS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Lists the Secret names in one namespace as a sorted `name` column. Without
|
||||
`IN`, it lists the session's namespace; `IN public` lists the root. `WHERE
|
||||
name > '<cursor>'` pages past the last name already seen, and `LIMIT`
|
||||
bounds the page size; `WHERE` must compare `name` with `>`. Requires
|
||||
`USAGE` on the database and the namespace.
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
Secret listings contain no values or Secret metadata.
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## DESCRIBE SECRET {#describe}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -184,16 +194,25 @@ only the reference naming it.
|
||||
|
||||
## SHOW STORAGE INTEGRATIONS {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW STORAGE INTEGRATIONS
|
||||
SHOW STORAGE INTEGRATIONS IN platform
|
||||
LIST STORAGE INTEGRATIONS
|
||||
```sql
|
||||
SHOW STORAGE INTEGRATIONS IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW STORAGE INTEGRATIONS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`LIST` is an alias for `SHOW` here. Returns one `name` column; `IN`
|
||||
narrows the listing to one namespace.
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
`LIST STORAGE INTEGRATIONS` is an exact alias, including pagination.
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## DROP STORAGE INTEGRATION {#drop}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -258,3 +268,23 @@ deployment stores its catalog. See
|
||||
Renaming, retyping and dropping columns from the SDK.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## SHOW TABLES {#show}
|
||||
|
||||
```sql
|
||||
SHOW TABLES IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW TABLES IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
+23
-20
@@ -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
|
||||
@@ -71,29 +81,22 @@ was none to begin with.
|
||||
## Listing {#listing}
|
||||
|
||||
```sql
|
||||
SHOW VIEWS
|
||||
SHOW VIEWS IN "analytics" WHERE name > 'previous_view' LIMIT 100
|
||||
SHOW VIEWS IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW VIEWS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
|
||||
`SHOW VIEWS` returns ascending `name` values. The `name` cursor is scoped to
|
||||
the selected namespace.
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
Object commands retain their small results in shared storage even when general
|
||||
query-result copying is disabled, so asynchronous polling can use any query node.
|
||||
|
||||
Views and tables share a namespace, and both are things you can query. The
|
||||
catalog distinguishes them:
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| view names | the views in the database |
|
||||
| table names | the tables |
|
||||
| relation names | everything queryable (both) |
|
||||
|
||||
Use the relation listing when the question is "what can I select from," and the
|
||||
separate listings when the distinction matters: before dropping, for
|
||||
instance, since dropping a view removes only the saved query while dropping a
|
||||
table removes data.
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## Choosing between a view and a materialized view {#choosing}
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
title: "Catalog listing pagination"
|
||||
description: "Use one continuation-token syntax for SQL catalog listings."
|
||||
---
|
||||
|
||||
Catalog `SHOW` statements share one pagination suffix:
|
||||
|
||||
```sql
|
||||
SHOW <objects> [IN <scope>] [LIMIT <count> [FROM '<page-token>']];
|
||||
```
|
||||
|
||||
This applies to tables, views, materialized views, functions and function
|
||||
history, secrets, storage integrations, namespaces/schemas, and databases.
|
||||
|
||||
```sql
|
||||
SHOW TABLES LIMIT 100;
|
||||
SHOW TABLES IN team$ml LIMIT 100;
|
||||
SHOW TABLES IN team$ml LIMIT 100 FROM '<page-token>';
|
||||
SHOW TABLES IN analytics.team$ml LIMIT 100;
|
||||
SHOW DATABASES LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
|
||||
## Namespace scope
|
||||
|
||||
`IN` is optional. Without it, listings include root and every authorized
|
||||
namespace in the current database, regardless of the session's default namespace.
|
||||
With `IN`, objects are listed only in that exact namespace. The scope accepts a
|
||||
schema directly: `IN team$ml` means the absolute namespace path `["team", "ml"]`
|
||||
in the current database. Use `IN public` for root, or `IN other_db.team$ml` to
|
||||
select a different database. Quote schema identifiers containing punctuation or
|
||||
mixed case, for example `IN "Team$ML"`.
|
||||
|
||||
`SHOW SCHEMAS` and `SHOW NAMESPACES` use the same rules: without `IN` they
|
||||
include all namespace paths and the public root; with `IN` they list the
|
||||
selected parent's immediate children. `SHOW DATABASES` remains global and
|
||||
does not accept `IN`.
|
||||
|
||||
SDK APIs that take a namespace send an explicit `IN` clause and continue to
|
||||
list that one namespace.
|
||||
|
||||
## Continuation metadata
|
||||
|
||||
The Arrow result schema carries `lancedb.next_page_token` when more results
|
||||
remain. Pass that opaque value unchanged in `FROM` on the next request.
|
||||
The token identifies the object type, database, namespace scope, and complete
|
||||
position, including namespace path and any numeric revision. It cannot be
|
||||
reused with another object type or scope.
|
||||
|
||||
The token is metadata, not an additional result column or a synthetic row.
|
||||
Namespace-scoped object listings contain `namespace_path` and `name`;
|
||||
databases contain only `name`. Function history retains revision metadata.
|
||||
SDK listing APIs expose this server-issued value as the page's `page_token`.
|
||||
|
||||
Continue until no token is returned. A short or empty page may still have a
|
||||
token. Pages observe the live catalog; continuation does not create a snapshot.
|
||||
|
||||
## Page size and ordering
|
||||
|
||||
The default page limit is 1,000, with a maximum of 10,000. `LIMIT 0` returns
|
||||
no rows. Object catalogs order identifiers by namespace path components and
|
||||
unqualified name; database names are ordered by name. Table page boundaries
|
||||
follow native catalog order, which may differ from logical name order for
|
||||
directory-backed tables; table names are sorted within each returned page. Function history uses
|
||||
numeric revision order within each name. The token preserves that complete
|
||||
position, including when names repeat in different namespaces.
|
||||
|
||||
The old name-comparison `WHERE` and Function `WITH` pagination forms are no
|
||||
longer supported. Use the same `LIMIT ... FROM ...` suffix for every listing.
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<parent>
|
||||
<groupId>com.lancedb</groupId>
|
||||
<artifactId>lancedb-parent</artifactId>
|
||||
<version>0.42.0-beta.10</version>
|
||||
<version>0.42.0-beta.16</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
+11
-2
@@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>com.lancedb</groupId>
|
||||
<artifactId>lancedb-parent</artifactId>
|
||||
<version>0.42.0-beta.10</version>
|
||||
<version>0.42.0-beta.16</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.16</lance-core.version>
|
||||
<lance-core.version>15.0.0-beta.22</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
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "lancedb-nodejs"
|
||||
edition.workspace = true
|
||||
version = "0.42.0-beta.10"
|
||||
version = "0.42.0-beta.16"
|
||||
publish = false
|
||||
license.workspace = true
|
||||
description.workspace = true
|
||||
|
||||
@@ -0,0 +1,644 @@
|
||||
// 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?: (response: http.ServerResponse) => void,
|
||||
) {
|
||||
let takes = 0;
|
||||
let rangeReads = 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",
|
||||
});
|
||||
if (fault === "stall-read" && ++rangeReads === 1) {
|
||||
// Withhold the rest of the body so native completion cannot win the abort.
|
||||
res.write(bytes.subarray(0, 1));
|
||||
onStall?.(res);
|
||||
return;
|
||||
}
|
||||
res.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?.(res);
|
||||
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 an in-flight BlobFile read and leaves the handle usable", async () => {
|
||||
let responseTimedOut = false;
|
||||
let markStalled!: () => void;
|
||||
const stalled = new Promise<void>((resolve) => {
|
||||
markStalled = resolve;
|
||||
});
|
||||
let markDisconnected!: () => void;
|
||||
const disconnected = new Promise<void>((resolve) => {
|
||||
markDisconnected = resolve;
|
||||
});
|
||||
await withRangeServer(
|
||||
async (db) => {
|
||||
const table = await open(db, 3);
|
||||
const [handle] = await table.fetchBlobFiles("image", [10n]);
|
||||
const controller = new AbortController();
|
||||
try {
|
||||
const pending = handle!.readRange(0n, handle!.size(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
const rejected = expect(pending).rejects.toMatchObject({
|
||||
name: "AbortError",
|
||||
});
|
||||
await stalled;
|
||||
controller.abort();
|
||||
await rejected;
|
||||
await disconnected;
|
||||
expect(responseTimedOut).toBe(false);
|
||||
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
|
||||
expect(handle!.isClosed()).toBe(false);
|
||||
expect(await handle!.tell()).toBe(0n);
|
||||
// The single request permit must also be released by cancellation.
|
||||
expect(await handle!.readRange(0n, 5n)).toEqual(Buffer.from("alpha"));
|
||||
} finally {
|
||||
controller.abort();
|
||||
await handle!.close();
|
||||
}
|
||||
},
|
||||
"stall-read",
|
||||
null,
|
||||
(response) => {
|
||||
response.once("timeout", () => {
|
||||
responseTimedOut = true;
|
||||
});
|
||||
response.once("close", markDisconnected);
|
||||
markStalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
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")}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
+520
-10
@@ -483,6 +483,222 @@ 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.each(
|
||||
[409, 429, 502, 503, 504].flatMap((status) =>
|
||||
[undefined, 0, 2].flatMap((retries) =>
|
||||
[[], ["analytics", "features"]].map((namespacePath) => ({
|
||||
status,
|
||||
retries,
|
||||
namespacePath,
|
||||
})),
|
||||
),
|
||||
),
|
||||
)("applies per-call merge retries: %j", async (scenario) => {
|
||||
let attempts = 0;
|
||||
const identifier = [...scenario.namespacePath, "items"].join("$");
|
||||
const succeeds =
|
||||
[409, 429].includes(scenario.status) && scenario.retries !== 0;
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
const url = new URL(req.url ?? "", "http://localhost");
|
||||
if (url.pathname === `/v1/table/${identifier}/describe/`) {
|
||||
res.writeHead(200).end(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
schema: {
|
||||
fields: [
|
||||
{ name: "id", type: { type: "int64" }, nullable: true },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
req.on("data", (chunk) => chunks.push(chunk));
|
||||
req.on("end", () => {
|
||||
try {
|
||||
expect(url.pathname).toBe(`/v1/table/${identifier}/merge_insert/`);
|
||||
expect(url.searchParams.get("use_index")).toBe("false");
|
||||
expect(req.headers["x-request-timeout-ms"]).toBe("10000");
|
||||
// Rust compresses the batches; Arrow JS can inspect the schema without a codec.
|
||||
const reader = RecordBatchReader.from(Buffer.concat(chunks)).open();
|
||||
expect(reader.schema.fields.map((field) => field.name)).toEqual([
|
||||
"id",
|
||||
]);
|
||||
} finally {
|
||||
attempts++;
|
||||
res
|
||||
.writeHead(attempts === 1 ? scenario.status : 200)
|
||||
.end('{"version":2}');
|
||||
}
|
||||
});
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("items", scenario.namespacePath);
|
||||
const merge = table
|
||||
.mergeInsert("id")
|
||||
.whenNotMatchedInsertAll()
|
||||
.useIndex(false);
|
||||
const result = merge.execute([{ id: 1n }], {
|
||||
timeoutMs: 10_000,
|
||||
retries: scenario.retries,
|
||||
});
|
||||
if (succeeds) {
|
||||
await expect(result).resolves.toMatchObject({ version: 2 });
|
||||
} else {
|
||||
await expect(result).rejects.toThrow();
|
||||
}
|
||||
},
|
||||
{
|
||||
clientConfig: {
|
||||
retryConfig: {
|
||||
retries: 3,
|
||||
statuses: [409, 429, 502, 503, 504],
|
||||
backoffFactor: 0,
|
||||
backoffJitter: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(attempts).toBe(succeeds ? 2 : 1);
|
||||
});
|
||||
|
||||
it("isolates merge retry overrides across reused builders and reads", async () => {
|
||||
let attempts = 0;
|
||||
let readAttempts = 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;
|
||||
}
|
||||
req.resume();
|
||||
req.on("end", () => {
|
||||
if (req.url?.endsWith("/count_rows/")) {
|
||||
readAttempts++;
|
||||
res.writeHead(readAttempts % 2 ? 429 : 200).end("1");
|
||||
} else {
|
||||
attempts++;
|
||||
res
|
||||
.writeHead([1, 2, 4, 6].includes(attempts) ? 429 : 200)
|
||||
.end('{"version":2}');
|
||||
expect(req.url).toContain("/merge_insert/");
|
||||
}
|
||||
});
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("items");
|
||||
const merge = table.mergeInsert("id").whenNotMatchedInsertAll();
|
||||
for (const retries of [
|
||||
-1,
|
||||
256,
|
||||
1.5,
|
||||
Number.NaN,
|
||||
Number.POSITIVE_INFINITY,
|
||||
]) {
|
||||
await expect(
|
||||
merge.execute([{ id: 1n }], { retries }),
|
||||
).rejects.toThrow("retries must be an integer between 0 and 255");
|
||||
}
|
||||
expect(attempts).toBe(0);
|
||||
await expect(
|
||||
merge.execute([{ id: 1n }], { retries: 0 }),
|
||||
).rejects.toThrow();
|
||||
expect(attempts).toBe(1);
|
||||
await expect(merge.execute([{ id: 1n }])).resolves.toMatchObject({
|
||||
version: 2,
|
||||
});
|
||||
await expect(
|
||||
merge.execute([{ id: 1n }], { retries: 255 }),
|
||||
).resolves.toMatchObject({ version: 2 });
|
||||
expect(attempts).toBe(5);
|
||||
await expect(table.countRows()).resolves.toBe(1);
|
||||
expect(readAttempts).toBe(2);
|
||||
await expect(
|
||||
table
|
||||
.mergeInsert("id")
|
||||
.whenNotMatchedInsertAll()
|
||||
.execute([{ id: 1n }]),
|
||||
).resolves.toMatchObject({ version: 2 });
|
||||
expect(attempts).toBe(7);
|
||||
},
|
||||
{
|
||||
clientConfig: {
|
||||
retryConfig: { retries: 3, backoffFactor: 0, backoffJitter: 0 },
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should accept partial connection options", async () => {
|
||||
await connect("db://test", {
|
||||
apiKey: "fake",
|
||||
@@ -647,6 +863,100 @@ describe("remote connection", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("passes a pinned version and decodes Function scheduler status", async () => {
|
||||
const queries: Record<string, string>[] = [];
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://localhost");
|
||||
if (url.pathname.endsWith("/describe/")) {
|
||||
res.writeHead(200, { "Content-Type": "application/json" }).end(
|
||||
JSON.stringify({
|
||||
name: "docs",
|
||||
version: 42,
|
||||
schema: { fields: [] },
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/v1/table/docs/function_columns/status") {
|
||||
queries.push(Object.fromEntries(url.searchParams.entries()));
|
||||
res.writeHead(200, { "Content-Type": "application/json" }).end(
|
||||
`[{
|
||||
"column":"embedding",
|
||||
"binding_id":"fb_01",
|
||||
"function":{
|
||||
"name":"embed",
|
||||
"object_id":"embed",
|
||||
"location":"objects/embed",
|
||||
"version":"7",
|
||||
"manifest_digest":"sha256:abc"
|
||||
},
|
||||
"table_version":42,
|
||||
"rows":4,
|
||||
"fresh":2,
|
||||
"stale":2,
|
||||
"never_computed":0,
|
||||
"failed":0,
|
||||
"last_refresh_job":{
|
||||
"job_id":"job-cancelled",
|
||||
"state":"cancelled",
|
||||
"automatic":true,
|
||||
"completed_at_millis":1790000002000
|
||||
},
|
||||
"last_failure_job":{
|
||||
"job_id":"job-failed",
|
||||
"state":"failed",
|
||||
"automatic":true,
|
||||
"completed_at_millis":1790000001000,
|
||||
"failure":{
|
||||
"phase":"finalize",
|
||||
"message":"worker timed out",
|
||||
"traceback":"Traceback: timeout",
|
||||
"retryable":true,
|
||||
"sql_job_id":"sql-job-7"
|
||||
}
|
||||
},
|
||||
"auto_refresh":{
|
||||
"enabled":true,
|
||||
"interval_seconds":60,
|
||||
"active_job_id":"job-queued",
|
||||
"state":"queued",
|
||||
"failure_streak":1,
|
||||
"next_run_at_millis":null,
|
||||
"next_run_at_reason":"job_queued_not_started"
|
||||
}
|
||||
}]`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("docs");
|
||||
await table.checkout(42);
|
||||
const status = await table.functionColumnStatus("embedding");
|
||||
expect(status.tableVersion).toBe(42n);
|
||||
expect(status.autoRefresh.state).toBe("queued");
|
||||
expect(status.autoRefresh.activeJobId).toBe("job-queued");
|
||||
expect(status.autoRefresh.failureStreak).toBe(1);
|
||||
expect(status.autoRefresh.nextRunAtReason).toBe(
|
||||
"job_queued_not_started",
|
||||
);
|
||||
expect(status.lastRefreshJob?.state).toBe("cancelled");
|
||||
expect(status.lastRefreshJob?.failure).toBeUndefined();
|
||||
expect(status.lastFailureJob?.jobId).toBe("job-failed");
|
||||
expect(status.lastFailureJob?.failure).toEqual({
|
||||
phase: "finalize",
|
||||
message: "worker timed out",
|
||||
traceback: "Traceback: timeout",
|
||||
retryable: true,
|
||||
sqlJobId: "sql-job-7",
|
||||
});
|
||||
},
|
||||
);
|
||||
expect(queries).toEqual([{ column: "embedding", version: "42" }]);
|
||||
});
|
||||
|
||||
it("forwards refresh options to the backfill request", async () => {
|
||||
const bodies: unknown[] = [];
|
||||
await withMockDatabase(
|
||||
@@ -682,6 +992,7 @@ describe("remote connection", () => {
|
||||
const job = await table.refreshColumnAsync("embedding", {
|
||||
where: "id % 2 = 0",
|
||||
batchSize: 16,
|
||||
publicationIntervalRows: 60,
|
||||
maxConcurrency: 3,
|
||||
gpuClass: "a10g",
|
||||
gpuCount: 2,
|
||||
@@ -694,6 +1005,18 @@ describe("remote connection", () => {
|
||||
});
|
||||
expect(job.id).toBe("j-9");
|
||||
await table.refreshColumnAsync("embedding");
|
||||
await table.refreshColumnAsync("embedding", {
|
||||
publicationIntervalRows: undefined,
|
||||
});
|
||||
for (const publicationIntervalRows of [
|
||||
1,
|
||||
2 ** 32 + 1,
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
]) {
|
||||
await table.refreshColumnAsync("embedding", {
|
||||
publicationIntervalRows,
|
||||
});
|
||||
}
|
||||
await table.refreshColumnAsync("embedding", {
|
||||
resourceBudget: {
|
||||
cpuMillis: 8_000,
|
||||
@@ -705,6 +1028,14 @@ describe("remote connection", () => {
|
||||
maxConcurrency: true as unknown as number,
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
for (const publicationIntervalRows of [true, "60", 60n]) {
|
||||
await expect(
|
||||
table.refreshColumnAsync("embedding", {
|
||||
publicationIntervalRows:
|
||||
publicationIntervalRows as unknown as number,
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
}
|
||||
// Invalid options reject before any request is sent.
|
||||
for (const [options, message] of [
|
||||
[{ maxFailedRows: -1 }, "maxFailedRows"],
|
||||
@@ -712,6 +1043,22 @@ describe("remote connection", () => {
|
||||
[{ where: " " }, "where"],
|
||||
[{ maxFailedFraction: 2 }, "max_failed_fraction"],
|
||||
[{ rowTimeoutSeconds: 0 }, "row_timeout_seconds"],
|
||||
[{ publicationIntervalRows: 0 }, "publicationIntervalRows"],
|
||||
[{ publicationIntervalRows: -1 }, "publicationIntervalRows"],
|
||||
[{ publicationIntervalRows: 1.5 }, "publicationIntervalRows"],
|
||||
[{ publicationIntervalRows: Number.NaN }, "publicationIntervalRows"],
|
||||
[
|
||||
{ publicationIntervalRows: Number.POSITIVE_INFINITY },
|
||||
"publicationIntervalRows",
|
||||
],
|
||||
[
|
||||
{ publicationIntervalRows: Number.NEGATIVE_INFINITY },
|
||||
"publicationIntervalRows",
|
||||
],
|
||||
[
|
||||
{ publicationIntervalRows: Number.MAX_SAFE_INTEGER + 1 },
|
||||
"publicationIntervalRows",
|
||||
],
|
||||
[{ maxConcurrency: 1.5 }, "maxConcurrency"],
|
||||
[{ maxConcurrency: 0 }, "maxConcurrency"],
|
||||
[{ maxConcurrency: -1 }, "maxConcurrency"],
|
||||
@@ -789,6 +1136,42 @@ describe("remote connection", () => {
|
||||
},
|
||||
"resourceBudget.gpuCount",
|
||||
],
|
||||
[
|
||||
{
|
||||
supervisorResources: {
|
||||
cpuMillis: 0,
|
||||
memoryBytes: 1_024,
|
||||
ephemeralStorageBytes: 2_048,
|
||||
},
|
||||
},
|
||||
"supervisorResources.cpuMillis",
|
||||
],
|
||||
[
|
||||
{
|
||||
supervisorResources: {
|
||||
cpuMillis: 1_000,
|
||||
memoryBytes: 1_024,
|
||||
ephemeralStorageBytes: 0,
|
||||
},
|
||||
},
|
||||
"supervisorResources.ephemeralStorageBytes",
|
||||
],
|
||||
[
|
||||
{
|
||||
planningWorkers: {
|
||||
resources: {
|
||||
cpuMillis: 1_000,
|
||||
memoryBytes: 1_024,
|
||||
ephemeralStorageBytes: 2_048,
|
||||
},
|
||||
maxWorkers: 0,
|
||||
rowsPerWorker: 100,
|
||||
fragmentsPerWorker: 1,
|
||||
},
|
||||
},
|
||||
"planningWorkers.maxWorkers",
|
||||
],
|
||||
[{ retryPolicy: { maxAttempts: 0 } }, "retry_policy.max_attempts"],
|
||||
] as const) {
|
||||
await expect(
|
||||
table.refreshColumnAsync("embedding", options),
|
||||
@@ -799,6 +1182,7 @@ describe("remote connection", () => {
|
||||
expect(bodies).toEqual([
|
||||
JSON.parse(
|
||||
`{"column": "embedding", "where": "id % 2 = 0", "batch_size": 16,
|
||||
"publication_interval_rows": 60,
|
||||
"max_concurrency": 3, "gpu_class": "a10g", "gpu_count": 2,
|
||||
"error_policy": "skip",
|
||||
"max_failed_fraction": 0.01, "max_failed_rows": 50,
|
||||
@@ -806,6 +1190,14 @@ describe("remote connection", () => {
|
||||
"max_executor_processes_per_worker": 2}`,
|
||||
),
|
||||
{ column: "embedding" },
|
||||
{ column: "embedding" },
|
||||
JSON.parse('{"column": "embedding", "publication_interval_rows": 1}'),
|
||||
JSON.parse(
|
||||
'{"column": "embedding", "publication_interval_rows": 4294967297}',
|
||||
),
|
||||
JSON.parse(
|
||||
'{"column": "embedding", "publication_interval_rows": 9007199254740991}',
|
||||
),
|
||||
JSON.parse(
|
||||
`{"column": "embedding",
|
||||
"resource_budget": {
|
||||
@@ -817,6 +1209,91 @@ describe("remote connection", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("forwards structured Function refresh options and Node retry policy", async () => {
|
||||
const bodies: unknown[] = [];
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
const path = req.url ?? "";
|
||||
if (path.endsWith("/describe/")) {
|
||||
res.writeHead(200, { "Content-Type": "application/json" }).end(
|
||||
JSON.stringify({
|
||||
name: "docs",
|
||||
version: 1,
|
||||
schema: { fields: [] },
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (path === "/v1/table/docs/backfill_column") {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => {
|
||||
body += chunk;
|
||||
});
|
||||
req.on("end", () => {
|
||||
bodies.push(JSON.parse(body));
|
||||
res
|
||||
.writeHead(202, { "Content-Type": "application/json" })
|
||||
.end('{"job_id": "j-structured"}');
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("docs");
|
||||
const job = await table.refreshColumnAsync("embedding", {
|
||||
supervisorResources: {
|
||||
cpuMillis: 2_000,
|
||||
memoryBytes: 4 * 1024 ** 3,
|
||||
ephemeralStorageBytes: 10 * 1024 ** 3,
|
||||
},
|
||||
planningWorkers: {
|
||||
resources: {
|
||||
cpuMillis: 1_000,
|
||||
memoryBytes: 2 * 1024 ** 3,
|
||||
ephemeralStorageBytes: 5 * 1024 ** 3,
|
||||
},
|
||||
maxWorkers: 4,
|
||||
rowsPerWorker: 100_000,
|
||||
fragmentsPerWorker: 8,
|
||||
},
|
||||
retryPolicy: { transient: true },
|
||||
});
|
||||
expect(job.id).toBe("j-structured");
|
||||
},
|
||||
);
|
||||
expect(bodies).toEqual([
|
||||
{
|
||||
column: "embedding",
|
||||
["supervisor_resources"]: {
|
||||
["cpu_millis"]: 2_000,
|
||||
["memory_bytes"]: 4 * 1024 ** 3,
|
||||
["ephemeral_storage_bytes"]: 10 * 1024 ** 3,
|
||||
},
|
||||
["planning_workers"]: {
|
||||
resources: {
|
||||
["cpu_millis"]: 1_000,
|
||||
["memory_bytes"]: 2 * 1024 ** 3,
|
||||
["ephemeral_storage_bytes"]: 5 * 1024 ** 3,
|
||||
},
|
||||
["max_workers"]: 4,
|
||||
["rows_per_worker"]: 100_000,
|
||||
["fragments_per_worker"]: 8,
|
||||
},
|
||||
["retry_policy"]: {
|
||||
["max_attempts"]: 3,
|
||||
["initial_backoff_seconds"]: 0.2,
|
||||
["max_backoff_seconds"]: 30,
|
||||
["exception_types"]: [],
|
||||
["message_pattern"]: null,
|
||||
["error_codes"]: [],
|
||||
transient: true,
|
||||
["honor_retry_after"]: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("surfaces JSON server errors from remote table operations", async () => {
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
@@ -1841,10 +2318,30 @@ describe("remote connection jobs surface", () => {
|
||||
queue_reason: "Waiting for Function worker capacity",
|
||||
});
|
||||
const descriptions = [
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 3000, unknownFleet)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 2000, knownFleet)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(40, 60, 1000, unknownFleet)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(60, 0, 0, unknownFleet)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(
|
||||
20,
|
||||
80,
|
||||
3000,
|
||||
unknownFleet,
|
||||
)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(
|
||||
20,
|
||||
80,
|
||||
2000,
|
||||
knownFleet,
|
||||
)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(
|
||||
40,
|
||||
60,
|
||||
1000,
|
||||
unknownFleet,
|
||||
)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(
|
||||
60,
|
||||
0,
|
||||
0,
|
||||
unknownFleet,
|
||||
)}}`,
|
||||
];
|
||||
let describeCount = 0;
|
||||
|
||||
@@ -1916,12 +2413,24 @@ describe("remote connection jobs surface", () => {
|
||||
it("does not derive ETA across a zero-rate, epoch, or pause boundary", async () => {
|
||||
const now = Date.now();
|
||||
const descriptions = [
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 5000}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 4000}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 3000}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 2000}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1500}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1000}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${
|
||||
now - 5000
|
||||
}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${
|
||||
now - 4000
|
||||
}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
|
||||
now - 3000
|
||||
}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
|
||||
now - 2000
|
||||
}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
|
||||
now - 1500
|
||||
}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
|
||||
now - 1000
|
||||
}}}`,
|
||||
];
|
||||
|
||||
await withMockDatabase(
|
||||
@@ -2097,6 +2606,7 @@ describe("lazy resource listings", () => {
|
||||
if (kind === "jobs") {
|
||||
expect(url.pathname).toBe("/v1/jobs/list");
|
||||
expect(request.body).toEqual({
|
||||
database: "dev",
|
||||
// biome-ignore lint/style/useNamingConvention: server wire format
|
||||
page_token: token,
|
||||
limit: 2,
|
||||
|
||||
@@ -0,0 +1,642 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { type Table, connect } from "../lancedb";
|
||||
import {
|
||||
Table as ArrowTable,
|
||||
DataType,
|
||||
Field,
|
||||
Float32,
|
||||
LargeBinary,
|
||||
RecordBatch,
|
||||
Schema,
|
||||
Struct,
|
||||
Uint8,
|
||||
Uint32,
|
||||
Uint64,
|
||||
Utf8,
|
||||
makeArrowTable,
|
||||
tableToIPC,
|
||||
vectorFromArray,
|
||||
} from "../lancedb/arrow";
|
||||
|
||||
const IDENTITY_A = `v1:${"a".repeat(64)}`;
|
||||
const IDENTITY_B = `v1:${"b".repeat(64)}`;
|
||||
const image = new Field(
|
||||
"image",
|
||||
new Struct([
|
||||
new Field("kind", new Uint8(), false),
|
||||
new Field("position", new Uint64(), true),
|
||||
new Field("size", new Uint64(), true),
|
||||
new Field("blob_id", new Uint32(), false),
|
||||
new Field("blob_uri", new Utf8(), false),
|
||||
]),
|
||||
true,
|
||||
// Native descriptor scans replace the logical extension metadata.
|
||||
new Map([
|
||||
["lance-encoding:blob", "true"],
|
||||
["lance-encoding:packed", "true"],
|
||||
]),
|
||||
);
|
||||
const schema = new Schema([new Field("label", new Utf8(), false), image]);
|
||||
const description = {
|
||||
fields: [
|
||||
{ name: "label", type: { type: "string" }, nullable: false },
|
||||
{
|
||||
name: "image",
|
||||
nullable: true,
|
||||
metadata: { "ARROW:extension:name": "lance.blob.v2" },
|
||||
type: {
|
||||
type: "struct",
|
||||
fields: ["position", "size"].map((name) => ({
|
||||
name,
|
||||
type: { type: "uint64" },
|
||||
nullable: true,
|
||||
})),
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
type Request = {
|
||||
path: string;
|
||||
body: Record<string, unknown>;
|
||||
raw: string;
|
||||
identity: string | string[] | undefined;
|
||||
};
|
||||
|
||||
interface ServerOptions {
|
||||
queryBlob?: Field;
|
||||
describeBlobName?: string | null;
|
||||
nestedBlob?: boolean;
|
||||
queryVersion?: string | null;
|
||||
queryIdentity?: string | null;
|
||||
echo?: string | null;
|
||||
empty?: boolean;
|
||||
values?: boolean;
|
||||
advanceQueries?: boolean;
|
||||
otherLegIdentity?: string | null;
|
||||
otherLegVersion?: string;
|
||||
}
|
||||
|
||||
// A real HTTP service: the query finishes on A, then the logical table changes
|
||||
// before the deferred blob request. Recreating B reuses both version and row IDs.
|
||||
async function withSnapshotServer(
|
||||
change: "recreate" | "overwrite",
|
||||
run: (table: Table, requests: Request[]) => Promise<void>,
|
||||
options: ServerOptions = {},
|
||||
) {
|
||||
const requests: Request[] = [];
|
||||
let changed = false;
|
||||
const queryBlob = options.queryBlob ?? image;
|
||||
const queryOutputSchema = options.nestedBlob
|
||||
? new Schema([
|
||||
schema.fields[0],
|
||||
new Field("extra", new Struct([queryBlob]), true),
|
||||
])
|
||||
: new Schema([schema.fields[0], queryBlob]);
|
||||
const server = createServer((req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
req.on("data", (chunk) => chunks.push(chunk));
|
||||
req.on("end", () => {
|
||||
try {
|
||||
const raw = Buffer.concat(chunks).toString() || "{}";
|
||||
const body = JSON.parse(raw);
|
||||
const path = req.url ?? "";
|
||||
const identity = req.headers["x-lancedb-query-snapshot"];
|
||||
requests.push({ path, body, raw, identity });
|
||||
res.setHeader("phalanx-version", "0.5.0");
|
||||
if (path.endsWith("/describe/")) {
|
||||
res.setHeader("content-type", "application/json");
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
version: changed && change === "overwrite" ? 2 : 1,
|
||||
schema: {
|
||||
fields: description.fields.flatMap((field) => {
|
||||
if (field.name !== "image") return [field];
|
||||
if (options.describeBlobName === null) return [];
|
||||
return [
|
||||
{ ...field, name: options.describeBlobName ?? "image" },
|
||||
];
|
||||
}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else if (path.endsWith("/query/")) {
|
||||
const vector = (body.vector?.length ?? 0) > 0;
|
||||
const advanced = options.advanceQueries === true && changed;
|
||||
const label = advanced ? "B" : "A";
|
||||
const columns: [string, string][] =
|
||||
body.columns === undefined
|
||||
? queryOutputSchema.fields.map((field) => [
|
||||
field.name,
|
||||
field.name,
|
||||
])
|
||||
: Array.isArray(body.columns)
|
||||
? body.columns.map((name: string) => [name, name])
|
||||
: Object.entries(body.columns);
|
||||
const queryFields = columns.map(([output, source]) =>
|
||||
queryOutputSchema.fields
|
||||
.find((field) => field.name === source)!
|
||||
.clone({ name: output }),
|
||||
);
|
||||
if (body.with_row_id) {
|
||||
queryFields.push(new Field("_rowid", new Uint64(), false));
|
||||
}
|
||||
if (vector || body.full_text_query) {
|
||||
queryFields.push(
|
||||
new Field(vector ? "_distance" : "_score", new Float32(), false),
|
||||
);
|
||||
}
|
||||
// Forged IPC metadata must never substitute for authoritative headers.
|
||||
const querySchema = new Schema(
|
||||
queryFields,
|
||||
new Map([
|
||||
["lancedb:query_version", "999"],
|
||||
["lancedb:query_snapshot", IDENTITY_B],
|
||||
]),
|
||||
);
|
||||
const values = options.empty
|
||||
? []
|
||||
: options.values
|
||||
? ["A", null, ""]
|
||||
: [label];
|
||||
const rows = values.map((value, index) => {
|
||||
const row: Record<string, unknown> = {};
|
||||
for (const [output, source] of columns) {
|
||||
const descriptor =
|
||||
value === null
|
||||
? null
|
||||
: {
|
||||
kind: 0,
|
||||
position: 0n,
|
||||
size: BigInt(value.length),
|
||||
// biome-ignore lint/style/useNamingConvention: Native Arrow field name.
|
||||
blob_id: 0,
|
||||
// biome-ignore lint/style/useNamingConvention: Native Arrow field name.
|
||||
blob_uri: "",
|
||||
};
|
||||
row[output] =
|
||||
source === "image"
|
||||
? descriptor
|
||||
: source === "extra"
|
||||
? descriptor === null
|
||||
? null
|
||||
: { image: descriptor }
|
||||
: label;
|
||||
}
|
||||
if (body.with_row_id) row._rowid = BigInt(index);
|
||||
if (vector || body.full_text_query) {
|
||||
row[vector ? "_distance" : "_score"] = 0.5;
|
||||
}
|
||||
return row;
|
||||
});
|
||||
const result =
|
||||
rows.length === 0
|
||||
? new ArrowTable(querySchema)
|
||||
: new ArrowTable(
|
||||
querySchema,
|
||||
Object.fromEntries(
|
||||
queryFields.map((field) => [
|
||||
field.name,
|
||||
vectorFromArray(
|
||||
rows.map((row) => row[field.name]),
|
||||
field.type,
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
res.setHeader("content-type", "application/vnd.apache.arrow.stream");
|
||||
const version =
|
||||
vector && options.otherLegVersion !== undefined
|
||||
? options.otherLegVersion
|
||||
: options.queryVersion;
|
||||
const snapshot =
|
||||
vector && options.otherLegIdentity !== undefined
|
||||
? options.otherLegIdentity
|
||||
: options.queryIdentity;
|
||||
res.setHeader("x-lancedb-version", "1");
|
||||
if (version !== null) {
|
||||
res.setHeader(
|
||||
"x-lancedb-query-version",
|
||||
version ?? (advanced ? "2" : "1"),
|
||||
);
|
||||
}
|
||||
if (snapshot !== null) {
|
||||
res.setHeader(
|
||||
"x-lancedb-query-snapshot",
|
||||
snapshot ?? (advanced ? IDENTITY_B : IDENTITY_A),
|
||||
);
|
||||
}
|
||||
changed = true;
|
||||
res.end(tableToIPC(result, "stream"));
|
||||
} else if (path.endsWith("/fetch_blobs/")) {
|
||||
const requestedVersion = /"version":([0-9]+)/.exec(raw)?.[1];
|
||||
const readsOriginal =
|
||||
change === "overwrite" &&
|
||||
requestedVersion === (options.queryVersion ?? "1");
|
||||
const actualIdentity = readsOriginal ? IDENTITY_A : IDENTITY_B;
|
||||
// An older serving node may ignore the guard and answer successfully;
|
||||
// its echo must still be verified before the client uses any bytes.
|
||||
if (options.echo !== null) {
|
||||
res.setHeader(
|
||||
"x-lancedb-query-snapshot",
|
||||
options.echo ?? actualIdentity,
|
||||
);
|
||||
}
|
||||
res.setHeader("content-type", "application/vnd.apache.arrow.stream");
|
||||
const payloads = options.values
|
||||
? ["A", null, ""]
|
||||
: [readsOriginal ? "A" : "B"];
|
||||
res.end(
|
||||
tableToIPC(
|
||||
makeArrowTable(
|
||||
(body.row_ids as number[]).map((id) => ({
|
||||
[String(body.column)]:
|
||||
payloads[id] === null ? null : Buffer.from(payloads[id]!),
|
||||
})),
|
||||
{
|
||||
schema: new Schema([
|
||||
new Field(String(body.column), new LargeBinary(), true),
|
||||
]),
|
||||
},
|
||||
),
|
||||
"stream",
|
||||
),
|
||||
);
|
||||
} else {
|
||||
res.writeHead(404).end(path);
|
||||
}
|
||||
} catch (error) {
|
||||
res.writeHead(500).end(String(error));
|
||||
}
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
try {
|
||||
const db = await connect("db://dev", {
|
||||
apiKey: "fake",
|
||||
hostOverride: `http://127.0.0.1:${
|
||||
(server.address() as AddressInfo).port
|
||||
}`,
|
||||
});
|
||||
await run(await db.openTable("test"), requests);
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
const fetchRequests = (requests: Request[]) =>
|
||||
requests.filter((request) => request.path.endsWith("/fetch_blobs/"));
|
||||
const queryRequests = (requests: Request[]) =>
|
||||
requests.filter((request) => request.path.endsWith("/query/"));
|
||||
|
||||
const keepFtsReranker = {
|
||||
async rerankHybrid(_query: string, _vector: RecordBatch, fts: RecordBatch) {
|
||||
const fields = fts.schema.fields.map((field) =>
|
||||
field.name === "_score"
|
||||
? field.clone({ name: "_relevance_score" })
|
||||
: field,
|
||||
);
|
||||
return new RecordBatch(
|
||||
new Schema(fields, fts.schema.metadata),
|
||||
fts.data.clone(new Struct(fields)),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
describe("remote blob query snapshot", () => {
|
||||
it.each([
|
||||
image.clone({ metadata: new Map() }),
|
||||
new Field(
|
||||
"image",
|
||||
new Struct(image.type.children.slice(1, 3)),
|
||||
true,
|
||||
image.metadata,
|
||||
),
|
||||
])(
|
||||
"leaves plain structs and v1 descriptors unchanged: %s",
|
||||
async (queryBlob) => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
const result = await table.query().toArrow({ blobMode: "bytes" });
|
||||
expect(DataType.isStruct(result.getChild("image")!.type)).toBe(true);
|
||||
expect(result.toArray()[0].image.size).toBe(1n);
|
||||
expect(fetchRequests(requests)).toHaveLength(0);
|
||||
},
|
||||
{ queryBlob },
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("still recognizes extension-marked Blob results", async () => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
const rows = await table.query().toArray({ blobMode: "bytes" });
|
||||
expect(Buffer.from(rows[0].image).toString()).toBe("A");
|
||||
expect(fetchRequests(requests)).toHaveLength(1);
|
||||
},
|
||||
{
|
||||
queryBlob: image.clone({
|
||||
metadata: new Map([["ARROW:extension:name", "lance.blob.v2"]]),
|
||||
}),
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[null, false],
|
||||
[null, true],
|
||||
["old_image", false],
|
||||
["old_image", true],
|
||||
] as const)(
|
||||
"uses the query schema after cached blob %s changes (alias: %s)",
|
||||
async (describeBlobName, alias) => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
expect(await table.blobColumns()).toEqual(
|
||||
describeBlobName === null ? [] : [describeBlobName],
|
||||
);
|
||||
const query = table.query();
|
||||
if (alias) query.select({ "photo.image": "image" });
|
||||
const output = alias ? "photo.image" : "image";
|
||||
const result = await query.toArrow({ blobMode: "bytes" });
|
||||
expect(DataType.isLargeBinary(result.getChild(output)!.type)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
result
|
||||
.toArray()
|
||||
.map((row) =>
|
||||
row[output] === null
|
||||
? null
|
||||
: Buffer.from(row[output]).toString(),
|
||||
),
|
||||
).toEqual(["A", null, ""]);
|
||||
expect(
|
||||
result.schema.fields.some((field) => field.name === "_rowid"),
|
||||
).toBe(false);
|
||||
expect(queryRequests(requests)).toHaveLength(1);
|
||||
expect(fetchRequests(requests)).toHaveLength(1);
|
||||
expect(fetchRequests(requests)[0].body.column).toBe("image");
|
||||
expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A);
|
||||
},
|
||||
{ describeBlobName, values: true },
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("maps nested query fields through literal aliases despite a stale schema", async () => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
expect(await table.blobColumns()).toEqual([]);
|
||||
const rows = await table
|
||||
.query()
|
||||
.select({ "container.alias": "extra" })
|
||||
.toArray({ blobMode: "bytes" });
|
||||
expect(
|
||||
rows.map((row) =>
|
||||
row["container.alias"] === null
|
||||
? null
|
||||
: Buffer.from(row["container.alias"].image).toString(),
|
||||
),
|
||||
).toEqual(["A", null, ""]);
|
||||
expect(queryRequests(requests)).toHaveLength(1);
|
||||
expect(fetchRequests(requests)[0].body.column).toBe("extra.image");
|
||||
expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A);
|
||||
},
|
||||
{ nestedBlob: true, describeBlobName: null, values: true },
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["toArrow", "toArray"] as const)(
|
||||
"%s rejects payloads from a recreated table with reused version and row IDs",
|
||||
async (terminal) => {
|
||||
await withSnapshotServer("recreate", async (table, requests) => {
|
||||
await expect(
|
||||
table.query()[terminal]({ blobMode: "bytes" }),
|
||||
).rejects.toThrow(/snapshot identity/);
|
||||
const [fetch] = fetchRequests(requests);
|
||||
expect(fetch.body.version).toBe(1);
|
||||
expect(fetch.body.row_ids).toEqual([0]);
|
||||
expect(fetch.body.column).toBe("image");
|
||||
expect(fetch.identity).toBe(IDENTITY_A);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the producing snapshot after an overwrite without rerunning the query", async () => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
const rows = await table.query().toArray({ blobMode: "bytes" });
|
||||
expect(rows[0].label).toBe("A");
|
||||
expect(Buffer.from(rows[0].image).toString()).toBe("A");
|
||||
expect(queryRequests(requests)).toHaveLength(1);
|
||||
const [fetch] = fetchRequests(requests);
|
||||
expect(fetch.body.version).toBe(1);
|
||||
expect(fetch.identity).toBe(IDENTITY_A);
|
||||
expect(await table.version()).toBe(2);
|
||||
const [latest] = await table.query().toArray({ blobMode: "bytes" });
|
||||
expect(latest.label).toBe("B");
|
||||
expect(Buffer.from(latest.image).toString()).toBe("B");
|
||||
expect(fetchRequests(requests)[1].identity).toBe(IDENTITY_B);
|
||||
},
|
||||
{ advanceQueries: true },
|
||||
);
|
||||
});
|
||||
|
||||
it.each<ServerOptions>([
|
||||
{ queryVersion: null },
|
||||
{ queryVersion: "0" },
|
||||
{ queryVersion: "18446744073709551616" },
|
||||
{ queryVersion: "invalid" },
|
||||
{ queryIdentity: null },
|
||||
{ queryIdentity: "v2:unsupported" },
|
||||
])("refuses bytes without authoritative capability %j", async (options) => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
const [descriptor] = await table.query().toArray();
|
||||
expect(descriptor.image.size).toBe(1n);
|
||||
await expect(
|
||||
table.query().toArray({ blobMode: "bytes" }),
|
||||
).rejects.toThrow(/blobMode.*bytes.*requires.*snapshot/);
|
||||
expect(fetchRequests(requests)).toHaveLength(0);
|
||||
},
|
||||
options,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a serving node without the snapshot echo", async () => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table) => {
|
||||
await expect(
|
||||
table.query().toArray({ blobMode: "bytes" }),
|
||||
).rejects.toThrow(/snapshot identity/);
|
||||
},
|
||||
{ echo: null },
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps aliases, NULL, empty bytes, and explicit row IDs", async () => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
const query = table
|
||||
.query()
|
||||
.select({ caption: "label", "photo.image": "image" });
|
||||
const rows = await query.withRowId().toArray({ blobMode: "bytes" });
|
||||
expect(rows.map((row) => row._rowid)).toEqual([0n, 1n, 2n]);
|
||||
expect(
|
||||
rows.map((row) =>
|
||||
row["photo.image"] === null
|
||||
? null
|
||||
: Buffer.from(row["photo.image"]).toString(),
|
||||
),
|
||||
).toEqual(["A", null, ""]);
|
||||
expect(rows[0].caption).toBe("A");
|
||||
expect(fetchRequests(requests)[0].body.column).toBe("image");
|
||||
const [descriptor] = await query.toArray();
|
||||
expect(descriptor["photo.image"].size).toBe(1n);
|
||||
},
|
||||
{ values: true },
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves an empty bytes schema without fetching payloads", async () => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
const result = await table.query().toArrow({ blobMode: "bytes" });
|
||||
expect(result.numRows).toBe(0);
|
||||
expect(DataType.isLargeBinary(result.getChild("image")!.type)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(result.schema.fields.map((field) => field.name)).toEqual([
|
||||
"label",
|
||||
"image",
|
||||
]);
|
||||
expect(fetchRequests(requests)).toHaveLength(0);
|
||||
},
|
||||
{ empty: true },
|
||||
);
|
||||
});
|
||||
|
||||
it("passes the query version without rounding through a JS number", async () => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
await table.query().toArray({ blobMode: "bytes" });
|
||||
expect(fetchRequests(requests)[0].raw).toContain(
|
||||
'"version":9007199254740993',
|
||||
);
|
||||
},
|
||||
{ queryVersion: "9007199254740993" },
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["vector", "hybrid"])(
|
||||
"materializes the actual %s query entry point",
|
||||
async (kind) => {
|
||||
await withSnapshotServer("overwrite", async (table, requests) => {
|
||||
const query = table.query().nearestTo([0.1, 0.2]);
|
||||
if (kind === "hybrid") query.fullTextSearch("A");
|
||||
const rows = await query.toArray({ blobMode: "bytes" });
|
||||
expect(Buffer.from(rows[0].image).toString()).toBe("A");
|
||||
expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A);
|
||||
expect(queryRequests(requests)).toHaveLength(kind === "hybrid" ? 2 : 1);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("allows scalar-only bytes queries on older servers", async () => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
const [row] = await table
|
||||
.query()
|
||||
.select(["label"])
|
||||
.toArray({ blobMode: "bytes" });
|
||||
expect(row.label).toBe("A");
|
||||
expect(Object.keys(row)).toEqual(["label"]);
|
||||
expect(fetchRequests(requests)).toHaveLength(0);
|
||||
// Row IDs are requested before the executed output schema is known,
|
||||
// then hidden from scalar-only results without requiring capability.
|
||||
expect(queryRequests(requests)[0].body.with_row_id).toBe(true);
|
||||
},
|
||||
{ queryIdentity: null, queryVersion: null },
|
||||
);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"preserves snapshot proof across a custom reranker (empty: %s)",
|
||||
async (empty) => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
const result = await table
|
||||
.query()
|
||||
.nearestTo([0.1, 0.2])
|
||||
.fullTextSearch("A")
|
||||
.rerank(keepFtsReranker)
|
||||
.toArrow({ blobMode: "bytes" });
|
||||
expect(result.numRows).toBe(empty ? 0 : 1);
|
||||
expect(DataType.isLargeBinary(result.getChild("image")!.type)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(fetchRequests(requests)).toHaveLength(empty ? 0 : 1);
|
||||
},
|
||||
{ empty },
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not trust a custom reranker's first-leg snapshot when the legs disagree", async () => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
const query = table
|
||||
.query()
|
||||
.nearestTo([0.1, 0.2])
|
||||
.fullTextSearch("A")
|
||||
.rerank(keepFtsReranker);
|
||||
await expect(query.toArray({ blobMode: "bytes" })).rejects.toThrow(
|
||||
/snapshot/,
|
||||
);
|
||||
expect(fetchRequests(requests)).toHaveLength(0);
|
||||
},
|
||||
{ otherLegIdentity: IDENTITY_B },
|
||||
);
|
||||
});
|
||||
|
||||
it.each<ServerOptions>([
|
||||
{ otherLegIdentity: IDENTITY_B },
|
||||
{ otherLegIdentity: null },
|
||||
{ otherLegVersion: "2" },
|
||||
])(
|
||||
"refuses hybrid bytes when its actual query legs disagree %j",
|
||||
async (options) => {
|
||||
await withSnapshotServer(
|
||||
"overwrite",
|
||||
async (table, requests) => {
|
||||
const query = table.query().nearestTo([0.1, 0.2]).fullTextSearch("A");
|
||||
await expect(query.toArray({ blobMode: "bytes" })).rejects.toThrow(
|
||||
/snapshot/,
|
||||
);
|
||||
expect(fetchRequests(requests)).toHaveLength(0);
|
||||
expect(await query.toArray()).toHaveLength(1);
|
||||
},
|
||||
options,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -938,7 +938,8 @@ describe("merge insert", () => {
|
||||
.mergeInsert("a")
|
||||
.whenMatchedUpdateAll()
|
||||
.whenNotMatchedInsertAll()
|
||||
.execute(newData, { timeoutMs: 10_000 });
|
||||
.useIndex(false)
|
||||
.execute(newData, { timeoutMs: 10_000, retries: 0 });
|
||||
expect(mergeInsertRes).toHaveProperty("version");
|
||||
expect(mergeInsertRes.version).toBe(2);
|
||||
expect(mergeInsertRes.numInsertedRows).toBe(1);
|
||||
@@ -3029,6 +3030,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"]);
|
||||
@@ -3244,29 +3282,6 @@ describe("when dealing with blob columns", () => {
|
||||
expect(await handle!.read()).toEqual(alpha);
|
||||
});
|
||||
|
||||
it("cancels an in-flight read", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const schema = new Schema([
|
||||
new Field("id", new Int64(), true),
|
||||
blob("payload", { inlineSizeThreshold: 0, dedicatedSizeThreshold: 1 }),
|
||||
]);
|
||||
const payload = Buffer.alloc(32 * 1024 * 1024, 7);
|
||||
const table = await db.createTable("large_blobs", [{ id: 1n, payload }], {
|
||||
schema,
|
||||
});
|
||||
const [row] = await table.query().withRowId().toArray();
|
||||
const [handle] = await table.fetchBlobFiles("payload", [
|
||||
row._rowid as bigint,
|
||||
]);
|
||||
const controller = new AbortController();
|
||||
const pending = handle!.readRange(0n, handle!.size(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort();
|
||||
await expect(pending).rejects.toMatchObject({ name: "AbortError" });
|
||||
expect(await handle!.readRange(0n, 4n)).toEqual(payload.subarray(0, 4));
|
||||
});
|
||||
|
||||
it("toArrow returns blob bytes with blobMode bytes", async () => {
|
||||
const { table, alpha, beta } = await openBlobTable();
|
||||
const result = await table.query().toArrow({ blobMode: "bytes" });
|
||||
@@ -5696,6 +5711,14 @@ describe("computed columns", () => {
|
||||
await expect(
|
||||
table.refreshColumnAsync("x", { errorPolicy: "skip" }),
|
||||
).rejects.toThrow("error_policy requires a LanceDB Enterprise refresh");
|
||||
for (const refresh of [
|
||||
() => table.refreshColumn("x", { publicationIntervalRows: 60 }),
|
||||
() => table.refreshColumnAsync("x", { publicationIntervalRows: 60 }),
|
||||
]) {
|
||||
await expect(refresh()).rejects.toThrow(
|
||||
"publication_interval_rows requires a LanceDB Enterprise refresh",
|
||||
);
|
||||
}
|
||||
await expect(
|
||||
table.refreshColumnAsync("x", { maxConcurrency: 4 }),
|
||||
).rejects.toThrow("max_concurrency requires a LanceDB Enterprise refresh");
|
||||
@@ -5704,6 +5727,31 @@ describe("computed columns", () => {
|
||||
resourceBudget: { cpuMillis: 1_000, memoryBytes: 1_024 },
|
||||
}),
|
||||
).rejects.toThrow("resource_budget requires a LanceDB Enterprise refresh");
|
||||
await expect(
|
||||
table.refreshColumn("x", {
|
||||
supervisorResources: {
|
||||
cpuMillis: 1_000,
|
||||
memoryBytes: 1_024,
|
||||
ephemeralStorageBytes: 2_048,
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"supervisor_resources requires a LanceDB Enterprise refresh",
|
||||
);
|
||||
await expect(
|
||||
table.refreshColumnAsync("x", {
|
||||
planningWorkers: {
|
||||
resources: {
|
||||
cpuMillis: 1_000,
|
||||
memoryBytes: 1_024,
|
||||
ephemeralStorageBytes: 2_048,
|
||||
},
|
||||
maxWorkers: 2,
|
||||
rowsPerWorker: 100,
|
||||
fragmentsPerWorker: 1,
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("planning_workers requires a LanceDB Enterprise refresh");
|
||||
});
|
||||
|
||||
it("records Function errors only on remote tables", async () => {
|
||||
|
||||
+51
-1
@@ -1,7 +1,14 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { Field, LargeBinary, Struct, Uint64, Utf8 } from "apache-arrow";
|
||||
import {
|
||||
DataType,
|
||||
Field,
|
||||
LargeBinary,
|
||||
Struct,
|
||||
Uint64,
|
||||
Utf8,
|
||||
} from "apache-arrow";
|
||||
import { BlobFile as NativeBlobFile } from "./native";
|
||||
|
||||
const BLOB_V2_EXTENSION_NAME = "lance.blob.v2";
|
||||
@@ -178,6 +185,39 @@ export function isBlobField(field: Field): boolean {
|
||||
return field.metadata?.get("ARROW:extension:name") === BLOB_V2_EXTENSION_NAME;
|
||||
}
|
||||
|
||||
/** @ignore */
|
||||
export function isBlobDescriptorField(field: Field): boolean {
|
||||
// Native descriptor scans replace the logical extension metadata. Require
|
||||
// both the encoding marker and the v2 layout to exclude v1 and plain structs.
|
||||
if (
|
||||
field.metadata?.get("lance-encoding:blob") !== "true" ||
|
||||
!DataType.isStruct(field.type)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const children = field.type.children;
|
||||
const integers = [
|
||||
["kind", 8],
|
||||
["position", 64],
|
||||
["size", 64],
|
||||
["blob_id", 32],
|
||||
] as const;
|
||||
return (
|
||||
children.length === 5 &&
|
||||
integers.every(([name, width], index) => {
|
||||
const child = children[index];
|
||||
return (
|
||||
child.name === name &&
|
||||
DataType.isInt(child.type) &&
|
||||
!child.type.isSigned &&
|
||||
child.type.bitWidth === width
|
||||
);
|
||||
}) &&
|
||||
children[4].name === "blob_uri" &&
|
||||
DataType.isUtf8(children[4].type)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A lazy handle to blob bytes. Create one with {@link Table.fetchBlobFiles}.
|
||||
*
|
||||
@@ -305,6 +345,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;
|
||||
|
||||
@@ -57,6 +57,9 @@ export {
|
||||
AddResult,
|
||||
AddColumnsResult,
|
||||
RefreshColumnOptions,
|
||||
FunctionRefreshPlanningConfig,
|
||||
FunctionRefreshPodResources,
|
||||
FunctionRetryPolicy,
|
||||
FunctionWorkerResourceBudget,
|
||||
RefreshColumnResult,
|
||||
FunctionErrors,
|
||||
@@ -91,6 +94,7 @@ export type {
|
||||
BlobInput,
|
||||
BlobOptions,
|
||||
BlobRange,
|
||||
BlobRangeRequest,
|
||||
BlobReadOptions,
|
||||
BlobUri,
|
||||
} from "./blob";
|
||||
@@ -154,6 +158,10 @@ export {
|
||||
|
||||
export {
|
||||
Table,
|
||||
FunctionColumnAutoRefreshStatus,
|
||||
FunctionColumnLastRefreshJob,
|
||||
FunctionColumnStatus,
|
||||
FunctionColumnVersionStatus,
|
||||
Branches,
|
||||
BranchColumnSummary,
|
||||
BranchColumnChange,
|
||||
|
||||
+27
-1
@@ -127,6 +127,14 @@ export class MergeInsertBuilder {
|
||||
data: Data,
|
||||
execOptions?: Partial<WriteExecutionOptions>,
|
||||
): Promise<MergeResult> {
|
||||
if (
|
||||
execOptions?.retries !== undefined &&
|
||||
(!Number.isInteger(execOptions.retries) ||
|
||||
execOptions.retries < 0 ||
|
||||
execOptions.retries > 255)
|
||||
) {
|
||||
throw new Error("retries must be an integer between 0 and 255");
|
||||
}
|
||||
let schema: Schema;
|
||||
if (this.#schema instanceof Promise) {
|
||||
schema = await this.#schema;
|
||||
@@ -140,7 +148,7 @@ export class MergeInsertBuilder {
|
||||
}
|
||||
|
||||
const buffer = await fromDataToBuffer(data, undefined, schema);
|
||||
return await this.#native.execute(buffer);
|
||||
return await this.#native.execute(buffer, execOptions?.retries);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +164,24 @@ export interface WriteExecutionOptions {
|
||||
* first attempt will not be cancelled.
|
||||
*
|
||||
* When this is set, the timeout is enforced on all attempts, including the first.
|
||||
* For remote tables this is sent as a server execution timeout. It does not
|
||||
* extend HTTP read or proxy idle timeouts, or prove that a failed request did
|
||||
* not commit.
|
||||
*/
|
||||
timeoutMs?: number;
|
||||
|
||||
/**
|
||||
* Override the remote retry budget for this execution only (an integer from
|
||||
* 0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after
|
||||
* precommit conflicts (409) or rate limits (429). This does not change
|
||||
* connection-wide/read budgets or local transaction conflict retries.
|
||||
*
|
||||
* By default, remote calls use the connection's `clientConfig.retryConfig`
|
||||
* ({@link RetryConfig}). Its `statuses` (also set through
|
||||
* `LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget;
|
||||
* it never permits replay of ambiguous merge outcomes. In particular, 502,
|
||||
* ordinary 503, and 504 are never replayed, even if configured. Reconcile table
|
||||
* contents before manually repeating a merge whose commit outcome is unknown.
|
||||
*/
|
||||
retries?: number;
|
||||
}
|
||||
|
||||
+65
-6
@@ -17,6 +17,7 @@ import {
|
||||
tableFromIPC,
|
||||
vectorFromArray,
|
||||
} from "./arrow";
|
||||
import { isBlobDescriptorField, isBlobField } from "./blob";
|
||||
import { Expr } from "./expr";
|
||||
import { type IvfPqOptions } from "./indices";
|
||||
import {
|
||||
@@ -148,6 +149,34 @@ async function readBlobBytes(
|
||||
);
|
||||
}
|
||||
|
||||
// Discover descriptors from the executed query, not the live table's cached
|
||||
// schema. Projection names are literal aliases; only source paths use dots.
|
||||
function projectedBlobSources(
|
||||
schema: Schema,
|
||||
projection: [string, string][] | undefined,
|
||||
): BlobSource[] {
|
||||
const sources: BlobSource[] = [];
|
||||
for (const field of schema.fields) {
|
||||
const source =
|
||||
projection?.find(([output]) => output === field.name)?.[1] ?? field.name;
|
||||
const visit = (child: Field, path: string[]) => {
|
||||
if (isBlobField(child) || isBlobDescriptorField(child)) {
|
||||
sources.push({
|
||||
output: field.name,
|
||||
path,
|
||||
source: [source, ...path].join("."),
|
||||
});
|
||||
} else if (DataType.isStruct(child.type)) {
|
||||
for (const nested of child.type.children) {
|
||||
visit(nested, [...path, nested.name]);
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(field, []);
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
|
||||
function withBinaryColumns(
|
||||
table: ArrowTable,
|
||||
replacements: Map<Field, (Buffer | null)[]>,
|
||||
@@ -257,8 +286,10 @@ export interface QueryExecutionOptions {
|
||||
* bytes. Blobs inside lists keep their descriptors. Arbitrary projection
|
||||
* expressions are not materialized as bytes.
|
||||
*
|
||||
* The rows and the bytes come from the same table version. If the table
|
||||
* changes while the query runs, the query runs again, up to three times.
|
||||
* The rows and bytes come from the same snapshot. Remote queries require
|
||||
* authoritative query version and snapshot identity headers, verified again
|
||||
* by the blob response. Older servers can still return `"descriptions"`.
|
||||
* Local queries retry up to three times if the table changes while they run.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
@@ -499,6 +530,34 @@ export class QueryBase<
|
||||
if (context === undefined) {
|
||||
return this.collect(options, false);
|
||||
}
|
||||
if (!context.table.isNative()) {
|
||||
// Request row IDs in the same query so newly added Blob columns can be
|
||||
// fetched without rerunning the query against a different snapshot.
|
||||
const addRowId = !context.withRowId;
|
||||
const table = await this.collect(options, addRowId);
|
||||
const sources = projectedBlobSources(table.schema, context.projection);
|
||||
if (sources.length === 0) {
|
||||
return addRowId
|
||||
? table.select(
|
||||
table.schema.fields
|
||||
.map((field) => field.name)
|
||||
.filter((name) => name !== "_rowid"),
|
||||
)
|
||||
: table;
|
||||
}
|
||||
const version = table.schema.metadata.get("lancedb:query_version");
|
||||
const identity = table.schema.metadata.get("lancedb:query_snapshot");
|
||||
if (version === undefined || identity === undefined) {
|
||||
throw new Error(
|
||||
'blobMode "bytes" requires a trustworthy query snapshot: missing, invalid, or inconsistent x-lancedb-query-version or x-lancedb-query-snapshot. Upgrade every serving node, or use blobMode "descriptions".',
|
||||
);
|
||||
}
|
||||
const snapshot = await context.table.querySnapshotWithIdentity(
|
||||
version,
|
||||
identity,
|
||||
);
|
||||
return readBlobBytes(table, sources, snapshot, addRowId);
|
||||
}
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
// The snapshot pins the bytes. The query runs on the live table, so an
|
||||
// unchanged version afterwards proves it read the snapshot's version.
|
||||
@@ -533,10 +592,10 @@ export class QueryBase<
|
||||
for await (const batch of RecordBatchIterator(iterator)) {
|
||||
batches.push(batch);
|
||||
}
|
||||
if (batches.length === 0) {
|
||||
return tableFromIPC((await iterator).schema());
|
||||
}
|
||||
return new ArrowTable(batches);
|
||||
// Read metadata from the executed stream, including empty results and
|
||||
// query types whose individual batches do not carry the stream metadata.
|
||||
const schema = tableFromIPC((await iterator).schema()).schema;
|
||||
return new ArrowTable(schema, batches);
|
||||
}
|
||||
|
||||
private blobBytesContext(
|
||||
|
||||
+200
-3
@@ -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";
|
||||
@@ -35,6 +40,7 @@ import {
|
||||
FunctionErrorsOptions,
|
||||
IndexConfig,
|
||||
IndexStatistics,
|
||||
JobFailureInfo,
|
||||
Branches as NativeBranches,
|
||||
OptimizeStats,
|
||||
RTEStats,
|
||||
@@ -136,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 {
|
||||
@@ -258,6 +271,76 @@ export interface RTEWriteSpec {
|
||||
writerConfigDefaults?: Record<string, string>;
|
||||
}
|
||||
|
||||
/** Exact immutable Function revision attached to a table output. */
|
||||
export interface FunctionColumnVersionStatus {
|
||||
name: string;
|
||||
namespacePath: string[];
|
||||
objectId: string;
|
||||
location: string;
|
||||
version: string;
|
||||
manifestDigest: string;
|
||||
}
|
||||
|
||||
/** Latest matching refresh Job projected for a Function output. */
|
||||
export interface FunctionColumnLastRefreshJob {
|
||||
jobId: string;
|
||||
state: string;
|
||||
automatic?: boolean;
|
||||
completedAtMillis?: bigint;
|
||||
/** Structured failure details for a failed Job. */
|
||||
failure?: JobFailureInfo;
|
||||
}
|
||||
|
||||
/** Automatic-refresh projection for a Function output. */
|
||||
export interface FunctionColumnAutoRefreshStatus {
|
||||
enabled: boolean;
|
||||
intervalSeconds?: bigint;
|
||||
activeJobId?: string;
|
||||
state:
|
||||
| "disabled"
|
||||
| "running"
|
||||
| "queued"
|
||||
| "ready"
|
||||
| "up_to_date"
|
||||
| "waiting_interval"
|
||||
| "waiting_backoff"
|
||||
| "blocked"
|
||||
| "unobservable";
|
||||
failureStreak: number;
|
||||
effectiveCooldownMillis?: bigint;
|
||||
blockedReason?:
|
||||
| "table_has_mem_wal"
|
||||
| "inputs_not_settled"
|
||||
| "dependency_in_flight"
|
||||
| "table_capacity"
|
||||
| "cancelled"
|
||||
| "preparation_backoff"
|
||||
| "failure_threshold_reached"
|
||||
| "binding_revision_missing";
|
||||
nextRunAtMillis: bigint | null;
|
||||
nextRunAtReason?: string;
|
||||
}
|
||||
|
||||
/** Exact four-way status of one Function output at one table version. */
|
||||
export interface FunctionColumnStatus {
|
||||
column: string;
|
||||
bindingId: string;
|
||||
function: FunctionColumnVersionStatus;
|
||||
tableVersion: bigint;
|
||||
rows: bigint;
|
||||
fresh: bigint;
|
||||
stale: bigint;
|
||||
neverComputed: bigint;
|
||||
failed: bigint;
|
||||
lastRefreshJob?: FunctionColumnLastRefreshJob;
|
||||
/**
|
||||
* Newest failed refresh Job. This remains present when `lastRefreshJob`
|
||||
* is a later cancellation.
|
||||
*/
|
||||
lastFailureJob?: FunctionColumnLastRefreshJob;
|
||||
autoRefresh: FunctionColumnAutoRefreshStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Table is a collection of Records in a LanceDB Database.
|
||||
*
|
||||
@@ -605,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.
|
||||
@@ -723,12 +831,18 @@ export abstract class Table {
|
||||
* `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows,
|
||||
* `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds`
|
||||
* and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`,
|
||||
* `maxConcurrency`, `resourceBudget` and
|
||||
* `maxExecutorProcessesPerWorker` size registered Function refreshes.
|
||||
* `maxConcurrency`, `resourceBudget`, `supervisorResources`,
|
||||
* `planningWorkers` and `maxExecutorProcessesPerWorker` size registered
|
||||
* Function refreshes. `retryPolicy` overrides user-code retries only when
|
||||
* repeating partial work is safe; set `maxAttempts: 1` to disable retries.
|
||||
* `maxConcurrency` overrides the registered default for this logical
|
||||
* execution only and is a positive integer; it is not an account-wide
|
||||
* quota. A `resourceBudget` requires `cpuMillis` and
|
||||
* `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function.
|
||||
* `supervisorResources` and each `planningWorkers.resources` entry require
|
||||
* positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`.
|
||||
* `planningWorkers` also requires positive `maxWorkers`,
|
||||
* `rowsPerWorker` and `fragmentsPerWorker`.
|
||||
* The budget applies only to this explicit refresh and does not configure
|
||||
* a later automatic refresh.
|
||||
* `gpuCount` at the top level is the shorthand that preserves the
|
||||
@@ -737,6 +851,11 @@ export abstract class Table {
|
||||
* `resourceBudget` for registered Functions. All are LanceDB Enterprise
|
||||
* only; a LanceDB Embedded refresh rejects every option other than
|
||||
* `batchSize`, `gpuClass` and `gpuCount`.
|
||||
* `publicationIntervalRows` opts into publishing completed Function split
|
||||
* ranges once their accumulated unpublished rows reach the threshold.
|
||||
* It must be a positive safe integer and requires non-Blob Function outputs.
|
||||
* Omit it for whole-fragment publication. Publications can exceed the
|
||||
* threshold, and remaining rows publish at completion.
|
||||
* @example
|
||||
* ```ts
|
||||
* const job = await table.refreshColumnAsync("embedding", {
|
||||
@@ -746,6 +865,7 @@ export abstract class Table {
|
||||
* memoryBytes: 16 * 1024 ** 3,
|
||||
* },
|
||||
* maxConcurrency: 4,
|
||||
* publicationIntervalRows: 10000,
|
||||
* errorPolicy: "skip",
|
||||
* maxFailedFraction: 0.01,
|
||||
* rowTimeoutSeconds: 30,
|
||||
@@ -780,6 +900,32 @@ export abstract class Table {
|
||||
options?: FunctionErrorsOptions,
|
||||
): Promise<FunctionErrors>;
|
||||
|
||||
/**
|
||||
* Return exact freshness status for Function-backed output columns.
|
||||
*
|
||||
* All results describe one server table version. Omit `column` for every
|
||||
* Function output. Rows already failed remain visible and do not prevent
|
||||
* `waitFresh` from completing. A handle pinned to an exact version requests
|
||||
* that version; a latest handle retains normal read-freshness behavior.
|
||||
*/
|
||||
abstract functionColumnStatuses(
|
||||
column?: string,
|
||||
): Promise<FunctionColumnStatus[]>;
|
||||
|
||||
/** Return exact freshness status for one Function-backed output column. */
|
||||
abstract functionColumnStatus(column: string): Promise<FunctionColumnStatus>;
|
||||
|
||||
/**
|
||||
* Poll until no stale or never-computed rows remain.
|
||||
*
|
||||
* Only HTTP 503 with the exact finalization-pending error code is retried;
|
||||
* every other error propagates. Failed rows do not block completion.
|
||||
*/
|
||||
abstract waitFresh(
|
||||
column: string,
|
||||
timeoutSeconds?: number,
|
||||
): Promise<FunctionColumnStatus>;
|
||||
|
||||
/**
|
||||
* Recompute this table's contents from its materialized-view definition.
|
||||
*
|
||||
@@ -1217,6 +1363,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();
|
||||
|
||||
@@ -1239,6 +1393,7 @@ export class LocalTable extends Table {
|
||||
mode,
|
||||
progress,
|
||||
options?.allowExternalBlobOutsideBases,
|
||||
options?.retries,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1391,6 +1546,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)[],
|
||||
@@ -1557,6 +1729,31 @@ export class LocalTable extends Table {
|
||||
return await this.inner.functionErrors(options);
|
||||
}
|
||||
|
||||
async functionColumnStatuses(
|
||||
column?: string,
|
||||
): Promise<FunctionColumnStatus[]> {
|
||||
return (await this.inner.functionColumnStatuses(
|
||||
column,
|
||||
)) as FunctionColumnStatus[];
|
||||
}
|
||||
|
||||
async functionColumnStatus(column: string): Promise<FunctionColumnStatus> {
|
||||
return (await this.inner.functionColumnStatus(
|
||||
column,
|
||||
)) as FunctionColumnStatus;
|
||||
}
|
||||
|
||||
async waitFresh(
|
||||
column: string,
|
||||
timeoutSeconds?: number,
|
||||
): Promise<FunctionColumnStatus> {
|
||||
validateNonNegativeInteger(timeoutSeconds, "timeoutSeconds");
|
||||
return (await this.inner.waitForFunctionColumn(
|
||||
column,
|
||||
timeoutSeconds,
|
||||
)) as FunctionColumnStatus;
|
||||
}
|
||||
|
||||
async refreshMaterializedView(
|
||||
sourceVersion?: number,
|
||||
full?: boolean,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-darwin-arm64",
|
||||
"version": "0.42.0-beta.10",
|
||||
"version": "0.42.0-beta.16",
|
||||
"os": ["darwin"],
|
||||
"cpu": ["arm64"],
|
||||
"main": "lancedb.darwin-arm64.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-arm64-gnu",
|
||||
"version": "0.42.0-beta.10",
|
||||
"version": "0.42.0-beta.16",
|
||||
"os": ["linux"],
|
||||
"cpu": ["arm64"],
|
||||
"main": "lancedb.linux-arm64-gnu.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-arm64-musl",
|
||||
"version": "0.42.0-beta.10",
|
||||
"version": "0.42.0-beta.16",
|
||||
"os": ["linux"],
|
||||
"cpu": ["arm64"],
|
||||
"main": "lancedb.linux-arm64-musl.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-x64-gnu",
|
||||
"version": "0.42.0-beta.10",
|
||||
"version": "0.42.0-beta.16",
|
||||
"os": ["linux"],
|
||||
"cpu": ["x64"],
|
||||
"main": "lancedb.linux-x64-gnu.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-x64-musl",
|
||||
"version": "0.42.0-beta.10",
|
||||
"version": "0.42.0-beta.16",
|
||||
"os": ["linux"],
|
||||
"cpu": ["x64"],
|
||||
"main": "lancedb.linux-x64-musl.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-win32-arm64-msvc",
|
||||
"version": "0.42.0-beta.10",
|
||||
"version": "0.42.0-beta.16",
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-win32-x64-msvc",
|
||||
"version": "0.42.0-beta.10",
|
||||
"version": "0.42.0-beta.16",
|
||||
"os": ["win32"],
|
||||
"cpu": ["x64"],
|
||||
"main": "lancedb.win32-x64-msvc.node",
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
"ann"
|
||||
],
|
||||
"private": false,
|
||||
"version": "0.42.0-beta.10",
|
||||
"version": "0.42.0-beta.16",
|
||||
"main": "dist/index.js",
|
||||
"exports": {
|
||||
".": "./dist/index.js",
|
||||
|
||||
+40
-10
@@ -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)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user